diff --git "a/4059.jsonl" "b/4059.jsonl" new file mode 100644--- /dev/null +++ "b/4059.jsonl" @@ -0,0 +1,1248 @@ +{"seq_id":"20390541827","text":"from pathlib import Path\n\nfrom config import BrokerConfig\n\n\ndef _build_bar_format() -> str:\n custom_left = \"{desc}: {n_fmt}/{total_fmt}\"\n custom_bar = \"{percentage:3.0f}% [{bar}]\"\n custom_info = \"{elapsed}<{remaining}, {rate_fmt}{postfix}\"\n\n return f\"{custom_left} {custom_bar} - {custom_info}\"\n\n\nIMPORTED_FULL_MODEL_PATH = Path(\n \"ml/imported/GNN_state_pred_het_full_StateGNNEncoderConvEdgeAttr_32ch.zip\"\n)\nIMPORTED_DICT_MODEL_PATH = Path(\n \"ml/imported/GNN_state_pred_het_dict_StateGNNEncoderConvEdgeAttr_32ch.zip\"\n)\n\nBASE_REPORT_DIR = Path(\"./report\")\nTABLES_LOG_FILE = BASE_REPORT_DIR / \"tables.log\"\nLEADERS_TABLES_LOG_FILE = BASE_REPORT_DIR / \"leaders.log\"\nEPOCH_BEST_DIR = BASE_REPORT_DIR / \"epochs_best\"\nAPP_LOG_FILE = Path(\"app.log\")\n\nTQDM_FORMAT_DICT = {\n \"unit\": \"game\",\n \"bar_format\": _build_bar_format(),\n \"dynamic_ncols\": True,\n}\n\n\nclass WebsocketSourceLinks:\n GET_WS = f\"http://{BrokerConfig.BROKER_HOST}:{BrokerConfig.BROKER_PORT}/{BrokerConfig.GET_WS_HANDLE}\"\n POST_WS = f\"http://{BrokerConfig.BROKER_HOST}:{BrokerConfig.BROKER_PORT}/{BrokerConfig.POST_WS_HANDLE}\"\n\n\nclass ResultsHandlerLinks:\n POST_RES = f\"http://{BrokerConfig.BROKER_HOST}:{BrokerConfig.BROKER_PORT}/{BrokerConfig.SEND_RES_HANDLE}\"\n GET_RES = f\"http://{BrokerConfig.BROKER_HOST}:{BrokerConfig.BROKER_PORT}/{BrokerConfig.RECEIVE_RES_HANDLE}\"\n\n\nDUMMY_INPUT_PATH = Path(\"ml/onnx/dummy_input.json\")\nBEST_MODEL_ONNX_SAVE_PATH = Path(\"ml/onnx/StateModelEncoder.onnx\")\nTEMP_EPOCH_INFERENCE_TIMES_DIR = Path(\".epoch_inference_times/\")\nBASE_NN_OUT_FEATURES_NUM = 8\n\nSERVER_WORKING_DIR = \"\"\n","repo_name":"emnigma/GNN_learner","sub_path":"common/constants.py","file_name":"constants.py","file_ext":"py","file_size_in_byte":1630,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"15"} +{"seq_id":"26432373292","text":"from dataset import CocoDataset\nfrom transformer_mapper import TransformerMapper\nimport torch\nfrom torch.utils.data import DataLoader\nfrom torch.utils.tensorboard import SummaryWriter\nimport torch.nn as nn\nfrom torch.optim import AdamW\nfrom tqdm import tqdm\nfrom transformers import BartForConditionalGeneration, BartTokenizerFast, get_linear_schedule_with_warmup, EvalPrediction\nimport evaluate\nfrom typing import Optional, Tuple\nimport argparse\nimport os\nimport sys\n\nclass MLP(nn.Module):\n def forward(self, x: torch.Tensor) -> torch.Tensor:\n return self.model(x)\n\n def __init__(self, sizes: Tuple[int, ...], bias=True, act=nn.Tanh):\n super(MLP, self).__init__()\n layers = []\n for i in range(len(sizes) - 1):\n layers.append(nn.Linear(sizes[i], sizes[i + 1], bias=bias))\n if i < len(sizes) - 2:\n layers.append(act())\n self.model = nn.Sequential(*layers)\n\nclass PrefixModel(nn.Module):\n def get_dummy_token(self, batch_size: int, device: torch.device) -> torch.Tensor:\n return torch.zeros(batch_size, self.prefix_length, dtype=torch.int64, device=device)\n\n def forward(self, tokens: torch.Tensor, prefix: torch.Tensor):\n prefix_projections = self.img_project(prefix).view(-1, self.prefix_length, self.bart_embedding_size)\n labels = torch.clone(tokens)\n labels[labels[:, :] == self.bart.config.pad_token_id] = -100\n out = self.bart(inputs_embeds=prefix_projections, labels=labels)\n return out\n \n\n def __init__(self, prefix_length: int, clip_length: int = 10, prefix_size: int = 768, num_layers: int = 8):\n super(PrefixModel, self).__init__()\n self.device = torch.device('cuda' if torch.cuda.is_available() else 'cpu')\n self.prefix_length = prefix_length\n self.bart = BartForConditionalGeneration.from_pretrained('facebook/bart-base').to(self.device)\n self.bart_embedding_size = self.bart.model.shared.weight.shape[1]\n self.img_project = MLP((prefix_size, (self.bart_embedding_size * prefix_length) // 2, self.bart_embedding_size * prefix_length))\n # self.img_project = TransformerMapper(prefix_size, self.bart_embedding_size, prefix_length, clip_length, num_layers)\n \nclass StaticBartPrefixModel(PrefixModel):\n \n def parameters(self):\n return self.img_project.parameters()\n \n def train(self, mode: bool = True):\n super(PrefixModel, self).train(mode)\n self.bart.eval()\n return self\n \ndef train(dataset: CocoDataset, val_dataset: CocoDataset, model: PrefixModel, lr: float = 2e-5, warmup_steps: int = 3000):\n\n device = torch.device('cuda' if torch.cuda.is_available() else 'cpu')\n batch_size = 16\n epochs = 3\n if not os.path.exists('./checkpoints'):\n os.makedirs('./checkpoints')\n model = model.to(device)\n model.train()\n optimizer = AdamW(model.parameters(), lr=lr)\n train_dataloader = DataLoader(dataset, batch_size=batch_size, shuffle=True, drop_last=True)\n val_dataloader = DataLoader(val_dataset, batch_size=batch_size, shuffle=True, drop_last=True)\n scheduler = get_linear_schedule_with_warmup(\n optimizer, num_warmup_steps=warmup_steps, num_training_steps=epochs * len(train_dataloader)\n )\n summary_writer = SummaryWriter(log_dir='./tensorboard')\n \n rouge = evaluate.load('rouge')\n bleu = evaluate.load('bleu')\n tokenizer = BartTokenizerFast.from_pretrained('facebook/bart-base')\n\n def compute_metrics(eval_prediction: EvalPrediction):\n predictions = eval_prediction.predictions\n labels = eval_prediction.label_ids\n\n pred_str = tokenizer.batch_decode(predictions, skip_special_tokens=True)\n labels_str = tokenizer.batch_decode(labels, skip_special_tokens=True)\n\n rouge_result = rouge.compute(predictions=pred_str, references=labels_str)\n rouge_result = {k: round(v * 100, 4) for k, v in rouge_result.items()}\n bleu_result = bleu.compute(predictions=pred_str, references=labels_str)\n return {\n **rouge_result, \n \"bleu\": round(bleu_result[\"bleu\"] * 100, 4), \n \"gen_len\": bleu_result[\"translation_length\"] / len(predictions)\n }\n \n for epoch in range(epochs):\n print(f\">>> Training epoch {epoch + 1}\")\n \n \n model.train()\n sys.stdout.flush()\n progress = tqdm(total=len(train_dataloader), desc='vit_bart_latest')\n for idx, (tokens, prefix) in enumerate(train_dataloader):\n model.zero_grad()\n tokens, prefix = tokens.to(device), prefix.to(device, dtype=torch.float32)\n outputs = model(tokens, prefix)\n loss = outputs.loss\n loss.backward()\n optimizer.step()\n scheduler.step()\n optimizer.zero_grad()\n progress.set_postfix({\"loss\": loss.item()})\n progress.update()\n progress.close()\n \n \n model.eval()\n valid_loss = 0\n predictions, labels = [], []\n progress = tqdm(total=len(val_dataloader), desc='evaluating')\n for idx, (tokens, prefix) in enumerate(val_dataloader):\n with torch.no_grad():\n tokens, prefix = tokens.to(device), prefix.to(device, dtype=torch.float32)\n outputs = model(tokens, prefix)\n loss = outputs.loss\n valid_loss += loss\n logits = outputs.logits.detach().cpu()\n predictions.extend(logits.argmax(dim=-1).tolist())\n tokens = tokens.detach().cpu()\n labels.extend(tokens.tolist())\n progress.update()\n progress.close()\n eval_prediction = EvalPrediction(predictions=predictions, label_ids=labels)\n metrics = compute_metrics(eval_prediction)\n print(f\"\\nEpoch: {epoch + 1}, Valid Loss: {valid_loss / len(val_dataloader)}, BLEU: {metrics['bleu']:.4f}, ROUGE-1: {metrics['rouge1']:.4f}, ROUGE-2: {metrics['rouge2']:.4f}, ROUGE-L: {metrics['rougeL']:.4f}\\n\")\n summary_writer.add_scalar(\"valid_loss\", valid_loss / len(val_dataloader))\n summary_writer.add_scalar(\"bleu\", metrics[\"bleu\"])\n summary_writer.add_scalar(\"rouge1\", metrics[\"rouge1\"])\n summary_writer.add_scalar(\"rouge2\", metrics[\"rouge2\"])\n summary_writer.add_scalar(\"rougeL\", metrics[\"rougeL\"])\n \n \n torch.save(\n model.state_dict(),\n os.path.join(\"./checkpoints\", f\"vit_bart_latest-{epoch + 1:03d}.pt\"),\n )\n return model\n\n\ndef main():\n parser = argparse.ArgumentParser();\n parser.add_argument('--prefix_length', type=int, default=10)\n parser.add_argument('--prefix_length_clip', type=int, default=10)\n parser.add_argument('--normalize_prefix', dest='normalize_prefix', action='store_true')\n args = parser.parse_args();\n dataset = CocoDataset(prefix_length=args.prefix_length, normalize_prefix=args.normalize_prefix)\n val_dataset = CocoDataset(prefix_length=args.prefix_length, normalize_prefix=args.normalize_prefix, type='val')\n model = PrefixModel(prefix_length=args.prefix_length, clip_length=args.prefix_length_clip)\n train(dataset, val_dataset, model)\n\nif __name__=='__main__':\n main()","repo_name":"nsivaku/vit-bart-prefix","sub_path":"train.py","file_name":"train.py","file_ext":"py","file_size_in_byte":7268,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"15"} +{"seq_id":"43165469777","text":"from xlutils.copy import copy # 只能修改xls后缀的文件格式,xlxs后缀格式在写入时会被破坏原文件\nimport os\nimport xlrd\n\ndef base_url(filename=None):\n return os.path.join(os.path.dirname(__file__), filename)\n\n\nwork = xlrd.open_workbook(base_url('test1.xls')) # 实例化文件对象\nprint(work)\n\nold_content = copy(work) # 复制未信息的xls\nws = old_content.get_sheet(0) # 通过索引获取sheet\nws.write(3, 3, 111) # ��改新的xls文件内容\nold_content.save(base_url('test1.xls')) # 修改后保存","repo_name":"zengwenhai/untitled1","sub_path":"day02/修改excel文件.py","file_name":"修改excel文件.py","file_ext":"py","file_size_in_byte":539,"program_lang":"python","lang":"zh","doc_type":"code","stars":0,"dataset":"github-code","pt":"15"} +{"seq_id":"22134175436","text":"#http://rasbt.github.io/mlxtend/user_guide/plotting/plot_decision_regions/\nfrom __future__ import division\nimport numpy\nimport os\nfrom sklearn import svm\nfrom collections import deque\nimport matplotlib.pyplot as plt\nfrom mlxtend.plotting import plot_decision_regions\nimport numpy as np\n\ndata = np.loadtxt(open('result.csv', 'rb'), delimiter=',')\n\n#sfe,ssip,rfip\nsfe = 0\nssip = 1\nrfip = 2\n\n\n\n\n\n#Graph1 sfe & ssip\nX = data[:, [sfe,ssip]]\ny = data[:, 3]\nclf = svm.SVC()\nclf.fit(X, y)\n# Plot Decision Region using mlxtend's awesome plotting function\nfig = plt.figure(figsize=(10,8))\nfig = plot_decision_regions(X=X,\n y=y.astype(int),\n clf=clf,\n legend=2)\nplt.title('SVM DDoS - Decision Region Boundary', size=16)\nplt.xlabel('Speed of Flow Entry')\nplt.ylabel('Speed of Source IP')\nplt.savefig(\"svm_graph1.png\")\n\n\n\n\n#Graph1 sfe & rfip\nX = data[:, [sfe,rfip]]\ny = data[:, 3]\nclf = svm.SVC()\nclf.fit(X, y)\n# Plot Decision Region using mlxtend's awesome plotting function\nfig = plt.figure(figsize=(10,8))\nfig = plot_decision_regions(X=X,\n y=y.astype(int),\n clf=clf,\n legend=2)\nplt.title('SVM DDoS - Decision Region Boundary', size=16)\nplt.xlabel('sfe')\nplt.ylabel('rfip')\nplt.savefig(\"svm_graph2.png\")\n","repo_name":"vishalsingh45/SDN-DDOS-Detection-and-Mitigation-using-ML-and-Statistical-methods","sub_path":"analysis/graph.py","file_name":"graph.py","file_ext":"py","file_size_in_byte":1319,"program_lang":"python","lang":"en","doc_type":"code","stars":41,"dataset":"github-code","pt":"15"} +{"seq_id":"1417463232","text":"from django.apps import apps\nfrom django.contrib.auth import logout\nfrom django.contrib.auth.decorators import login_required\nfrom django.shortcuts import render, redirect\n\nSkin = apps.get_model(\"game\", \"Skin\")\nUserSkin = apps.get_model(\"game\", \"UserSkins\")\n\n\ndef homepage(request):\n return render(request, 'index.html')\n\n\n@login_required\ndef shop(request):\n skins = {}\n for skin in Skin.objects.all():\n skins[skin.slang] = skin.path_png\n\n userskins = list(map(lambda s: s.skin.slang, UserSkin.objects.filter(profile=request.user.user_profile)))\n\n return render(request, 'shop.html', {\"skin_list\": skins, \"user_skins\": userskins})\n\n\n@login_required\ndef select_skin(request, skin):\n userskins = list(map(lambda s: s.skin.slang, UserSkin.objects.filter(profile=request.user.user_profile)))\n if skin in userskins:\n request.user.user_profile.current_skin = skin\n request.user.user_profile.save()\n return redirect(shop)\n\n\n@login_required\ndef pay_mobile(request, skin):\n data = {'value': 1, 'skin': skin}\n return render(request, 'pay_mobile.html', data)\n\n\ndef pay_qrcode(request, skin):\n data = {'value': 1, 'skin': skin}\n return render(request, 'pay_qrcode.html', data)\n\n\n@login_required\ndef logout_view(request):\n logout(request)\n return redirect(homepage)\n","repo_name":"joaopat98/igot.io","sub_path":"server/server/views.py","file_name":"views.py","file_ext":"py","file_size_in_byte":1316,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"15"} +{"seq_id":"13006327741","text":"import six\nimport yaml\nimport morph\nimport json\n\n#------------------------------------------------------------------------------\ndef _writeObject(obj, out, color=True, level=0, indent=' '):\n def _write(obj, level):\n curdent = indent * level\n if morph.isseq(obj):\n out.write('[\\n')\n last = len(obj)\n for idx, val in enumerate(obj):\n out.write(curdent)\n out.write(indent)\n _write(val, level=level + 1)\n if idx + 1 < last:\n out.write(',')\n out.write('\\n')\n out.write(curdent)\n out.write(']')\n return\n if morph.isdict(obj):\n out.write('{\\n')\n last = len(obj)\n for idx, (key, val) in enumerate(obj.items()):\n out.write(curdent)\n out.write(indent)\n _write(key, level=level + 1)\n out.write(': ')\n _write(val, level=level + 1)\n if idx + 1 < last:\n out.write(',')\n out.write('\\n')\n out.write(curdent)\n out.write('}')\n return\n out.write(json.dumps(obj))\n return _write(obj, level)\n\n#------------------------------------------------------------------------------\ndef prettify(input, output=None, strict=True, color=True):\n stream = output or six.StringIO()\n if morph.isstr(input) or isinstance(input, six.binary_type):\n data = input\n else:\n data = input.read()\n try:\n ydata = yaml.load(data)\n except Exception as err:\n if strict:\n raise\n if output:\n output.write(data)\n return\n return data\n _writeObject(ydata, stream, color=True)\n if output:\n return\n return stream.getvalue()\n\n#------------------------------------------------------------------------------\n# end of $Id$\n#------------------------------------------------------------------------------\n","repo_name":"metagriffin/proxylog","sub_path":"proxylog/pyaml.py","file_name":"pyaml.py","file_ext":"py","file_size_in_byte":1762,"program_lang":"python","lang":"en","doc_type":"code","stars":3,"dataset":"github-code","pt":"15"} +{"seq_id":"3508411088","text":"import requests\nimport yaml\n\n\nBASE_URL = \"https://10.10.20.48/restconf\"\n\ndef main():\n requests.packages.urllib3.disable_warnings()\n #Interface path to get interfaces\n interface_path = \"/data/ietf-interfaces:interfaces\"\n post_headers = {\n \"Content-Type\": \"application/yang-data+json\",\n \"Accept\": \"application/yang-data+json, application/yang-data.errors+json\",\n }\n\n auth = (\"developer\", \"C1sco12345\")\n with open(r'C:\\Users\\xxenc\\OneDrive\\Documents\\enauto_coding\\venv\\enauto\\Python\\interfacedata.yml', \"r\") as handle:\n config_state = yaml.safe_load(handle)\n response = requests.post(\n BASE_URL + interface_path,\n headers=post_headers,\n json=config_state,\n auth=auth,\n verify=False\n )\n if response.status_code == 201:\n print(f\"Added interface successfully\")\n elif response.status_code == 409:\n print(f\"Interface already exists!\")\n else:\n print(f\"Unexpected {response.status_code}\")\n\nif __name__ == \"__main__\":\n main()","repo_name":"CamelJake/enauto","sub_path":"Python/restconf_editinterface.py","file_name":"restconf_editinterface.py","file_ext":"py","file_size_in_byte":1030,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"15"} +{"seq_id":"8948120927","text":"import math\nimport numpy as np\n\nfrom scipy import sparse\nfrom sklearn.utils.extmath import safe_sparse_dot\n\n\ndef mean_squared_error(y_true, y_pred):\n \"\"\"\n Returns the mean squared error between y_true and y_pred\n\n :param y_true:\n :param y_pred:\n :return:\n \"\"\"\n mse = np.mean(np.power(y_true - y_pred, 2))\n return mse\n\n\ndef calculate_variance(X):\n \"\"\"\n\n :param X:\n :return:\n \"\"\"\n mean = np.ones(np.shape(X)) * X.mean(0)\n n_samples = np.shape(X)[0]\n variance = (1 / n_samples) * np.diag((X - mean).T.dot(X - mean))\n return variance\n\n\ndef calculate_std_dev(X):\n \"\"\"\n Calculate the standard deviations of the features in dataset X\n \"\"\"\n std_dev = np.sqrt(calculate_variance(X))\n return std_dev\n\n\ndef euclidean_distance(x1, x2):\n \"\"\"\n :param x1: ndarray of shape (n_samples1, n_features)\n :param x2:ndarray of shape (n_samples2, n_features)\n :return:\n \"\"\"\n distance = np.sqrt(np.sum(np.power(x1 - x2, 2), axis=0))\n return distance\n\n\ndef accuracy_score(y, y_pred):\n \"\"\"\n Compare ground truth y to predictions y_pred and return the accuracy\n\n :param y: ndarray of shape (n_samples, )\n Target values\n\n :param y_pred: ndarray of shape (n_samples, )\n Predicted values\n\n :return: float\n Accuracy of comparison between y and y_pred\n \"\"\"\n accuracy = np.sum(y == y_pred, axis=0) / len(y)\n return accuracy\n\n\ndef calculate_covariance_matrix(X, Y=None):\n \"\"\"\n\n :param X:\n :param Y:\n :return:\n \"\"\"\n if Y is None:\n Y = X\n n_samples = np.shape(X)[0]\n covariance_matrix = (1 / (n_samples - 1)) * (X - X.mean(axis=0)).T.dot(Y - Y.mean(axis=0))\n\n return np.array(covariance_matrix, dtype=float)\n\n\ndef calculate_correlation_matrix(X, Y=None):\n \"\"\"\n Calculate the correlation matrix for the dataset X\n \"\"\"\n if Y is None:\n Y = X\n n_samples = np.shape(X)[0]\n covariance = (1 / n_samples) * (X - X.mean(0)).T.dot(Y - Y.mean(0))\n std_dev_X = np.expand_dims(calculate_std_dev(X), 1)\n std_dev_y = np.expand_dims(calculate_std_dev(Y), 1)\n correlation_matrix = np.divide(covariance, std_dev_X.dot(std_dev_y.T))\n\n return np.array(correlation_matrix, dtype=float)\n\n\ndef logsumexp(arr, axis=0):\n \"\"\"\n Computes the sum of arr assuming arr is in the log domain.\n Returns log(sum(exp(arr))) while minimizing the possibility of over/underflow.\n \"\"\"\n arr = np.rollaxis(arr, axis)\n # Use the max to normalize, as with the log this is what accumulates the less errors\n vmax = arr.max(axis=0)\n out = np.log(np.sum(np.exp(arr - vmax), axis=0))\n out += vmax\n return out\n\n\ndef rescale_data(X, y, sample_weight):\n \"\"\"\n Rescale data sample-wise by square root of sample weight\n :param X:\n :param y:\n :param sample_weight:\n :return:\n \"\"\"\n n_samples = X.shape[0]\n sample_weight = np.asarray(sample_weight)\n if sample_weight.ndim == 0:\n sample_weight = np.full(n_samples, sample_weight, dtype=sample_weight.dtype)\n sample_weight = np.sqrt(sample_weight)\n sw_matrix = sparse.dia_matrix((sample_weight, 0), shape=(n_samples, n_samples))\n X = safe_sparse_dot(sw_matrix, X)\n y = safe_sparse_dot(sw_matrix, y)\n\n return X, y\n\n\ndef soft_thresholding_operator(self, x, lambda_):\n if x > 0 and lambda_ < abs(x):\n return x - lambda_\n elif x < 0 and lambda_ < abs(x):\n return x + lambda_\n else:\n return 0.0\n","repo_name":"juan190199/ML-Zero-To-Hero","sub_path":"utils/data_operation.py","file_name":"data_operation.py","file_ext":"py","file_size_in_byte":3456,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"15"} +{"seq_id":"7890415800","text":"from flask import Flask, render_template\nimport json\nimport os\n\napp = Flask(__name__)\n\n@app.route('/')\ndef home():\n all_images = []\n with open('dungeons.json') as all_dungeons:\n data = json.load(all_dungeons)\n for dungeon in data:\n all_images.append(data[dungeon][\"image\"])\n return render_template('home.html', all_images=all_images)\n\n@app.route('/dungeon/')\ndef dungeon(dungeon):\n with open('dungeons.json') as all_dungeons:\n dungeon = dungeon.replace(\"_\", \" \").replace(\".jpg\", \"\")\n data = json.load(all_dungeons)\n data = data[dungeon]\n print(data)\n image = data[\"image\"]\n return render_template('dungeon.html', image=image, dungeon=dungeon, data=data)\n\n@app.route('/about')\ndef about():\n return render_template('about.html')\n\nif __name__ == '__main__':\n app.secret_key = \"as\"\n app.run(debug=True)\n","repo_name":"netn10/magic-dungeon-tracker","sub_path":"app.py","file_name":"app.py","file_ext":"py","file_size_in_byte":899,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"15"} +{"seq_id":"15107586182","text":"from collections import deque\n\ndx = [0, 0, -1, 1]\ndy = [-1, 1, 0, 0]\n\n\ndef solution(rectangle, characterX, characterY, itemX, itemY):\n for rect in rectangle:\n for i in range(4):\n rect[i] *= 2\n characterX *= 2\n characterY *= 2\n itemX *= 2\n itemY *= 2\n visited = [[False] * 110 for _ in range(110)]\n result = 1000\n\n q = deque([[characterX, characterY, 0]])\n\n while q:\n curX, curY, count = q.popleft()\n visited[curX][curY] = True\n\n if curX == itemX and curY == itemY and result > count:\n result = count\n continue\n\n for i in range(4):\n nextX = curX + dx[i]\n nextY = curY + dy[i]\n\n if not (0 <= nextX <= 100 and 0 <= nextY <= 100):\n continue\n\n if visited[nextX][nextY]:\n continue\n\n isEdge = False\n\n for rect in rectangle:\n x_min, y_min, x_max, y_max = rect\n\n if (nextX < x_min or nextX > x_max) or (nextY < y_min or nextY > y_max):\n continue\n\n if x_min < nextX < x_max and y_min < nextY < y_max:\n isEdge = False\n break\n\n isEdge = True\n\n if isEdge:\n q.append([nextX, nextY, count + 1])\n\n return result // 2\n","repo_name":"sdh20282/Algorithm","sub_path":"Programmers/Level_3/아이템 줍기.py","file_name":"아이템 줍기.py","file_ext":"py","file_size_in_byte":1338,"program_lang":"python","lang":"en","doc_type":"code","stars":2,"dataset":"github-code","pt":"15"} +{"seq_id":"26778869501","text":"from fastapi import APIRouter, Depends\nfrom sqlalchemy.orm import Session\nfrom db import get_db\nfrom models import Welayatlar\nfrom returns import Returns\nimport json\n\nwelayat_router = APIRouter()\n\n@welayat_router.get(\"/get-welayat\")\nasync def get_welayat(db: Session = Depends(get_db)):\n result = db.query(\n Welayatlar.id,\n Welayatlar.name,\n ).all()\n \n if result:\n return Returns.object(result)\n f = open('json/welayatlar.json')\n data = json.load(f)\n for i in data:\n name_json: str = i.get('name')\n new_add = Welayatlar(name = name_json)\n db.add(new_add)\n db.commit()\n db.refresh(new_add)\n if not new_add:\n return Returns.NOT_INSERTED\n f.close()\n result = db.query(\n Welayatlar.id,\n Welayatlar.name,\n ).all()\n if result:\n return Returns.object(result)\n else:\n return Returns.BODY_NULL","repo_name":"olympusss/ishgarlerBolumi_api","sub_path":"routers/welayatlar.py","file_name":"welayatlar.py","file_ext":"py","file_size_in_byte":922,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"15"} +{"seq_id":"1763268302","text":"# Lights config\nMAX_ACC = 30\nMAX_VEL = 30\nNUM_LIGHTS = 2000\nLIGHT_SIZE = 4\nLIGHTS_MASS = 100\nPOINTER_MASS = 10000\nG = 6.67 * 10 ** -4\nMASS_PRODUCT = G * LIGHTS_MASS * POINTER_MASS\n\n# Window config\nWINDOW_SIZE = WIDTH, HEIGHT = 1080, 720\nBACKGROUND = 0, 0, 0\n","repo_name":"watxaut/pylights","sub_path":"pylights/config.py","file_name":"config.py","file_ext":"py","file_size_in_byte":258,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"15"} +{"seq_id":"23851926045","text":"import logging\n\nfrom django.core.management import BaseCommand\nfrom papermerge.core.backup_restore import (\n _can_restore,\n _is_valid_user,\n restore_documents\n)\n\nlogger = logging.getLogger(__name__)\n\n\nclass Command(BaseCommand):\n help = \"\"\"\n Restore all Documents and their folder structure from an archive.\n If you don't pass a username with --user you will be asked for it.\n\n By default will trigger OCR for each imported document.\n Use --skip-ocr if you wish to OCR documents later.\n \"\"\"\n\n def add_arguments(self, parser):\n\n parser.add_argument(\n '--user', type=str,\n help=\"user (username of) the restored documents should belong to\",\n default=None\n )\n # 1. Very useful option\n # during tests/development/maintenance of this module\n # 2. In case archive is full backup (i.e. includes OCR text info)\n # can be skipped (that is the point of full backup - not to perform\n # OCR operation again).\n parser.add_argument(\n 's',\n '--skip-ocr',\n action='store_true',\n help=\"will skip \",\n )\n\n parser.add_argument('location', nargs='?', type=str)\n\n def handle(self, *args, **options):\n\n skip_ocr = options.get('skip_ocr')\n\n if options.get('location') is None:\n logger.error(\"Please add the path to your backup.tar\")\n else:\n with open(options.get('location'), 'rb') as restore_file:\n if _can_restore(restore_file):\n if options.get('user') is None:\n username = input(\"Username:\")\n else:\n username = options.get('user')\n logging.info(\n \"Archive can be handled.\"\n \"Please enter the user (username of) that should\"\n \" own the restored documents.\"\n )\n\n if _is_valid_user(username):\n restore_documents(\n restore_file=restore_file,\n username=username,\n skip_ocr=skip_ocr\n )\n else:\n logging.error(\"User %s was not valid\", username)\n else:\n logging.error(\n \"Archive cannot be restored because of\"\n \" version mismatch.\"\n )\n","repo_name":"wetdesert/papermerge","sub_path":"papermerge/core/management/commands/restore.py","file_name":"restore.py","file_ext":"py","file_size_in_byte":2537,"program_lang":"python","lang":"en","doc_type":"code","dataset":"github-code","pt":"15"} +{"seq_id":"26272987911","text":"import pygame\n\n\nclass Cursor(object):\n\n def __init__(self):\n\n self.rect = pygame.rect.Rect(0, 0, 6, 6)\n self.puntero = pygame.rect.Rect(0, 0, 1, 1)\n pygame.mouse.set_visible(False)\n\n def update(self):\n\n self.rect.x, self.rect.y = pygame.mouse.get_pos()\n self.puntero.x, self.puntero.y = self.rect.centerx, self.rect.centery\n\n def changeState(self, matriz):\n\n for fila in matriz:\n for cell in fila:\n if pygame.mouse.get_pressed()[0]:\n if self.puntero.colliderect(cell.rect):\n\n cell.estado = True\n\n if pygame.mouse.get_pressed()[2]:\n\n if self.puntero.colliderect(cell.rect):\n\n cell.estado = False\n","repo_name":"damasko/vida_pygame","sub_path":"cursor.py","file_name":"cursor.py","file_ext":"py","file_size_in_byte":771,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"15"} +{"seq_id":"229992507","text":"import docker\nimport json\nimport pytest\nimport redis\n\nimport hydra.cluster.haproxy as haproxy\nfrom hydra.cluster import HydraCluster\nfrom tests.conftest import random_str\n\n\n@pytest.fixture\ndef nodes(mocker):\n n1 = mocker.MagicMock()\n n1.name = 'node-1.test'\n n1.exec_run = mocker.MagicMock(return_value=(0, random_str(),))\n\n n2 = mocker.MagicMock()\n n2.name = 'node-2.test'\n n2.exec_run = n1.exec_run\n\n return [n1, n2]\n\n\ndef test_hydra_cluster(mocker):\n mocker.patch.object(docker, docker.from_env.__name__)\n clstr = HydraCluster()\n\n assert clstr._node is None\n assert clstr._network is None\n assert clstr._haproxy is None\n assert clstr._service_registry is None\n assert clstr._docker_client is not None\n\n\ndef test_hydra_cluster_node(mocker):\n mocker.patch.object(docker, docker.from_env.__name__)\n clstr = HydraCluster()\n\n assert clstr._node is None\n assert clstr.node is not None\n assert clstr._node is not None\n\n\ndef test_hydra_cluster_name(mocker):\n mocker.patch.object(docker, docker.from_env.__name__)\n clstr = HydraCluster()\n\n assert clstr.name is not None\n\n\ndef test_hydra_cluster_network(mocker):\n clstr = sut(mocker, [], [])\n\n assert clstr._network is None\n assert clstr.network is not None\n assert clstr._network is not None\n\n clstr._docker_client.networks.get.assert_called_once_with(clstr.network.name)\n\n\ndef test_hydra_cluster_nodes(mocker, nodes):\n clstr = sut(mocker, nodes, [])\n\n assert len(list(clstr.nodes)) == 2\n clstr._docker_client.containers.list.assert_called_once_with(\n **dict(filters={'network': clstr.name})\n )\n\n\ndef test_hydra_cluster_node_state(mocker, nodes):\n clstr = sut(mocker, nodes, [])\n\n node_state = list(clstr.node_state)\n\n assert len(node_state) == 2\n assert node_state[0].get('name') in [n.name for n in nodes]\n assert node_state[0].get('ip') is not None\n assert node_state[1].get('name') in [n.name for n in nodes]\n assert node_state[1].get('ip') is not None\n assert node_state[0].get('name') != node_state[1].get('name')\n assert node_state[0].get('ip') != node_state[1].get('ip')\n\n\ndef test_hydra_cluster_service_registry(mocker):\n mocker.patch.object(redis, redis.Redis.__name__)\n mocker.patch.object(\n HydraCluster,\n HydraCluster.network.fget.__name__,\n new_callable=mocker.PropertyMock\n )\n\n clstr = HydraCluster()\n\n assert clstr._service_registry is None\n assert clstr.service_registry is not None\n assert clstr._service_registry is not None\n\n\ndef test_hydra_cluster_haproxy(mocker):\n mocker.patch.object(\n HydraCluster,\n HydraCluster.network.fget.__name__,\n new_callable=mocker.PropertyMock\n )\n\n clstr = HydraCluster()\n\n assert clstr._haproxy is None\n assert clstr.haproxy is not None\n assert clstr._haproxy is not None\n\n\ndef test_hydra_cluster_services(mocker):\n service = {random_str(): random_str()}\n mget_ret_val = [json.dumps(service)]\n mocker.patch.object(\n HydraCluster,\n HydraCluster.service_registry.fget.__name__,\n new_callable=mocker.PropertyMock,\n return_value=mocker.MagicMock(\n mget=mocker.MagicMock(return_value=mget_ret_val),\n keys=mocker.MagicMock(return_value=[])\n )\n )\n\n clstr = HydraCluster()\n services = clstr.services\n\n assert list(services) == [service]\n\n\ndef test_hydra_cluster_next_node_name(mocker, nodes):\n clstr = sut(mocker, nodes, [])\n\n assert clstr.next_node_name() == 'node-3.test'\n\n\ndef test_hydra_cluster_get_free_nodes(mocker, nodes):\n haproxy_nodes = [dict(svname='node1')]\n\n clstr = sut(mocker, nodes, haproxy_nodes)\n nodes = list(clstr.get_free_nodes(random_str()))\n\n assert len(nodes) == 1\n assert nodes[0].name in [n.name for n in nodes]\n\n\ndef test_hydra_cluster_create_node(mocker, nodes):\n mocker.patch.object(\n HydraCluster,\n HydraCluster.node_down_monitor.__name__\n )\n\n expected_node_name = 'node-3.test'\n expected_network_name = 'test'\n\n clstr = sut(mocker, nodes, [])\n\n node = clstr.create_node()\n\n clstr._docker_client.containers.run.assert_called_once_with(\n HydraCluster.NODE_IMAGE,\n **dict(\n name=expected_node_name,\n hostname=expected_node_name,\n privileged=True,\n network=expected_network_name,\n tty=True,\n stdin_open=True,\n detach=True,\n remove=True\n )\n )\n clstr.node_down_monitor.assert_called_once_with(\n node.name,\n [clstr.migrate_services],\n HydraCluster.NODE_DOWN_EVENTS\n )\n\n\ndef test_hydra_cluster_deploy_service(mocker, nodes):\n haproxy_nodes = [dict(svname='node1'), dict(svname='node2')]\n\n clstr = sut(mocker, nodes, haproxy_nodes)\n\n srv_name = random_str()\n img_name = random_str()\n srv_port = 10000\n node_port = 10001\n srv_cfg = clstr.deploy_service(\n srv_name,\n img_name,\n node_port,\n srv_port\n )\n\n assert srv_cfg.get('name') == srv_name\n assert srv_cfg.get('endpoints')[0].endswith(srv_name)\n assert len(srv_cfg.get('nodes')) == 1\n assert srv_cfg.get('nodes')[0].get('name') in [n.name for n in nodes]\n assert srv_cfg.get('nodes')[0].get('service_image') == img_name\n assert srv_cfg.get('nodes')[0].get('node_port') == node_port\n assert srv_cfg.get('nodes')[0].get('service_port') == srv_port\n\n\ndef sut(mocker, docker_nodes: list, haproxy_nodes: list, cluster_name: str = 'test') -> HydraCluster:\n # Mock docker\n mock_docker = mocker.MagicMock()\n mock_docker.containers = mocker.MagicMock()\n mock_node = mocker.MagicMock(\n attrs=dict(\n NetworkSettings=dict(\n Networks={\n cluster_name: dict(IPAddress=random_str())\n }\n )\n )\n )\n mock_node.name = cluster_name\n mock_docker.containers.get = lambda x: mock_node\n mock_docker.containers.list = mocker.MagicMock(return_value=docker_nodes)\n mock_docker.networks = mocker.MagicMock()\n mock_network = mocker.MagicMock()\n mock_network.name = cluster_name\n mock_docker.networks.get = mocker.MagicMock(return_value=mock_network)\n\n # Mock Redis\n mock_redis = mocker.MagicMock()\n mock_redis.get = mocker.MagicMock(return_value={'name': random_str(), 'nodes': docker_nodes})\n\n # Mock HAProxy\n mocker.patch.object(\n haproxy.HAProxy,\n haproxy.HAProxy.get_free_nodes.__name__,\n return_value=iter(haproxy_nodes)\n )\n mocker.patch.object(\n haproxy.HAProxy,\n haproxy.HAProxy.url.fget.__name__,\n new_callable=mocker.PropertyMock,\n return_value=random_str()\n )\n mocker.patch.object(\n haproxy.HAProxy,\n haproxy.HAProxy.register_service.__name__\n )\n\n clstr = HydraCluster()\n clstr._docker_client = mock_docker\n clstr._service_registry = mock_redis\n return clstr","repo_name":"ragnarpa/hydra","sub_path":"hydra-cluster/tests/hydra/cluster/test_cluster.py","file_name":"test_cluster.py","file_ext":"py","file_size_in_byte":6977,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"15"} +{"seq_id":"32042890060","text":"from typing import Union\nfrom fastapi import FastAPI\nfrom funciones import developer_reviews_analysis_,developer_,best_developer_year_ ,userdata_,recomendacion_usuario_#,UserForGenre_\nfrom fastapi.responses import JSONResponse \n\napp= FastAPI()\n\"\"\"\n@app.get(\"/\")\nasync def root():\n return {\"message\":\"Hello world\"}\n\n@app.get(\"/items/{item_id}\")\ndef read_item (item_id: int, q: Union[str, None] = None):\n return {\"item_id\": item_id, \"q\": q}\n\"\"\"\n#funcion N1\n\n@app.get(\"/developer/{desarrollador}\")\nasync def developer(desarrollador: str):\n contenido_Free = developer_(desarrollador)\n # Devolver el resultado como respuesta JSON\n return JSONResponse(contenido_Free.to_dict(orient=\"records\"))\n\n#funcion N2\n\n@app.get(\"/userdata/{Userd_id}\")\nasync def userdata( User_id : str ):\n usuario = userdata_(User_id)\n return usuario\n\n#funcion N3\n# La funcion N3 no me funciona en render, debido al data set de item. Diferente que de manera local si me funciona,\n# ya que, disponemos de mas memoria ram\n\"\"\"\n@app.get(\"/UserForGenre/{genero}\")\nasync def UserForGenre(genero: str):\n Horas_por_año = UserForGenre_(genero)\n return Horas_por_año\n\"\"\"\n#funcion N4\n\n@app.get(\"/best_developer_year/{year}\")\nasync def Best_developer_year(year: str):\n try:\n year_int = int(year) # Convertir el año a un entero\n result2 = best_developer_year_(year_int)\n return result2\n except Exception as e:\n return {\"error\": str(e)}\n\n#funcion N5\n\n@app.get(\"/developer_reviews_analysis/{developer}\")\nasync def developer_reviews_analysis(developer: str):\n Reseñas = developer_reviews_analysis_(developer)\n return Reseñas\n\n#funcion N6 ML\n\n@app.get(\"/recomendacion_usuario/{id_usuario}\")\nasync def recomendacion_usuario(id_usuario: str):\n recomendaciones = recomendacion_usuario_(id_usuario)\n return recomendaciones\n\n","repo_name":"Marianoe155/Proyecto-Individual-ML_OPS","sub_path":"main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":1865,"program_lang":"python","lang":"es","doc_type":"code","stars":0,"dataset":"github-code","pt":"15"} +{"seq_id":"29806381015","text":"#!/usr/bin/python2.7\n# -!- coding: utf-8 -!-\n# usage: freeling.py\n\nfrom __future__ import unicode_literals\n\nimport os, sys\nimport re\nimport pymystem3\n\n\"\"\"\nThis is the recommended way to check against part of speech. Add a lambda-function for the desired POS\nand use it in your code in the following way: pos_filters['desired_pos'](word), where word is a list\n\"\"\"\npos_filters = {\n 'noun': lambda x: x.tag['pos'] in ['S', 'NP', 'PP'],\n 'adj': lambda x: x.tag['pos'] in ['A', 'ANUM'],\n 'properNoun': lambda x: len(x.tag['gr'] & frozenset([u'имя', u'фам'])) > 0,\n 'pronoun': lambda x: x.tag['pos'] == ['SPRO'],\n 'comma': lambda x: x.wordform == u',',\n 'prep': lambda x: x.tag['pos'] == 'PR',\n 'firstName': lambda x: x.tag['pos'] == 'S' and u'имя' in x.tag['gr'],\n 'secondName': lambda x: x.tag['pos'] in ['A', 'S'] and u'фам' in x.tag['gr'],\n 'middleName': lambda x: x.tag['pos'] == 'S' and u'отч' in x.tag['gr'],\n 'conj': lambda x: x.tag['pos'] == 'CONJ' and x.wordform in [u'и', u'а', u'но'],\n 'quant': lambda x: x.tag['pos'] == 'NUM',\n}\n\ngram_values = {\n 'number': frozenset(['ед', 'мн']),\n 'gender': frozenset(['муж', 'сред', 'жен']),\n 'case': frozenset(['им', 'род', 'дат', 'вин', 'твор', 'пр', 'парт', 'местн', 'зват'])\n}\n\ndef same_grammemmes(name, words):\n if name not in gram_values:\n return True\n\n for feature in gram_values[name]:\n if all(feature in item.tag['gr'] for item in words):\n return True\n return False\n\n\n\"\"\"\nThis is the list of groups which we are trying to extract. To disable any of the groups, just comment it\n\"\"\"\nagreement_filters = {\n 'adjNoun': lambda adj, noun: {'pos': 'NP', 'gr': noun.tag['gr']} if (\n pos_filters['adj'](adj) and pos_filters['noun'](noun) and\n same_grammemmes('number', (adj, noun)))\n else None,\n\n 'quantNoun': lambda quant, noun: {'pos': 'NP', 'gr': noun.tag['gr']} if (\n pos_filters['quant'](quant) and pos_filters['noun'](noun) and\n same_grammemmes('number', (quant, noun)))\n else None,\n\n 'name': lambda name, surname: {'pos': 'NP', 'gr': name.tag['gr']} if (\n pos_filters['firstName'](name) and (pos_filters['secondName'](surname) or pos_filters['middleName'](surname)) and\n same_grammemmes('number', (name, surname)) and same_grammemmes('case', (name, surname)))\n else None\n}\n\nnp_conjunction = lambda word1, conj, word2: {'pos': 'NP', 'gr': [u'мн']} if (\n pos_filters['noun'](word1) and pos_filters['noun'](word2) and pos_filters['conj'](conj)) else None\n\n\ndef load():\n parser = pymystem3.Mystem()\n return lambda text: parser.analyze(text)\n\ntokens_to_skip = ['', ' ', '\\n', '\\r', '\\t', '«', '»', '\"']\nrx_grammemmes_splitter = re.compile('[^А-ЯЁа-яёA-Za-z]', re.UNICODE)\n\ndef tag_text(text, analyzer):\n ret = []\n text_part = text[:]\n prev_offset = 0\n\n for word in analyzer(text):\n if word['text'].strip(' ') in tokens_to_skip:\n continue\n word_info = word['analysis'][0] if 'analysis' in word and len(word['analysis']) > 0 else None\n new_word = type(b'Word', (object,),\n {'wordform': word['text'],\n 'lemma': word_info['lex'] if word_info else word['text'],\n 'tag': word_info['gr'] if word_info else 'PUNCT',\n 'prob': 1.0,\n 'offset': prev_offset + text_part.find(word['text']),\n 'length': len(word['text']),\n 'type': 'word'})\n\n\n grammemmes = rx_grammemmes_splitter.split(new_word.tag)\n new_word.tag = {'pos': grammemmes[0], 'gr': frozenset(grammemmes[1:])}\n ret.append(new_word)\n\n text_part = text[new_word.offset + new_word.length:]\n prev_offset = new_word.offset + new_word.length\n\n return ret","repo_name":"max-ionov/anaphora-ru","sub_path":"lemmatizer-filters/mystem.py","file_name":"mystem.py","file_ext":"py","file_size_in_byte":3906,"program_lang":"python","lang":"en","doc_type":"code","stars":2,"dataset":"github-code","pt":"15"} +{"seq_id":"37331575318","text":"# -*- coding: utf-8 -*-\n\"\"\"\nCreated on Fri Oct 22 16:57:07 2021\n\n@author: qizhe\n\"\"\"\n\nclass Solution:\n def numDecodings(self, s: str) -> int:\n \"\"\"\n 读题:\n 1、通过了不高,然后看了内容,肯定是有一些极端测试例子,所以这个不要急着测试,一定要完善测试例子\n 2、非常像那个IP地址的题,典型的回溯\n \n 测试:\n 1、15min写完,样例都通过了,结果超时了,不通过\n 2、那么就需要剪枝\n 3、他要的好像只是种类,应该是动态规划吧?只需要连乘就可以了\n 4、吃了个饭,好像想出来了优化DP方法\n 5、多次测试失败,终于成功了 性能还不好\n \n 答案:\n 1、真的是,动态规划,他们写的代码好简单啊\n 2、思路差不多,答案的思路更清楚一些\n \n 教训:\n 1、看到回溯,要想一下复杂度以及题目要求,看是不是动态规划就足够\n 2、动态规划不要急着直接写优化的思路,先写空间复杂度高的,容易实现\n \n \"\"\"\n # def __dfs(s,begin,length):\n # if begin == length:\n # return 1\n # result = 0\n # for i in range(begin,min(length,begin + 2)):\n # if 1 <= int(s[begin:i+1]) <= 26 and s[begin] !='0':\n # result += __dfs(s,i+1,length)\n # return result\n # return __dfs(s,0,len(s))\n dplast = 1\n dpnow = 1\n N = len(s)\n if int(s[0]) == 0:\n return 0 \n i = 0\n while i < N:\n # print(s,i,dplast,dpnow)\n if i > 0 and 1 <= int(s[i-1:i+1]) <= 26 and int(s[i-1]) and int(s[i]):\n # 10-26的考虑范围\n dpnow,dplast = dplast + dpnow,dpnow\n elif int(s[i-1]) == 0 and (i-1 == 0 or int(s[i-2]) == 0 or int(s[i-2])>2 or int(s[i]) == 0):\n # 出现单个0,不合法,直接return 0 \n # 00 - 09 的非法情况,这个0必须和前面的配对,否则失败\n dpnow = 0\n break\n elif int(s[i]) == 0 and (int(s[i-1]) == 0 or int(s[i-1])>2):\n # 非法情况 30 40 50 60\n dpnow = 0\n break\n elif int(s[i]) == 0:\n dpnow,dplast = dplast,dplast\n elif i >0 and int(s[i-1:i+1]) > 26:\n # 处理 > 26 的合法情况\n dpnow,dplast = dpnow,dpnow\n i += 1\n\n return dpnow\n \nif __name__ == '__main__':\n solu = Solution()\n\n # nums = [3,2,1,5]\n\n n = 8\n inputList = [1]\n inputList = [2, 0, 5, 6, 2, 3]\n matrix = [[\"0\",\"1\",\"0\",\"1\",\"0\"],[\"1\",\"1\",\"0\",\"1\",\"1\"],[\"1\",\"1\",\"1\",\"1\",\"1\"],[\"1\",\"0\",\"0\",\"1\",\"0\"]]\n matrix = []\n matrix = [[\"0\"],['1']]\n matrix = [[\"1\",\"0\"]]\n ss = ['12',\"23\",'20310','06','011106','111111111111111111111111111111111111111111111']\n ss = ['1234','2101','123123']\n for s in ss:\n result = solu.numDecodings(s)\n \n output_Str = ' result = ' + str(result)\n print(output_Str)\n ","repo_name":"qizhenkang/myLeetCode","sub_path":"code/Solution_0091_numDecodings.py","file_name":"Solution_0091_numDecodings.py","file_ext":"py","file_size_in_byte":3185,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"15"} +{"seq_id":"6786493512","text":"import pytest\nfrom selenium import webdriver\n\n@pytest.fixture\ndef driver(request):\n wd = webdriver.Chrome()\n request.addfinalizer(wd.quit)\n return wd\n\ndef test(driver):\n driver.implicitly_wait(5)\n driver.get(\"http://localhost/litecart/admin/\")\n driver.find_element_by_name(\"username\").send_keys(\"admin\")\n driver.find_element_by_name(\"password\").send_keys(\"admin\")\n driver.find_element_by_name(\"login\").click()\n driver.get(\"http://localhost/litecart/admin/?app=geo_zones&doc=geo_zones\")\n rows = driver.find_elements_by_css_selector(\".dataTable .row td:nth-child(3)\")\n print(rows)\n countries = []\n for row in rows:\n countries.append(row.text)\n for country in countries:\n driver.find_element_by_link_text(country).click()\n zones = driver.find_elements_by_css_selector(\".dataTable tr td:nth-child(3) select option:checked\")\n zoneName = ([p.text for p in zones])\n zoneNameOrder = zoneName\n zoneNameOrder.sort()\n if zoneName != zoneNameOrder:\n print(country)\n print(\"The order is incorrect.\")\n else:\n print(country)\n print(\"The order is correct.\")\n driver.get(\"http://localhost/litecart/admin/?app=geo_zones&doc=geo_zones\")","repo_name":"alexfilippovw/Selenium_training","sub_path":"Lesson_5/Task_9_2.py","file_name":"Task_9_2.py","file_ext":"py","file_size_in_byte":1266,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"15"} +{"seq_id":"22537627017","text":"import unittest\nimport os\nfrom SDExamination2_piggame import Game\n\n\nclass TestGame(unittest.TestCase):\n\n def test_high_scores_file_access(self):\n # Check if the high scores file is only accessible by the game.\n self.assertFalse(os.access(\"high_scores.txt\", os.X_OK))\n\n def test_player_name_sanitization(self):\n # Check if player's name input is sanitized and validated.\n game = Game(num_players=1, level=1)\n player_name = game.players[0].name\n self.assertTrue(player_name.isalpha())\n\n def test_cheat_variable_security(self):\n # Check if the \"cheat\" variable is properly secured.\n game = Game(num_players=1, level=1)\n game.cheat = True\n with self.assertRaises(AttributeError):\n game.cheat = False\n\n\nif __name__ == '__main__':\n unittest.main()\n","repo_name":"Securella/SD2","sub_path":"test_game_sec.py","file_name":"test_game_sec.py","file_ext":"py","file_size_in_byte":835,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"15"} +{"seq_id":"1392787868","text":"\r\n# M083140008\r\n# 黃警鋒\r\n\r\nfrom layoutV import *\r\nfrom pointV import *\r\nfrom ConvexHull import *\r\nclass Voronoi:\r\n def __init__(self,pointN,_pointArray):\r\n # self.data_pointArray = _pointArray\r\n # print(self.data_num_Array)\r\n\r\n self.pointArray = _pointArray # 放每個點 之後會排序\r\n self.pointNum = pointN\r\n self.midlineArray = []\r\n self.lineArray = []\r\n self.drawlineArray = []\r\n self.sortedPointArray = []\r\n self.CH_Draw = []\r\n self.CH_Point = []\r\n\r\n self.combine_pointArray = []\r\n self.combine_drawlineArray = []\r\n self.combine_sortedPointArray = []\r\n self.combine_lineArray = []\r\n self.combine_CH_Draw = []\r\n def set_self(self,VD):\r\n self.pointArray = VD.pointArray\r\n self.drawlineArray = VD.drawlineArray\r\n self.sortedPointArray = VD.sortedPointArray\r\n self.lineArray = VD.lineArray\r\n self.CH_Draw = VD.CH_Draw\r\n self.CH_Point = VD.CH_Point\r\n self.combine_pointArray = VD.combine_pointArray\r\n self.combine_drawlineArray = VD.combine_drawlineArray\r\n self.combine_sortedPointArray = VD.combine_sortedPointArray\r\n self.combine_lineArray = VD.combine_lineArray\r\n self.combine_CH_Draw = VD.combine_CH_Draw\r\n def getandline(self):\r\n return self.sortedPointArray, self.lineArray\r\n def getPointArray(self):\r\n return self.pointArray\r\n def getDraw_line(self):\r\n return self.drawlineArray\r\n def getDraw_point_and_line(self): # 回傳要畫的圖跟線\r\n return self.sortedPointArray,self.drawlineArray\r\n def printArrayPoint(self,array):\r\n for i in array :\r\n print(i.getXY())\r\n def lexical_order_Point(self): # 排序\r\n self.pointArray.sort(key=lambda x: (x.getX(), x.getY()))\r\n self.sortedPointArray = self.pointArray\r\n # self.sortedPointArray.sort(key =lambda x:(x.getX(),x.getY()))\r\n # self.printArrayPoint(self.sortedPointArray)\r\n def lexical_order_Line(self):\r\n self.drawlineArray.sort(key = lambda x:(x.getp1().getX(),x.getp1().getY(),x.getp2().getX(),x.getp2().getY()))\r\n\r\n\r\n def run(self):\r\n self.lexical_order_Point()\r\n # print(self.pointArray)\r\n if self.pointNum == 1 :\r\n p1 = self.pointArray[0]\r\n elif self.pointNum == 2 :\r\n p1 = self.pointArray[0]\r\n p2 = self.pointArray[1]\r\n l1 = lineV(p1, p2)\r\n l1_V = l1.Vertical_line() # 找出中垂線\r\n self.midlineArray.append(l1_V)\r\n self.drawlineArray.append(l1_V)\r\n # print(self.pointArray)\r\n CH_test = ConvexHull(self.pointArray)\r\n CH_test.convexHull(self.pointNum)\r\n self.CH_Draw = CH_test.lineDraw\r\n self.CH_Point = CH_test.convexPoint\r\n # print('11')\r\n elif self.pointNum == 3 :\r\n CH_test = ConvexHull(self.pointArray)\r\n CH_test.convexHull(self.pointNum )\r\n self.CH_Draw = CH_test.lineDraw\r\n self.CH_Point = CH_test.convexPoint\r\n self.point_Three(0)\r\n else :\r\n # point > 3 做divide\r\n # self.divide(0,int(self.pointNum-1))\r\n print(\"divided\")\r\n self.set_self(self.divide_and_merge(self))\r\n CH_test = ConvexHull(self.pointArray)\r\n CH_test.convexHull(self.pointNum)\r\n self.CH_Draw = CH_test.lineDraw\r\n self.CH_Point = CH_test.convexPoint\r\n self.lexical_order_Line()\r\n # self.reset()\r\n def point_Three(self,left):\r\n p1 = self.pointArray[left]\r\n p2 = self.pointArray[left+1]\r\n p3 = self.pointArray[left+2]\r\n l1 = lineV(p1, p2)\r\n l1_r = lineV(p2, p1)\r\n l2 = lineV(p1, p3)\r\n l3 = lineV(p2, p3)\r\n self.lineArray.append(l1)\r\n self.lineArray.append(l2)\r\n self.lineArray.append(l3)\r\n angle1 = l1.angle(l1, l2)\r\n angle2 = l1.angle(l1_r, l3)\r\n angle3 = l2.angle(l2, l3)\r\n l1_V = l1.Vertical_line()\r\n l2_V = l2.Vertical_line()\r\n l3_V = l3.Vertical_line()\r\n self.midlineArray.append(l1_V)\r\n self.midlineArray.append(l2_V)\r\n self.midlineArray.append(l3_V)\r\n p1_2 = l1_V.calulate_corss_lines_point(l2_V)\r\n p1_3 = l1_V.calulate_corss_lines_point(l3_V)\r\n p2_3 = l2_V.calulate_corss_lines_point(l3_V)\r\n if p1_2 is not None:\r\n line_Vector_midpoint = lineV(p1_2, l1.getMidPoint())\r\n line_Vector_midLine_p1 = lineV(p1_2, l1_V.getp1())\r\n line_Vector_midLine_p2 = lineV(p1_2, l1_V.getp2())\r\n a = line_Vector_midpoint.Vector_cross_Inner(line_Vector_midLine_p1)\r\n b = line_Vector_midpoint.Vector_cross_Inner(line_Vector_midLine_p2)\r\n # print(a)\r\n # print(b)\r\n if angle3 < 90:\r\n if a < 0:\r\n l1_V.setp1(p1_2)\r\n else:\r\n l1_V.setp2(p1_2)\r\n else:\r\n if a <= 0:\r\n l1_V.setp2(p1_2)\r\n else:\r\n l1_V.setp1(p1_2)\r\n line_Vector_midpoint = lineV(p1_2, l2.getMidPoint())\r\n line_Vector_midLine_p1 = lineV(p1_2, l2_V.getp1())\r\n line_Vector_midLine_p2 = lineV(p1_2, l2_V.getp2())\r\n a = line_Vector_midpoint.Vector_cross_Inner(line_Vector_midLine_p1)\r\n b = line_Vector_midpoint.Vector_cross_Inner(line_Vector_midLine_p2)\r\n if angle2 < 90:\r\n if a < 0:\r\n l2_V.setp1(p1_2)\r\n else:\r\n l2_V.setp2(p1_2)\r\n else:\r\n if a <= 0:\r\n l2_V.setp2(p1_2)\r\n else:\r\n l2_V.setp1(p1_2)\r\n line_Vector_midpoint = lineV(p1_2, l3.getMidPoint())\r\n line_Vector_midLine_p1 = lineV(p1_2, l3_V.getp1())\r\n line_Vector_midLine_p2 = lineV(p1_2, l3_V.getp2())\r\n a = line_Vector_midpoint.Vector_cross_Inner(line_Vector_midLine_p1)\r\n b = line_Vector_midpoint.Vector_cross_Inner(line_Vector_midLine_p2)\r\n if angle1 < 90:\r\n if a < 0:\r\n l3_V.setp1(p1_2)\r\n else:\r\n l3_V.setp2(p1_2)\r\n else:\r\n if a <= 0:\r\n l3_V.setp2(p1_2)\r\n else:\r\n l3_V.setp1(p1_2)\r\n self.drawlineArray.append(l1_V)\r\n # if angle2 > 180 :\r\n # self.drawlineArray.append(l2_V)\r\n if angle2 < 179:\r\n self.drawlineArray.append(l2_V)\r\n # if p1_2 is not None :\r\n # if not ( p1_2.getX() > 600 or p1_2.getX() < 0 or p1_2.getY() > 600 or p1_2.getY() < 0 ) :\r\n # self.drawlineArray.append(l2_V)\r\n self.drawlineArray.append(l3_V)\r\n def divide_and_merge(self,VD):\r\n\r\n print(\"divide_and_merge\")\r\n print(\"VD, pointNUM = {:d}\".format(VD.pointNum))\r\n if VD.pointNum <= 3 :\r\n VD.run()\r\n print(\"run if point < 3 \")\r\n return VD\r\n else :\r\n VDL_Array = []\r\n VDR_Array = []\r\n for i in range(int(VD.pointNum/2)):\r\n VDL_Array.append(VD.pointArray[i])\r\n for i in range(int(VD.pointNum/2),int(VD.pointNum)) :\r\n VDR_Array.append(VD.pointArray[i])\r\n VDLL = self.divide_and_merge(Voronoi(len(VDL_Array),VDL_Array))\r\n VDRR = self.divide_and_merge(Voronoi(len(VDR_Array), VDR_Array))\r\n return self.merge( VDLL, VDRR)\r\n ## merge to one VD\r\n def merge(self,VDL,VDR):\r\n print(\"merge\")\r\n print(\"VDL pointNum = {:d}\".format(VDL.pointNum))\r\n print(\"VDR pointNum = {:d}\".format(VDR.pointNum))\r\n\r\n Merge_pointArray = []\r\n for i in VDL.pointArray :\r\n Merge_pointArray.append(i)\r\n for i in VDR.pointArray :\r\n Merge_pointArray.append(i)\r\n Merge_pointNum = VDL.pointNum + VDR.pointNum\r\n MergeV = Voronoi(Merge_pointNum,Merge_pointArray)\r\n MergeV.drawlineArray = VDL.drawlineArray + VDR.drawlineArray\r\n MergeV.sortedPointArray = VDL.sortedPointArray + VDR.sortedPointArray\r\n MergeV.lineArray = VDL.lineArray + VDR.lineArray\r\n MergeV.CH_Draw = VDL.CH_Draw + VDR.CH_Draw\r\n CH_test = ConvexHull(MergeV.pointArray)\r\n CH_test.convexHull(MergeV.pointNum)\r\n MergeV.CH_Point = CH_test.convexPoint\r\n # MergeV.pointArray = VDL.pointArray.extend(VDR.pointArray)\r\n # left convex\r\n leftConvex = VDL.CH_Point\r\n rightConvex = VDR.CH_Point\r\n ## get convexhull start and stop where y is min and y is max\r\n leftminN = leftConvex.index(min(leftConvex, key=lambda x: x.getY()))\r\n RightminN = rightConvex.index(min(rightConvex, key=lambda x: x.getY()))\r\n leftmaxN = leftConvex.index(max(leftConvex, key=lambda x: x.getY()))\r\n RightmaxN = rightConvex.index(max(rightConvex,key = lambda x:x.getY()))\r\n print(\"leftMinN = \", leftminN)\r\n print(\"leftMaxN = \" , leftmaxN )\r\n print(\"RightminN = \", RightminN)\r\n print(\"RightmaxN = \", RightmaxN )\r\n print(\"left : \")\r\n for i in leftConvex:\r\n print(i.printP())\r\n print (\"right : \" )\r\n for i in rightConvex:\r\n print(i.printP())\r\n back_point = None\r\n while True :\r\n leftminNext = leftminN\r\n RightminNext = RightminN\r\n if leftminN != leftmaxN : leftminNext = leftminN + 1\r\n if RightminN != RightmaxN : RightminNext = RightminN - 1\r\n if leftminN == leftmaxN and RightminN == RightmaxN :\r\n break\r\n if leftminNext == len(leftConvex) : leftminNext = 0\r\n if RightminNext == -1 :RightminNext = len(rightConvex) -1\r\n print(\"leftMinN = \", leftminN)\r\n print(\"RightminN = \", RightminN)\r\n print(\"leftMinNext = \", leftminNext)\r\n print(\"RightminNext = \", RightminNext)\r\n midline = lineV(leftConvex[leftminN], rightConvex[RightminN]).Vertical_line()\r\n lineleft = lineV(leftConvex[leftminN], leftConvex[leftminNext]).Vertical_line()\r\n lineright = lineV(rightConvex[RightminN], rightConvex[RightminNext]).Vertical_line()\r\n left_p = lineleft.calulate_corss_lines_point(midline)\r\n right_p = lineright.calulate_corss_lines_point(midline)\r\n mid_p = midline.getMidPoint()\r\n if left_p is None :\r\n print(\"mid to right point = \", mid_p.lenlong(right_p))\r\n midline.setp1(right_p)\r\n RightminN = RightminNext\r\n elif right_p is None :\r\n print(\"mid to left point = \", mid_p.lenlong(left_p))\r\n midline.setp1(left_p)\r\n leftminN = leftminNext\r\n elif left_p is not None and right_p is not None :\r\n print(\"mid to left point = \", mid_p.lenlong(left_p))\r\n print(\"mid to right point = \", mid_p.lenlong(right_p))\r\n if mid_p.lenlong(left_p) < mid_p.lenlong(right_p) :\r\n midline.setp1(left_p)\r\n leftminN = leftminNext\r\n # RightminN = RightminNext\r\n else :\r\n midline.setp1(right_p)\r\n RightminN = RightminNext\r\n else :\r\n break\r\n MergeV.drawlineArray.append(midline)\r\n\r\n return MergeV\r\n @staticmethod\r\n def next_point(max,now):\r\n if now == max : now = 0\r\n return now\r\n def find_line(self,VD,line):\r\n a = 0\r\n for i in VD.drawlineArray:\r\n if i.parent_p1 == line.parent_p1 and i.parent_p2 == line.parent_p2 :\r\n return a\r\n a += 1\r\n return -1\r\n def reset(self):\r\n self.pointArray = []\r\n\r\n\r\nif __name__ == '__main__':\r\n print('0.0')\r\n","repo_name":"cfhfelix/pyVonorio","sub_path":"Voronoi.py","file_name":"Voronoi.py","file_ext":"py","file_size_in_byte":12038,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"15"} +{"seq_id":"16622771718","text":"from LCG import LCG_alogorithm, check_valid\n\nb,m = 0,997\ncount = 0\nfor a in range(1,m):\n x = LCG_alogorithm(a,b,m,seed = 2,iterations=2000)\n if check_valid(x,m):\n count += 1\n\nprint(f\"There are {count} vaild\")","repo_name":"StevenMaharaj/ecg","sub_path":"Steven_Maharaj_695281_code_task_1/d_test.py","file_name":"d_test.py","file_ext":"py","file_size_in_byte":221,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"15"} +{"seq_id":"33526088805","text":"# read a text file line by line\n# when word count is more than 10000, cut it and save it to a new file\n\nimport os\nimport re\nimport sys\n\n# read a text file line by line\nfile_input = 'analyze/text/西遊記_clean.txt'\nfile_output_folder = 'analyze/text/西遊記_cut'\n\ntemp = ''\nword_count = 0\npart_num = 1\n\nwith open(file_input, 'r', encoding='utf-8') as f:\n while True:\n lines = f.readline()\n # if line is empty, break\n if not lines:\n break\n \n lines = lines.strip()\n # if after strip, line is empty, continue\n if not lines:\n continue\n\n # if line is not empty, add it to temp \n temp += lines\n word_count += len(lines)\n\n # if word count is more than 10000, cut it and save it to a new file\n if word_count > 10000:\n # save it to a new file\n output_file = os.path.join(file_output_folder, '西遊記_' + str(part_num) + '.txt')\n with open(output_file, 'w', encoding='utf-8') as f2:\n f2.write(temp)\n # reset temp and word_count\n temp = ''\n word_count = 0\n print('part ' + str(part_num) + ' done')\n part_num += 1\n # continue to read the rest of the file\n continue\n","repo_name":"eason8479/Analyze-Novel-By-Statics-Method","sub_path":"analyze/code/cut.py","file_name":"cut.py","file_ext":"py","file_size_in_byte":1295,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"15"} +{"seq_id":"42646140971","text":"import uvicorn\nfrom fastapi import FastAPI, Request, Response, HTTPException\nfrom fastapi.middleware.cors import CORSMiddleware\nfrom fastapi_utils.tasks import repeat_every\nfrom fastapi.responses import FileResponse\nimport requests\nfrom requests_oauthlib import OAuth1\nimport time\nfrom hashlib import sha1\nfrom base64 import b64encode\n\nimport secrets\n\nimport json\n\nimport sqlite3\nimport os\nimport bcrypt\n\n\ntemperatureData = {}\n\nwith open('statusServer.json') as statusServer:\n serverJson = json.load(statusServer)\ntry:\n clientKey = serverJson['Client_Key']\nexcept:\n clientKey = ''\ntry:\n clientSecret = serverJson['Client_Secret']\nexcept:\n clientSecret = ''\ntry:\n tokenKey = serverJson['Token_Key']\nexcept:\n tokenKey = ''\ntry:\n tokenSecret = serverJson['Token_Secret']\nexcept:\n tokenSecret = ''\ntry:\n restADR = serverJson['Server_Host']\nexcept:\n restADR = \"http://localhost:5000/\"\n\nstatusServerAuth = OAuth1(clientKey, clientSecret, tokenKey, tokenSecret)\n\napp = FastAPI()\nlogData = []\ntemperatureData = {\n \"PRP\": [],\n \"RGP\": [],\n \"CFP\": [],\n \"STP\": [],\n \"ICP\": [],\n \"MXP\": [],\n\n}\nplotTimes = []\n\n\napp.add_middleware(\n CORSMiddleware,\n allow_origins=['http://localhost:3000'],\n allow_credentials=True,\n allow_methods=[\"GET\", \"POST\", \"HEAD\", \"OPTIONS\"],\n allow_headers=[\"Content-Type\", \"Access-Control-Allow-Origin\",\n \"Access-Control-Allow-Headers\", \"Authorization\", \"Set-Cookie\"]\n)\n\n\n@app.get(\"/\")\nasync def root():\n return {\"test\": \"Hello World\"}\n\n\n@app.get(\"/Plot/{param}\")\nasync def plot(param):\n return FileResponse(\"./test.png\")\n\n\n@app.post(\"/logout\")\nasync def logout(request: Request, response: Response):\n cookie = request.cookies\n print(cookie)\n if 'token' not in cookie:\n return [False]\n requests.post(restADR+\"Remote/Logout\", auth=getAuthFromToken(cookie))\n response.delete_cookie(key='token')\n return [True]\n\n\n@app.post(\"/login\")\nasync def token(request: Request, response: Response):\n data = await request.json()\n if (not 'username' in data) or (not 'password' in data):\n return {\"authenticated\": False}\n\n hashedPassword = b64encode(\n sha1(bytes(data['password'], 'utf-8')).digest()).decode()\n hashedUsername = b64encode(\n sha1(bytes(data['username'], 'utf-8')).digest()).decode()\n\n authRequest = requests.post(restADR+\"Remote/Auth\",\n json={'username': hashedUsername,\n 'password': hashedPassword},\n auth=statusServerAuth)\n authResponse = authRequest.json()\n print(authResponse)\n if 'authenticated' in authResponse and authResponse['authenticated'] == False:\n return {'authenticated': False}\n if 'tokenKey' and 'tokenSecret' not in authResponse:\n raise HTTPException(500)\n\n accessToken = secrets.token_hex(32)\n\n db_connection = sqlite3.connect('clients.db')\n sqlCursor = db_connection.cursor()\n\n sqlCursor.execute(\n \"SELECT EXISTS(SELECT 1 FROM activeUsers WHERE username=?)\", (hashedUsername,)\n )\n if sqlCursor.fetchone()[0]:\n sqlCursor.execute(\n \"UPDATE activeUsers SET accessToken = ?, tokenKey = ?, tokenSecret = ?\",\n (accessToken, authResponse['tokenKey'],\n authResponse['tokenSecret'])\n )\n else:\n sqlCursor.execute(\"INSERT INTO activeUsers VALUES(?, ?, ?, ?)\",\n (hashedUsername, accessToken, tokenKey, tokenSecret))\n db_connection.commit()\n\n print(accessToken)\n response.set_cookie(\n key='token', value=accessToken, samesite='none', httponly=True)\n\n if authResponse['authenticated']:\n return {\"authenticated\": True}\n else:\n return {\"authenticated\": False}\n\n\ndef validateToken(token):\n db_connection = sqlite3.connect('clients.db')\n sqlCursor = db_connection.cursor()\n\n sqlCursor.execute(\n \"SELECT EXISTS(SELECT 1 FROM activeUsers WHERE accessToken = ?)\", (token, ))\n\n return sqlCursor.fetchone()[0]\n\n\ndef getUserTokenKey(token):\n db_connection = sqlite3.connect('clients.db')\n sqlCursor = db_connection.cursor()\n\n sqlCursor.execute(\n \"SELECT tokenKey FROM activeUsers WHERE accessToken = ?\", (token,)\n )\n return sqlCursor.fetchone()[0]\n\n\ndef getUserTokenSecret(token):\n db_connection = sqlite3.connect('clients.db')\n sqlCursor = db_connection.cursor()\n\n sqlCursor.execute(\n \"SELECT tokenSecret FROM activeUsers WHERE accessToken = ?\", (token,)\n )\n return sqlCursor.fetchone()[0]\n\n\ndef getAuthFromToken(cookie):\n if 'token' not in cookie:\n print('not in cookie')\n raise HTTPException(401)\n token = cookie['token']\n if not validateToken(token):\n print('not validated')\n raise HTTPException(401)\n tokenKey = getUserTokenKey(token)\n tokenSecret = getUserTokenSecret(token)\n print(f\"TOKEN KEY: {tokenKey}\\nTOKEN SECRET: {tokenSecret}\")\n auth = OAuth1(clientKey, clientSecret, tokenKey, tokenSecret)\n return auth\n\n\n@app.get(\"/status\")\nasync def status(request: Request):\n cookie = request.cookies\n auth = getAuthFromToken(cookie)\n response = requests.get(restADR+\"State\", auth=auth)\n try:\n data = response.json()\n print('data', data)\n status = {}\n for valve in data['Valves']:\n status[valve.lower()] = not data[\"Valves\"][valve]\n print('status', status)\n for pump in data[\"Pumps\"]:\n status[pump.upper()] = data[\"Pumps\"][pump]\n except Exception as e:\n print(e)\n status = {}\n print(status)\n return status\n\n\n@app.get(\"/values\")\nasync def values(request: Request):\n cookie = request.cookies\n auth = getAuthFromToken(cookie)\n response = requests.get(restADR+\"All\", auth=auth)\n if response.status_code != 200:\n raise HTTPException(response.status_code)\n try:\n data = response.json()\n except:\n data = {}\n returnData = {ii.upper(): data[ii] for ii in data}\n\n if \"STATUS\" not in returnData:\n returnData[\"STATUS\"] = {}\n if \"TEMPERATURES\" not in returnData:\n returnData[\"TEMPERATURES\"] = {}\n if \"PRESSURES\" not in returnData:\n returnData[\"PRESSURES\"] = {}\n if \"SETPOINT\" not in returnData:\n returnData[\"SETPOINT\"] = {}\n if \"FLOW\" not in returnData:\n returnData[\"FLOW\"] = {}\n\n print(returnData)\n return returnData\n\n\n@app.post(\"/setstate\")\nasync def setState(request: Request):\n cookie = request.cookies\n auth = getAuthFromToken(cookie)\n body = await request.json()\n response = requests.post(\n restADR+\"State/Set\", auth=auth, json=body)\n if response.status_code != 200:\n raise HTTPException(response.status_code)\n try:\n success, state = response.json()\n except:\n success, state = [False, body]\n\n print((success, state))\n\n newState = {}\n if 'valves' in state:\n for valve in state['valves']:\n newState[valve.lower()] = not state['valves'][valve]\n if 'pumps' in state:\n for pump in state['pumps']:\n newState[pump.upper()] = state['pumps'][pump]\n\n print((success, newState))\n\n return (success, newState)\n\n\n@app.on_event(\"startup\")\n@repeat_every(seconds=20)\ndef generatePlot():\n\n try:\n\n data = requests.get(restADR+\"Temperatures\",\n auth=statusServerAuth).json()\n\n except:\n return\n\n dbConnection = sqlite3.connect('logs.db')\n dbCursor = dbConnection.cursor()\n\n try:\n dbCursor.execute(\n \"CREATE TABLE IF NOT EXISTS datalog1(timestamp, PRP, RGP, CFP, STP, ICP, MXP)\")\n except sqlite3.OperationalError:\n pass\n\n DMAP = {\n \"PRP\": \"PRP\",\n \"RGP\": \"RGP\",\n \"CFP\": \"CFP\",\n \"STP\": \"STP\",\n \"ICP\": \"DHX-T\",\n \"MXP\": \"MXP_RUOX\",\n }\n try:\n dbCursor.execute(\"INSERT INTO datalog1 VALUES (?, ?, ?, ?, ?, ?, ?)\", [\n\n time.time(),\n data[DMAP[\"PRP\"]],\n data[DMAP[\"RGP\"]],\n data[DMAP[\"CFP\"]],\n data[DMAP[\"STP\"]],\n data[DMAP[\"ICP\"]],\n data[DMAP[\"MXP\"]],\n\n ])\n except Exception as e:\n print(e)\n\n dbConnection.commit()\n try:\n print('building')\n os.system(\"python ./generatePlot.py\")\n except:\n print('failed')\n\n\nif __name__ == '__main__':\n uvicorn.run(\"main:app\", host=\"0.0.0.0\", port=8000, reload=True)\n","repo_name":"Joshua-Moler/mb_remote_viewer","sub_path":"backend/main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":8475,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"15"} +{"seq_id":"2038035571","text":"from django.db import models\nfrom django.shortcuts import render, get_object_or_404\nfrom .models import Cars\nfrom .forms import CarForm\nfrom django.core.paginator import Paginator, EmptyPage, PageNotAnInteger\nimport urllib\n\n\ndef welcome(request):\n return render(request, 'home.html')\n\n\ndef one_car(request, index):\n car = get_object_or_404(Cars, pk=index)\n\n form_car = CarForm(request.POST or None, request.FILES or None, instance=car)\n\n return render(request, 'car_form.html', {'form_car': form_car})\n\n\ndef is_valid_queryparam(param):\n return param != '' and param is not None\n\n\ndef search(request):\n all = Cars.objects.all().filter(is_activ=True).order_by('index')\n\n make_set = set(Cars.objects.filter(is_activ=True).values_list('make', flat=True))\n make_set_sort = sorted(make_set)\n\n model_set = set(Cars.objects.filter(is_activ=True).values_list('model', flat=True))\n model_set_sort = sorted(model_set)\n\n fuel_set = set(Cars.objects.filter(is_activ=True).values_list('fuel', flat=True))\n fuel_set_sort = sorted(fuel_set)\n\n id_car_contains_query = request.GET.get('id_car')\n make_contains_query = request.GET.get('make')\n model_contains_query = request.GET.get('model')\n fuel_contains_query = request.GET.get('fuel')\n year_min = request.GET.get('year_min')\n year_max = request.GET.get('year_max')\n price_min = request.GET.get('price_min')\n price_max = request.GET.get('price_max')\n date_ad_min = request.GET.get('date_ad_min')\n date_ad_max = request.GET.get('date_ad_max')\n mileage_min = request.GET.get('mileage_min')\n mileage_max = request.GET.get('mileage_max')\n capacity_min = request.GET.get('capacity_min')\n capacity_max = request.GET.get('capacity_max')\n new_price = request.GET.get('new_price')\n order = request.GET.get('order')\n\n if is_valid_queryparam(id_car_contains_query):\n all = all.filter(id_car__exact=id_car_contains_query)\n\n if is_valid_queryparam(make_contains_query) and make_contains_query != 'Wybierz markę':\n all = all.filter(make__icontains=make_contains_query)\n\n if is_valid_queryparam(model_contains_query) and model_contains_query != 'Wybierz model':\n all = all.filter(model__exact=model_contains_query)\n\n if is_valid_queryparam(fuel_contains_query) and fuel_contains_query != 'Wybierz paliwo':\n all = all.filter(fuel__exact=fuel_contains_query)\n\n if is_valid_queryparam(year_min):\n all = all.filter(production_year__gte=year_min)\n if is_valid_queryparam(year_max):\n all = all.filter(production_year__lte=year_max)\n\n if is_valid_queryparam(price_min):\n all = all.filter(price__gte=price_min)\n if is_valid_queryparam(price_max):\n all = all.filter(price__lte=price_max)\n\n if is_valid_queryparam(date_ad_min):\n all = all.filter(date_ad__gte=date_ad_min)\n if is_valid_queryparam(date_ad_max):\n all = all.filter(date_ad__lte=date_ad_max)\n\n if is_valid_queryparam(mileage_min):\n all = all.filter(mileage__gte=mileage_min)\n if is_valid_queryparam(mileage_max):\n all = all.filter(mileage__lte=mileage_max)\n\n if is_valid_queryparam(capacity_min):\n all = all.filter(capacity__gte=capacity_min)\n if is_valid_queryparam(capacity_max):\n all = all.filter(capacity__lte=capacity_max)\n\n if new_price == \"on\":\n all = all.exclude(new_price=0)\n all = all.filter(price__gt=models.F('new_price'))\n if new_price == \"off\":\n all = all.exclude(new_price=0)\n all = all.filter(price__lt=models.F('new_price'))\n\n if order == 'Cena':\n all = all.order_by('-price')\n\n if order == 'Nowa cena':\n all = all.order_by('-new_price')\n\n if order == 'Rok produkcji':\n all = all.order_by('-production_year')\n\n if order == 'Przebieg':\n all = all.order_by('-mileage')\n\n if order == 'Pojemność':\n all = all.order_by('-capacity')\n\n if order == 'Data dodania':\n all = all.order_by('-date_ad')\n\n number_results = len(all)\n page = request.GET.get('page', 1)\n\n paginator = Paginator(all, 100)\n try:\n all = paginator.page(page)\n except PageNotAnInteger:\n all = paginator.page(1)\n except EmptyPage:\n all = paginator.page(paginator.num_pages)\n\n raw_params = request.GET.copy()\n params = urllib.parse.urlencode(raw_params)\n\n print(len(all))\n\n context = {\n 'allcar': all,\n 'make': make_set_sort,\n 'model': model_set_sort,\n 'fuels': fuel_set_sort,\n 'params': params,\n 'number_results': number_results\n }\n\n return render(request, 'search.html', context)\n","repo_name":"HannnaK/samochody","sub_path":"samochody/views.py","file_name":"views.py","file_ext":"py","file_size_in_byte":4648,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"15"} +{"seq_id":"4277613900","text":"# Given the root of a binary tree, return the level order traversal of its nodes' values. (i.e., from left to right, level by level).\n# Input: root = [3,9,20,null,null,15,7]\n# Output: [[3],[9,20],[15,7]]\n# Example 2:\n#\n# Input: root = [1]\n# Output: [[1]]\n# Example 3:\n#\n# Input: root = []\n# Output: []\nfrom collections import deque\nfrom typing import Optional, List\n\n\nclass TreeNode:\n def __init__(self, x, left = None, right = None):\n self.val = x\n self.left = left\n self.right = right\n\n\ndef levelOrder(root: Optional[TreeNode]) -> List[List[int]]:\n if not root:\n return []\n\n result = []\n\n stack = deque()\n stack.append(root)\n while stack:\n level = []\n for i in range(len(stack)):\n node = stack.pop()\n level.append(node.val)\n if node.left:\n stack.appendleft(node.left)\n if node.right:\n stack.appendleft(node.right)\n result.append(level)\n return result\n\n\nnode = TreeNode(10, TreeNode(1), TreeNode(100, TreeNode(3), TreeNode(500)))\nassert levelOrder(node) == [[10], [1, 100], [3, 500]]","repo_name":"olbogdan/Algorithms","sub_path":"Python/AlgoBootcamp/leetcode/medium/102. Binary Tree Level Order Traversal.py","file_name":"102. Binary Tree Level Order Traversal.py","file_ext":"py","file_size_in_byte":1128,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"15"} +{"seq_id":"16542857293","text":"from bs4 import BeautifulSoup\nimport requests\nfrom pprint import pprint\nimport datetime\nimport time\n\nbase_url = \"https://habr.com\"\nurl = \"https://habr.com/ru/all/\"\nheaders = {\n 'User-Agent': 'Mozilla/5.0 (Macintosh; Intel Mac OS X 10_10_1) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/39.0.2171.95 Safari/537.36'}\n\nKEYWORDS = ['JavaScript', 'C++', 'web', 'python']\n\nlist_stat = list()\n\n\ndef decor_link(link_log):\n def decor(old_fuction):\n def new_function(url, keywords, headers):\n result = old_fuction(url, keywords, headers)\n\n with open(link_log, \"a+\", encoding=\"utf-8\") as result_file:\n result_file.write(f'Дата и время: {datetime.datetime.now()}' + '\\n')\n result_file.write(f'Функция: {old_fuction.__name__}' + '\\n')\n result_file.write(f'Аргументы: {url} {keywords} {headers}' + '\\n')\n result_file.write(f'Возвращаемый результат: {result}' + '\\n')\n result_file.write('\\n')\n\n return result\n\n return new_function\n return decor\n\n\n@decor_link('parse.txt')\ndef parse_url_tags(url, keywords, headers):\n response = requests.get(url, headers=headers)\n\n if response.status_code == 200:\n html = response.text\n soup = BeautifulSoup(html, \"html.parser\")\n container = soup.select_one(\".tm-articles-list\")\n\n\n for item_pr in container.select('article.tm-articles-list__item'):\n dates = item_pr.select_one(\".tm-article-snippet__datetime-published\").text\n name = item_pr.select_one(\".tm-article-snippet__title-link span\").text\n link = base_url + item_pr.select_one(\".tm-article-snippet__title-link\").attrs[\"href\"]\n\n list_tag_item_container = item_pr.select_one('.tm-article-snippet__hubs')\n list_tag_item = list()\n for item_tag in list_tag_item_container.select('.tm-article-snippet__hubs-item'):\n list_tag_item.append(item_tag.text.replace(' *', ''))\n\n\n result_search = list(set(KEYWORDS) & set(list_tag_item))\n\n if not result_search:\n pass\n else:\n list_stat.append(dates + ' ||| ' + name + ' ||| ' + link)\n print(dates + ' ||| ' + name + ' ||| ' + link)\n\n else:\n print('Сервер не отвечает')\n\n return list_stat\n\n\nparse_url_tags(url, KEYWORDS, headers)\n","repo_name":"AleksChu13/DecoHW","sub_path":"3.py","file_name":"3.py","file_ext":"py","file_size_in_byte":2441,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"15"} +{"seq_id":"411510933","text":"\r\n\r\nx=3\r\ny=2\r\nz=x+y\r\nprint(z)\r\n\r\n#f = open('mydata','r')\r\n#print (f.read())\r\n\r\n#import openpyxl\r\n#openpyxl.load_workbook(\"stocks.xlsx\")\r\n#sheets=wb.sheetnames\r\n#print(sheets)\r\n\r\nimport csv\r\nwith open('stockscsv.csv', mode='r') as f:\r\n reader = csv.reader(f)\r\n for row in reader:\r\n print(row)\r\n\r\n\r\nimport xlrd\r\nloc = (\"stocksnew.xls\")\r\nwb = xlrd.open_workbook(loc)\r\nsheet = wb.sheet_by_index(0)\r\nsheet.cell_value(0, 0)\r\nprint(sheet.ncols)\r\nprint(sheet)\r\n\r\n#import openpyxl\r\n#openpyxl.load_workbook(\"stocks.xlsx\")\r\n\r\n\r\n","repo_name":"ankur131/read-xls-sql-python","sub_path":"main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":527,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"15"} +{"seq_id":"42901362982","text":"import pandas as pd\nimport matplotlib.pyplot as plt\nplt.style.use(\"seaborn-dark\") # Añade un gris de fondo a la gráfica\n\n\ndef Graph(data):\n\n for param in ['figure.facecolor', 'axes.facecolor', 'savefig.facecolor']:\n plt.rcParams[param] = '#212946' # Color del fondo, toda la figura\n for param in ['text.color', 'axes.labelcolor', 'xtick.color', 'ytick.color']:\n plt.rcParams[param] = 'white' # Color de las etiquetas y números de los ejes\n\n colors = [\n '#08F7FE', # teal/cyan\n '#FE53BB', # pink\n '#F5D300', # yellow\n '#00ff41', # matrix green\n ]\n\n df = data['SAT'] # Graficamos solo una variable de data, en este caso SAT (tenemos GPA tambien)\n \n fig, ax = plt.subplots()\n \n df.plot(marker='o', color='#08F7FE', ax=ax) #Aqui podemos cambiar el color de las línea y marcadores\n\n # Esta parte del código nos da las sombras alrededor de las líneas graficadas, es un efecto sombra. \n n_shades = 5\n diff_linewidth = 1.05\n alpha_value = 0.3 / n_shades\n for n in range(1, n_shades+1):\n df.plot(marker='o',\n linewidth=2+(diff_linewidth*n),\n alpha=alpha_value,\n legend=False,\n ax=ax,\n color='#08F7FE')\n \n # Graficar los datos\n \n ax.grid(color='#F5D300', alpha = 0.3) # Cambiar el grid\n font = {'fontname' : 'AppleMyungjo'} # Cambiar el tipo de fuente\n for tick in ax.get_xticklabels():\n tick.set_fontname('AppleMyungjo') # Cambiar el tipo de fuente del eje X\n for tick in ax.get_yticklabels():\n tick.set_fontname('AppleMyungjo') # Cambiar el tipo de fuente del eje Y\n plt.xlabel(\"Number of student\", **font)\n plt.ylabel(\"Score\", **font)\n plt.title(\"SAT\", size = 30, **font)\n plt.show()\n\n\ndef main():\n data = pd.read_csv('1.01. Simple linear regression.csv') # Leemos la información del CSV\n Graph(data)\n\nmain()","repo_name":"PabloYamamoto/Data-Science-Tec","sub_path":"Clases/Clase 19 - Matplotlib/CyberPunkStyle/Test1.py","file_name":"Test1.py","file_ext":"py","file_size_in_byte":1920,"program_lang":"python","lang":"es","doc_type":"code","stars":0,"dataset":"github-code","pt":"15"} +{"seq_id":"13966111484","text":"'''\n编写一个函数来查找字符串数组中的最长公共前缀。\n\n如果不存在公共前缀,返回空字符串 \"\"。\n\n示例 1:\n\n输入: [\"flower\",\"flow\",\"flight\"]\n输出: \"fl\"\n示例 2:\n\n输入: [\"dog\",\"racecar\",\"car\"]\n输出: \"\"\n解释: 输入不存在公共前缀。\n说明:\n\n所有输入只包含小写字母 a-z 。\n'''\n\n# 获取最短的字符串长度,从0开始比较,直到不同的位置\ndef calc(input:list)->str:\n res = ''\n length=len(min(input, key=lambda k: len(k)))\n\n for i in range(length):\n val=input[0][i]\n same=True\n for j in range(1, len(input)):\n same = val == input[j][i] and same\n if same:\n res += val\n else:\n break\n\n return res\n\nif __name__ == '__main__':\n input=[\"flower\",\"flow\",\"floight\"]\n print(calc(input))\n","repo_name":"SsmallWinds/leetcode","sub_path":"codes/14_longest_common_prefix.py","file_name":"14_longest_common_prefix.py","file_ext":"py","file_size_in_byte":843,"program_lang":"python","lang":"zh","doc_type":"code","stars":0,"dataset":"github-code","pt":"15"} +{"seq_id":"20013855565","text":"from graphene import Field, GlobalID, Int, Interface, ObjectType\nfrom graphene.relay import Node, is_node\nfrom mock import patch\n\nfrom .models import Article, Reporter\nfrom ..registry import Registry\nfrom ..types import PynamoObjectType\n\nregistry = Registry()\n\n\nclass Character(PynamoObjectType):\n '''Character description'''\n\n class Meta:\n model = Reporter\n registry = registry\n\n\nclass Human(PynamoObjectType):\n '''Human description'''\n\n pub_date = Int()\n\n class Meta:\n model = Article\n exclude_fields = ('id',)\n registry = registry\n interfaces = (Node,)\n\n\ndef test_pynamo_interface():\n assert issubclass(Node, Interface)\n assert issubclass(Node, Node)\n\n\n@patch('graphene_pynamodb.tests.models.Article.get', return_value=Article(id=1))\ndef test_pynamo_get_node(get):\n human = Human.get_node(None, 1)\n get.assert_called_with(1)\n assert human.id == 1\n\n\ndef test_objecttype_registered():\n assert issubclass(Character, ObjectType)\n assert Character._meta.model == Reporter\n assert list(Character._meta.fields.keys()) == [\n 'articles',\n 'awards',\n 'custom_map',\n 'email',\n 'favorite_article',\n 'first_name',\n 'id',\n 'last_name',\n 'pets']\n\n\ndef test_node_idfield():\n idfield = Human._meta.fields['id']\n assert isinstance(idfield, GlobalID)\n\n\ndef test_node_replacedfield():\n idfield = Human._meta.fields['pub_date']\n assert isinstance(idfield, Field)\n assert idfield.type == Int\n\n\ndef test_object_type():\n assert issubclass(Human, ObjectType)\n assert sorted(list(Human._meta.fields.keys())) == ['headline', 'id', 'pub_date', 'reporter']\n assert is_node(Human)\n","repo_name":"yfilali/graphql-pynamodb","sub_path":"graphene_pynamodb/tests/test_types.py","file_name":"test_types.py","file_ext":"py","file_size_in_byte":1722,"program_lang":"python","lang":"en","doc_type":"code","stars":64,"dataset":"github-code","pt":"15"} +{"seq_id":"37332011098","text":"# -*- coding: utf-8 -*-\n\"\"\"\nCreated on Sun Oct 10 10:38:32 2021\n\n@author: qizhe\n\"\"\"\n\nclass Solution:\n def minOperations(self, grid, x: int) -> int:\n \"\"\"\n 读题:因为要最小操作数,感觉要求一个平均值,然后再讨论是否可以做到全部一致\n \n 1、平均值:遍历\n 2、是否全部一致:最小元素差 奇偶数判断,感觉上是一个取余?是不是一个最小差距 然后看是不是能整除x\n \n 为什么不给我一个一维的变量呢\n \"\"\"\n m = len(grid)\n n = len(grid[0])\n cnt = 0\n # gridArray = \n for i in range(m):\n for j in range(n):\n cnt += grid[i][j]\n average = round(cnt / (m*n))\n \n # 找最接近平均数的一个元素\n # 是不是应该找中位数\n \n aimNumber = grid[0][0]\n gridOne = []\n for i in range(m):\n for j in range(n):\n gridOne.append(grid[i][j])\n gridOne.sort()\n aimNumber = gridOne[(m*n)//2]\n # # print\n # print(gridOne[(m*n)//2])\n # # endFlag = 0\n # for i in range(m):\n # for j in range(n):\n # if abs(aimNumber-average) > abs(grid[i][j]-average):\n # aimNumber = grid[i][j]\n \n # # if aimNumber == average:\n # # endFlag = 1\n # # break\n \n # # if abs(grid[i][j]-average) < x and grid[i][j] > average:\n # # # print(grid[i][j],average)\n # # aimNumber = grid[i][j]\n # # endFlag = 1\n # # break\n # # if endFlag:\n # # break\n # if aimNumber > average:\n # aimNumber2 = aimNumber - x\n # else:\n # aimNumber2 = aimNumber + x\n # aimNumber = 596 + x\n opeCnt = 0\n for i in range(m):\n for j in range(n):\n if abs(grid[i][j] -aimNumber) % x == 0:\n opeCnt += abs(grid[i][j] -aimNumber) // x\n # print(opeCnt1,abs(grid[i][j] -aimNumber) // x,aimNumber)\n else:\n return -1\n # print(average,aimNumber,opeCnt)\n \n # print(opeCnt1,opeCnt2)\n return opeCnt\n\n\nif __name__ == '__main__':\n solu = Solution()\n\n # m = 3\n grid = [[1,2],[3,4]]\n x = 2\n grid = [[1,5],[2,3]]\n x = 1\n grid = [[2,4],[6,8]]\n x = 2\n grid = [[980,476,644,56],[644,140,812,308],[812,812,896,560],[728,476,56,812]]\n x = 84\n \n # grid = [[454,328,160,286,664],[496,538,748,244,286],[34,244,454,706,790],[496,538,832,958,328],[370,874,370,874,286]]\n # x = 42\n # grid = [[596,904,960,232,120,932,176],[372,792,288,848,960,960,764],[652,92,904,120,680,904,120],[372,960,92,680,876,624,904],[176,652,64,344,316,764,316],[820,624,848,596,960,960,372],[708,120,456,92,484,932,540]]\n # x = 28\n result = solu.minOperations(grid, x)\n # output_Str = ' result = '\n # print(' result = ',end=' ')\n # while result:\n # print(result.val,end=' ')\n # result = result.next\n\n\n output_Str = ' result = ' + str(result) \n print(output_Str)","repo_name":"qizhenkang/myLeetCode","sub_path":"code/Solution_2033_minOperations.py","file_name":"Solution_2033_minOperations.py","file_ext":"py","file_size_in_byte":3273,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"15"} +{"seq_id":"10588020428","text":"import shutil\nimport traceback\nimport csv\nfrom rdflib import Graph, URIRef, Literal, BNode, XSD\nfrom rdflib.namespace import FOAF, NamespaceManager, Namespace, RDFS\nimport os\n\nedm = Namespace(\"http://www.europeana.eu/schemas/edm/\")\nrdf = Namespace(\"http://www.w3.org/1999/02/22-rdf-syntax-ns#\")\ndcterms = Namespace(\"http://purl.org/dc/terms/\")\naat = Namespace(\"http://vocab.getty.edu/aat/\")\ndc = Namespace(\"http://purl.org/dc/elements/1.1/\")\n\ndef openCsvToTriple(_path=\"./testfile/\"):\n try:\n _entities = []\n for fName in os.listdir(_path):\n if not fName.endswith('.csv'):\n continue\n _entities.append(fName.split(\".\")[0])\n csvToTripleProcess(_path, _entities)\n except Exception as e:\n print(str(e), traceback.format_exc())\n\ndef csvToTripleProcess(_path, _entities, artformPath = './artformtriple/'):\n shutil.rmtree(artformPath, ignore_errors=True)\n os.makedirs(artformPath, exist_ok=True)\n try:\n g = Graph()\n for csvFile in _entities:\n print(csvFile)\n with open (f'{_path}{csvFile}.csv') as fileHanler:\n csvreader = csv.reader(fileHanler)\n for row in csvreader:\n g.add((URIRef(row[0]), dcterms.artform, URIRef(row[1])))\n\n g.serialize(destination=f'{artformPath}artforms_test.n3', format='ntriples', encoding='utf-8')\n g2 = Graph()\n g2.parse(f'{artformPath}artforms_test.n3', format='ntriples')\n g2.namespace_manager.bind('dcterms', URIRef('http://purl.org/dc/terms/'), replace=True)\n g2.namespace_manager.bind('aat', URIRef('http://vocab.getty.edu/aat/'), replace=True)\n g2.serialize(destination=f'{artformPath}artforms_test_final.ttl', format='turtle', encoding='utf-8')\n\n except Exception as e:\n print(str(e), traceback.format_exc())\n\n\n\ndef enrichWithArtForm( enrichfile = './enrich-step1/', artformPath = './artformtriple/artforms_test_final.ttl', pathorginalfile=\"./converted/mauritshuis.ttl\"):\n shutil.rmtree(enrichfile, ignore_errors=True)\n os.makedirs(enrichfile, exist_ok=True)\n gArtFrom = Graph()\n gArtFrom.parse(f'{artformPath}', format='turtle')\n gOrginFile = Graph()\n gOrginFile.parse(f'{pathorginalfile}', format='turtle')\n integrateFile = gArtFrom + gOrginFile\n integrateFile.serialize(destination=f'{enrichfile}mauritshuis_Graph.ttl', format='turtle', encoding='utf-8')\n\ndef extract_csv_creators(enrichfile='./enrich-step1/', _resultCreatorsCsv='./creators/'):\n shutil.rmtree(_resultCreatorsCsv, ignore_errors=True)\n os.makedirs(_resultCreatorsCsv, exist_ok=True)\n # for entityName in _entities:\n gPath = f'{enrichfile}mauritshuis_Graph.ttl'\n g = Graph()\n g.parse(gPath, format(\"ttl\"))\n print( \" file Parsed successfully\")\n\n getByIdentifiers = \"\"\"\n SELECT DISTINCT ?a ?b \n WHERE {\n ?a ?b .\n ?a ?c. \n }\"\"\"\n\n qres = g.query(getByIdentifiers)\n with open(_resultCreatorsCsv+ f'creators.csv', 'w', encoding='utf-8', newline='') as f:\n writer = csv.writer(f, quoting=csv.QUOTE_ALL, delimiter=',', quotechar='\"') # quotechar='',\n f.write(\",\".join([\"uri\", \"creators\"]))\n f.write(\"\\n\")\n for row in qres:\n sub = row.a.split(\"/n\")[0]\n obj = row.b.split(\"/n\")[0]\n writer.writerow([sub, obj])\n\n\nopenCsvToTriple()\nenrichWithArtForm()\nextract_csv_creators()","repo_name":"mariamsajadian/myproject-DHN","sub_path":"myproject/3-artform-creators/.idea/art-form_creators.py","file_name":"art-form_creators.py","file_ext":"py","file_size_in_byte":3515,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"15"} +{"seq_id":"39090098262","text":"#!/usr/bin/env python\n# -*- coding: utf-8 -*-\n\nimport re\nfrom main import app\n#from .models import set_user_info, get_user_student_info, get_user_library_info\nfrom .utils import AESCipher, init_wechat_sdk\nfrom .plugins.state import set_user_state, get_user_state, \\\n set_user_last_interact_time, get_user_last_interact_time\n\ndef wechat_response(data):\n \"\"\"微信消息处理回复\"\"\"\n global message, openid, wechat\n\n wechat = init_wechat_sdk()\n wechat.parse_data(data)\n message = wechat.get_message()\n openid = message.source\n # 用户信息写入数据库\n #set_user_info(openid)\n\n try:\n get_resp_func = msg_type_resp[message.type]\n response = get_resp_func()\n except KeyError:\n # 默认回复微信消息\n response = 'success'\n\n # 保存最后一次交互的时间\n set_user_last_interact_time(openid, message.time)\n return response\n\n# 储存微信消息类型所对应函数(方法)的字典\nmsg_type_resp = {}\n\n\ndef set_msg_type(msg_type):\n \"\"\"\n 储存微信消息类型所对应函数(方法)的装饰器\n \"\"\"\n def decorator(func):\n msg_type_resp[msg_type] = func\n return func\n return decorator\n\n\n@set_msg_type('text')\ndef text_resp():\n \"\"\"文本类型回复\"\"\"\n # 默认回复微信消息\n response = 'success'\n # 替换全角空格为半角空格\n message.content = message.content.replace(u' ', ' ')\n # 清除行首空格\n message.content = message.content.lstrip()\n # 指令列表\n commands = {\n u'取消': cancel_command,\n u'^\\?|^?': all_command,\n u'^wifi|^WIFI|^配置': printer_airkiss_command,\n\n u'^绑定|^綁定': auth_url,\n u'更新菜单': update_menu_setting\n }\n # 状态列表\n # state_commands = {\n # 'chat': chat_robot,\n # 'express': express_shipment_tracking\n # }\n # 匹配指令\n command_match = False\n for key_word in commands:\n if re.match(key_word, message.content):\n # 指令匹配后,设置默认状态\n set_user_state(openid, 'default')\n response = commands[key_word]()\n command_match = True\n break\n if not command_match:\n # 匹配状态\n state = get_user_state(openid)\n # 关键词、状态都不匹配,缺省回复\n if state == 'default' or not state:\n response = command_not_found()\n else:\n response = state_commands[state]()\n return response\n\n\n@set_msg_type('click')\ndef click_resp():\n \"\"\"菜单点击类型回复\"\"\"\n commands = {\n 'phone_number': phone_number,\n 'express': enter_express_state,\n 'score': exam_grade,\n 'borrowing_record': borrowing_record,\n 'renew_books': renew_books,\n 'sign': daily_sign,\n 'chat_robot': enter_chat_state,\n 'music': play_music,\n 'weather': get_weather_news\n }\n # 匹配指令后,重置状态\n set_user_state(openid, 'default')\n response = commands[message.key]()\n return response\n\n\n@set_msg_type('scancode_waitmsg')\ndef scancode_waitmsg_resp():\n \"\"\"扫码类型回复\"\"\"\n set_user_state(openid, 'express')\n response = express_shipment_tracking()\n return response\n\n\n@set_msg_type('subscribe')\ndef subscribe_resp():\n \"\"\"订阅类型回复\"\"\"\n set_user_state(openid, 'default')\n response = subscribe()\n return response\n\n\ndef borrowing_record():\n \"\"\"查询借书记录\"\"\"\n return library_check_auth(u'查询中……')\n\n\ndef renew_books():\n \"\"\"续借图书\"\"\"\n return library_check_auth(u'续借中……', renew=True)\n\ndef search_books():\n \"\"\"图书馆找书\"\"\"\n content = app.config['LIBRARY_TEXT'] + app.config['HELP_TEXT']\n return wechat.response_text(content)\n\n\n\ndef auth_url():\n \"\"\"教务系统、图书馆绑定的 URL\"\"\"\n jw_url = app.config['HOST_URL'] + '/auth-score/' + openid\n library_url = app.config['HOST_URL'] + '/auth-library/' + openid\n content = app.config['AUTH_TEXT'] % (jw_url, library_url)\n return wechat.response_text(content)\n\n\ndef get_school_news():\n \"\"\"读取学院新闻\"\"\"\n school_news.get.delay(openid)\n return 'success'\n\n\ndef get_weather_news():\n \"\"\"获取天气预报\"\"\"\n weather.get.delay(openid)\n return 'success'\n\n\ndef update_menu_setting():\n \"\"\"更新自定义菜单\"\"\"\n try:\n wechat.create_menu(app.config['MENU_SETTING'])\n except Exception as e:\n return wechat.response_text(e)\n else:\n return wechat.response_text('Done!')\n\n\ndef developing():\n \"\"\"维护公告\"\"\"\n return wechat.response_text('该功能维护中')\n\n\ndef enter_express_state():\n \"\"\"进入快递查询模式\"\"\"\n set_user_state(openid, 'express')\n return wechat.response_text(app.config['ENTER_EXPRESS_STATE_TEXT'])\n\n\ndef cancel_command():\n \"\"\"取消状态\"\"\"\n content = app.config['CANCEL_COMMAND_TEXT'] + app.config['COMMAND_TEXT']\n return wechat.response_text(content)\n\n\ndef enter_chat_state():\n \"\"\"进入聊天模式\"\"\"\n set_user_state(openid, 'chat')\n return wechat.response_text(app.config['ENTER_CHAT_STATE_TEXT'])\n\n\ndef cet_score():\n \"\"\"回复四六级查询网址\"\"\"\n content = app.config['CET_SCORE_TEXT'] + app.config['HELP_TEXT']\n return wechat.response_text(content)\n\n\ndef postcard():\n \"\"\"明信片查询\"\"\"\n content = app.config['POSTCARD_TEXT'] + app.config['HELP_TEXT']\n return wechat.response_text(content)\n\n\ndef html5_games():\n \"\"\"HTML5游戏\"\"\"\n content = app.config['HTML5_GAMES_TEXT'] + app.config['HELP_TEXT']\n return wechat.response_text(content)\n\n\ndef contact_us():\n \"\"\"合作信息\"\"\"\n content = app.config['CONTACT_US_TEXT'] + app.config['HELP_TEXT']\n return wechat.response_text(content)\n\n\ndef academic_calendar():\n \"\"\"校历\"\"\"\n return wechat.response_news(app.config['ACADEMIC_CALENDAR_NEWS'])\n\n\ndef bbs_url():\n \"\"\"论坛网址\"\"\"\n content = app.config['BBS_URL_TXT'] + app.config['HELP_TEXT']\n return wechat.response_text(content)\n\n\ndef bus_routes():\n \"\"\"公交信息\"\"\"\n return wechat.response_news(app.config['BUS_ROUTES_NEWS'])\n\n\ndef weather_radar():\n \"\"\"气象雷达动态图\"\"\"\n content = app.config['WEATHER_RADAR_TEXT'] + app.config['HELP_TEXT']\n return wechat.response_text(content)\n\n\ndef command_not_found():\n \"\"\"非关键词回复\"\"\"\n # 客服接口回复信息\n content = app.config['COMMAND_NOT_FOUND_TEXT'] + app.config['HELP_TEXT']\n wechat_custom.send_text(openid, content)\n # 转发消息到微信多客服系统\n return wechat.group_transfer_message()\n\n\ndef all_command():\n \"\"\"回复全部指令\"\"\"\n content = app.config['COMMAND_TEXT']\n return wechat.response_text(content)\n\n\ndef subscribe():\n \"\"\"回复订阅事件\"\"\"\n content = app.config['WELCOME_TEXT'] + app.config['COMMAND_TEXT']\n return wechat.response_text(content)\n\n\ndef phone_number():\n \"\"\"回复电话号码\"\"\"\n content = app.config['PHONE_NUMBER_TEXT'] + app.config['HELP_TEXT']\n return wechat.response_text(content)\n\ndef printer_airkiss_command():\n \"\"\"代开airkiss 页面\"\"\"\n airkissURL = app.config['HOST_URL']+\"/wechat/printer/airkiss\"\n content = app.config['AIRKISS_URL_TXT'].format(airkissURL)\n return wechat.response_text(content)\n\nif __name__ == '__main__':\n import sys;\n file = open(sys.argv[1],'r')\n data = file.read()\n print(data)\n wechat_response(data)\n","repo_name":"cszhan163/tt","sub_path":"main/response.py","file_name":"response.py","file_ext":"py","file_size_in_byte":7443,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"15"} +{"seq_id":"8052517708","text":"\"\"\"Contains general utility functions to be used by the execution server.\"\"\"\n\nimport os\nimport signal\nimport json\nimport sys\nimport subprocess\nimport threading\nimport platform\n\n\ndef load_configuration():\n config_file_name = os.path.join(os.path.dirname(__file__), 'config.json')\n config = json.load(open(config_file_name))\n return config\n\n\ndef process_commandline_args(register, update):\n if len(sys.argv) > 1:\n if sys.argv[1] == 'register':\n register()\n print('Successfully registered.')\n sys.exit(0)\n elif sys.argv[1] == 'update':\n update()\n print('Successfully updated.')\n sys.exit(0)\n else:\n print('Python custom execution server can take one of two optional arguments:')\n print('register - register the execution server with details from config.json')\n print('update - update the details of the execution server to those in config.json')\n sys.exit(1)\n\n\ndef run_background_thread(target, args=()):\n background_thread = threading.Thread(target=target, args=args)\n background_thread.daemon = True\n background_thread.start()\n\n\nclass ProcessRunner():\n def __init__(self):\n self._current_processes = {}\n self._stopping_processes = []\n self._running_on_windows = platform.system() == 'Windows'\n\n def execute(self, command, identifier):\n if self._running_on_windows:\n process = subprocess.Popen(command, stdout=subprocess.PIPE, stderr=subprocess.STDOUT, shell=False)\n else:\n process = subprocess.Popen(command, stdout=subprocess.PIPE, stderr=subprocess.STDOUT, shell=True, preexec_fn=os.setsid)\n self._current_processes[identifier] = process\n output = ''\n for line in iter(process.stdout.readline, b''):\n output += line\n process.communicate()\n self._current_processes.pop(identifier, None)\n if identifier in self._stopping_processes:\n self._stopping_processes.remove(identifier)\n return None\n return output, process.returncode\n\n def stop(self, identifier):\n process = self._current_processes.get(identifier)\n if process is not None:\n self._stopping_processes.append(identifier)\n if self._running_on_windows:\n process.kill()\n else:\n os.killpg(process.pid, signal.SIGTERM)\n","repo_name":"graboskyc/BasicCloudShellRobot","sub_path":"CES/utility.py","file_name":"utility.py","file_ext":"py","file_size_in_byte":2445,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"15"} +{"seq_id":"14415572920","text":"from django.urls import path\nfrom tasks.views import index\n\nfrom . import views\n\nurlpatterns = [\n path(\"\", index.as_view(), name=\"index\"),\n path(\"logout\", views.logout_view, name=\"logout\"),\n path(\"login\", views.login_view, name=\"login\"),\n path(\"register\", views.register, name=\"register\"),\n path(\"new_task\", views.new_task, name=\"new_task\"),\n path(\"change/\", views.task_change, name=\"task_change\"),\n path(\"delete/\", views.delete, name=\"delete\"),\n path(\"category/\", views.category, name=\"category\")\n]\n","repo_name":"pawot/task-manager","sub_path":"tasks/urls.py","file_name":"urls.py","file_ext":"py","file_size_in_byte":569,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"15"} +{"seq_id":"18018020916","text":"import cv2\nimport mediapipe as mp\nimport math\nimport keyboard\nimport joystick\nmp_drawing = mp.solutions.drawing_utils\nmp_drawing_styles = mp.solutions.drawing_styles\nmp_hands = mp.solutions.hands\nd_threshold = 200\nlr_margin = 0.2\nmax_x = 1.5\nmin_x = -max_x\n\n\ndef controll_key(x, f, b):\n if x > max_x:\n x = max_x\n # print('here x',x)\n joystick.joystick_press(x, smax=max_x, smin=min_x)\n if(f):\n keyboard.press('w')\n else:\n keyboard.release('w')\n if(b):\n keyboard.press('s')\n else:\n keyboard.release('s')\n\n\ndef main():\n forward = False\n backward = False\n left = False\n right = False\n x_start = x_end = 0\n slope = 0\n cap = cv2.VideoCapture(0)\n with mp_hands.Hands(\n model_complexity=1,\n min_detection_confidence=0.7,\n min_tracking_confidence=0.5) as hands:\n while cap.isOpened():\n success, image = cap.read()\n if not success:\n print(\"Ignoring empty camera frame.\")\n continue\n image.flags.writeable = False\n image = cv2.cvtColor(image, cv2.COLOR_BGR2RGB)\n results = hands.process(image)\n\n image.flags.writeable = True\n image = cv2.cvtColor(image, cv2.COLOR_RGB2BGR)\n image_height, image_width, _ = image.shape\n if results.multi_hand_landmarks and len(results.multi_hand_landmarks) > 1:\n text = ''\n x_start, y_start = (int(\n image_width*results.multi_hand_landmarks[0].landmark[9].x), int(image_height*results.multi_hand_landmarks[0].landmark[9].y))\n x_end, y_end = (int(image_width*results.multi_hand_landmarks[1].landmark[9].x), int(\n image_height*results.multi_hand_landmarks[1].landmark[9].y))\n image = cv2.line(image, (x_start, y_start),\n (x_end, y_end), (0, 0, 0), 9)\n if((x_end-x_start) != 0):\n slope = (y_end-y_start)/(x_end-x_start)\n distance = math.dist([x_start, y_start], [x_end, y_end])\n if(distance > d_threshold):\n text = 'Forward'\n forward = True\n backward = False\n else:\n text = 'Backward'\n backward = True\n forward = False\n if(slope < 0 and slope < -1*lr_margin):\n text += ' | Right'\n right = True\n left = False\n\n elif (slope > 0 and slope > lr_margin):\n text += ' | Left'\n right = False\n left = True\n else:\n text += ' | Straight'\n right = left = False\n # print(f'\\r slope : {slope} distance:{distance}')\n else:\n text = 'Not detected'\n right = left = forward = backward = False\n controll_key(-slope, forward, backward)\n # Flip the image horizontally for a selfie-view display.\n image = cv2.putText(cv2.flip(image, 1), text, (0, 40), cv2.FONT_HERSHEY_SIMPLEX, 1,\n (0, 0, 0), 2, cv2.LINE_AA, False)\n cv2.imshow('MediaPipe Hands', image)\n if cv2.waitKey(1) & 0xFF == 27:\n break\n cap.release()\n\n\nif __name__ == \"__main__\":\n main()\n","repo_name":"tr1ten/HGController","sub_path":"main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":3472,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"15"} +{"seq_id":"29883371602","text":"# uncompyle6 version 3.9.0\n# Python bytecode version base 3.7.0 (3394)\n# Decompiled from: Python 3.7.16 (default, May 16 2023, 11:05:37) \n# [Clang 13.0.0 (clang-1300.0.29.30)]\n# Embedded file name: T:\\InGame\\Gameplay\\Scripts\\Server\\interactions\\go_here_test.py\n# Compiled at: 2023-03-07 20:30:20\n# Size of source mod 2**32: 3616 bytes\nimport routing, services, sims4\nfrom event_testing.results import TestResult\nfrom server.pick_info import PickType\n\ndef go_here_test(target, context, **kwargs):\n position = None\n surface = None\n if context.pick is not None:\n position = context.pick.location\n surface = context.pick.routing_surface\n if target is not None:\n position = target.position\n surface = target.routing_surface\n if position is None:\n return TestResult(False, 'Cannot go here without a pick or target.')\n if context.pick is not None:\n if context.pick.pick_type == PickType.PICK_POOL_EDGE:\n return TestResult.TRUE\n plex_service = services.get_plex_service()\n if plex_service.is_active_zone_a_plex():\n plex_zone_id_at_pick = plex_service.get_plex_zone_at_position(position, surface.secondary_id)\n if plex_zone_id_at_pick is not None:\n if plex_zone_id_at_pick != services.current_zone_id():\n return TestResult(False, 'Pick point in inactive plex')\n routing_location = routing.Location(position, sims4.math.Quaternion.IDENTITY(), surface)\n routing_context = context.sim.get_routing_context()\n objects_to_ignore = set()\n if target is not None:\n if target.is_sim:\n posture_target = target.posture_target\n if posture_target is not None:\n objects_to_ignore.update(posture_target.parenting_hierarchy_gen())\n if context.sim is not None:\n posture_target = context.sim.posture_target\n if posture_target is not None:\n if posture_target.vehicle_component is not None:\n posture_target = posture_target.part_owner if posture_target.is_part else posture_target\n objects_to_ignore.add(posture_target)\n try:\n for obj in objects_to_ignore:\n footprint_component = obj.footprint_component\n if footprint_component is not None:\n routing_context.ignore_footprint_contour(footprint_component.get_footprint_id())\n\n if not routing.test_connectivity_permissions_for_handle(routing.connectivity.Handle(routing_location), routing_context):\n return TestResult(False, 'Cannot GoHere! Unroutable area.')\n finally:\n for obj in objects_to_ignore:\n footprint_component = obj.footprint_component\n if footprint_component is not None:\n routing_context.remove_footprint_contour_override(footprint_component.get_footprint_id())\n\n return TestResult.TRUE","repo_name":"jolieschae/Phase-3-Sims-4-Game-Mod","sub_path":"game/decompile/simulation/interactions/go_here_test.py","file_name":"go_here_test.py","file_ext":"py","file_size_in_byte":2863,"program_lang":"python","lang":"en","doc_type":"code","stars":2,"dataset":"github-code","pt":"15"} +{"seq_id":"31861460408","text":"import pytest\nfrom invoke import context\n\nfrom noos_tf import cli\n\n\n@pytest.fixture\ndef ctx():\n return context.Context()\n\n\n@pytest.fixture(\n params=[\n (None, \"test_token\"),\n (\"test_organisation\", None),\n ]\n)\ndef secrets(request):\n return request.param\n\n\nclass TestUpdate:\n def test_invalid_credentials_raise_error(self, ctx, secrets):\n with pytest.raises(AssertionError):\n cli.update(ctx, organisation=secrets[0], token=secrets[1])\n\n\nclass TestRun:\n def test_invalid_credentials_raise_error(self, ctx, secrets):\n with pytest.raises(AssertionError):\n cli.run(ctx, organisation=secrets[0], token=secrets[1])\n","repo_name":"noosenergy/noos-terraform","sub_path":"src/tests/test_cli.py","file_name":"test_cli.py","file_ext":"py","file_size_in_byte":674,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"15"} +{"seq_id":"73902464972","text":"from queue import SimpleQueue, Empty\nfrom typing import Optional, Any, Dict, List, Union, Sequence\nfrom uuid import UUID\n\nfrom langchain.callbacks.base import BaseCallbackHandler\nfrom langchain.schema import LLMResult, Document\n\njob_done = object()\n\n\nclass ResponseCallback(BaseCallbackHandler):\n queue: SimpleQueue\n documents: Sequence[Document]\n\n def __init__(self, queue: SimpleQueue) -> None:\n self.queue = queue\n\n def on_llm_start(self, serialized: Dict[str, Any], prompts: List[str], *, run_id: UUID,\n parent_run_id: Optional[UUID] = None, tags: Optional[List[str]] = None,\n metadata: Optional[Dict[str, Any]] = None, **kwargs: Any) -> Any:\n while not self.queue.empty():\n try:\n self.queue.get(block=False)\n except Empty:\n continue\n\n def on_llm_new_token(self, token: str, *, run_id: UUID, parent_run_id: Optional[UUID] = None, **kwargs: Any) -> Any:\n self.queue.put(token)\n\n def on_llm_end(self, response: LLMResult, *, run_id: UUID, parent_run_id: Optional[UUID] = None,\n **kwargs: Any) -> Any:\n self.queue.put(job_done)\n\n def on_llm_error(self, error: Union[Exception, KeyboardInterrupt], *, run_id: UUID,\n parent_run_id: Optional[UUID] = None, **kwargs: Any) -> Any:\n self.queue.put(job_done)\n\n def on_retriever_end(self, documents: Sequence[Document], *, run_id: UUID, parent_run_id: Optional[UUID] = None,\n **kwargs: Any) -> Any:\n self.documents = documents\n","repo_name":"wellCh4n/lively-paper","sub_path":"lively_paper/views/response_callback.py","file_name":"response_callback.py","file_ext":"py","file_size_in_byte":1590,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"15"} +{"seq_id":"7082509082","text":"'''\n@Author: fzy\n@Date: 2019-05-23 14:53:54\n@LastEditors: Zhenying\n@LastEditTime: 2019-05-23 16:51:01\n@Description: \n'''\nimport numpy as np\nimport pandas as pd\nimport time\nimport argparse\nfrom utils.log_utils import get_logger\nfrom utils.color_utils import to_blue, to_cyan, to_green, to_magenta, to_red, to_yellow\n\n# ===== 加载数据集 =====\ndef load_data(filename, logg):\n # logg.info(to_blue(\"===== Loading Data =====\"))\n logg.info(\"===== Loading Data =====\")\n df = pd.read_csv(filename, header=None)\n # 获得类别标签\n labels = df.iloc[:, 0].values\n # 获得数据\n datas = df.iloc[:, 1:].values\n # 转换成二分类,分0类和非0类,将原始类别为0的标记为1,原始类别非0的标记为-1\n labels = np.where(labels > 0, 1, -1)\n # 将数据除255\n datas = datas / 255.\n # logg.info(to_blue(\"===== Loaded Data =====\"))\n logg.info(\"===== Loaded Data =====\")\n return datas, labels\n\n# ===== 感知机训练算法 =====\ndef perceptron(datas, labels, logg, args):\n # logg.info(to_cyan(\"===== start train =====\"))\n logg.info(\"===== start train =====\")\n # 得到训练数据的数量和维度\n m, n = datas.shape\n # 初始化权重和偏置\n w = np.zeros((1, n))\n b = 0\n # 初始化学习率\n eta = args.eta\n # 进行iter次迭代计算\n for now_iter in range(args.iters):\n err_cnt = 0.\n for i in range(m):\n xi = datas[i]\n yi = labels[i]\n xi = np.mat(xi)\n yi = np.mat(yi)\n # 判断是否是误分类样本\n if (-1 * yi * (w * xi.T + b)) >= 0:\n err_cnt = err_cnt + 1\n # 对于误分类样本,进行梯度下降,更新w和b\n w = w + eta * yi * xi\n b = b + eta * yi\n logg.info('Iter [{0}]:[{1}] Train Err: [{2:.4f}]'.format(now_iter, args.iters, err_cnt / float(m)))\n # logg.info(to_green('Iter [{0}]:[{1}] Train Err: [{2}]'.format(to_yellow(now_iter),\n # to_cyan(args.iters),\n # to_blue('{0:.4f}'.format(err_cnt / float(m))))))\n # logg.info(to_cyan(\"===== trained =====\"))\n logg.info(\"===== trained =====\")\n return w, b\n\n# ===== 测试代码 =====\ndef val(datas, labels, w, b, logg):\n # logg.info(to_magenta(\"===== start testing =====\"))\n logg.info(\"===== start testing =====\")\n m, n = datas.shape\n # 用来统计预测错误的个数\n errorCnt = 0\n # 对所有样本进行预测\n for i in range(m):\n xi = datas[i]\n yi = labels[i]\n xi = np.mat(xi)\n yi = np.mat(yi)\n res = -1 * yi * (w * xi.T + b)\n if res >= 0:\n errorCnt += 1\n accruRate = 1 - (errorCnt / m)\n # logg.info(to_magenta(\"===== tested =====\"))\n # logg.info(to_red(\"accRate: {0}\".format(accruRate)))\n logg.info(\"===== tested =====\")\n logg.info(\"accRate: {0}\".format(accruRate))\n return accruRate\n\n\nif __name__ == \"__main__\":\n # ===== 初始化参数 =====\n parser = argparse.ArgumentParser(description=\"perceptron\")\n parser.add_argument(\"--eta\", default=0.0001, type=int,\n help=\"eta\")\n parser.add_argument(\"--iters\", default=100, type=int,\n help=\"iters\")\n args = parser.parse_args()\n # ===== 获取logger =====\n logger = get_logger(\"perceptron\")\n # ===== 读取训练数据 =====\n train_datas, train_labels = load_data(\"../data/mnist_train.csv\", logger)\n # ===== 训练,并返回训练好的权重和偏置 =====\n w, b = perceptron(train_datas, train_labels, logger, args)\n # ===== 读取测试数据 =====\n test_datas, test_labels = load_data(\"../data/mnist_test.csv\", logger)\n # ===== 得到测试结果 =====\n accRate = val(test_datas, test_labels, w, b, logger)\n","repo_name":"zhenyingfang/Machine-Learning-Algorithm","sub_path":"perceptron/perception_algorithm.py","file_name":"perception_algorithm.py","file_ext":"py","file_size_in_byte":3910,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"15"} +{"seq_id":"39033374317","text":"# coding=utf-8\n\nfrom setuptools import setup, find_packages\nimport os\n\nversion = '1.2'\n\nsetup(name='fullmarks.tinymceplugins.asciimath',\n version=version,\n description=\"TinyMCE ASCIIMATH Plugin for Plone\",\n long_description=open(\"README.rst\").read() + \"\\n\" +\n open(os.path.join(\"docs\", \"HISTORY.txt\")).read(),\n # Get more strings from\n # http://pypi.python.org/pypi?:action=list_classifiers\n classifiers=[\n \"Framework :: Plone\",\n \"Programming Language :: Python\",\n ],\n keywords='plone math asciimath mathml tinymce',\n author='Roché Compaan',\n author_email='roche@upfrontsystems.co.za',\n url='http://github.com/fullmarks',\n license='GPL',\n packages=find_packages(exclude=['ez_setup']),\n namespace_packages=['fullmarks', 'fullmarks.tinymceplugins'],\n include_package_data=True,\n zip_safe=False,\n install_requires=[\n 'setuptools',\n # -*- Extra requirements: -*-\n 'fullmarks.mathjax',\n ],\n entry_points=\"\"\"\n # -*- Entry points: -*-\n [z3c.autoinclude.plugin]\n target = plone\n \"\"\",\n )\n","repo_name":"fullmarks/fullmarks.tinymceplugins.asciimath","sub_path":"setup.py","file_name":"setup.py","file_ext":"py","file_size_in_byte":1165,"program_lang":"python","lang":"en","doc_type":"code","stars":3,"dataset":"github-code","pt":"15"} +{"seq_id":"29413944985","text":"# -*- coding: utf-8 -*-\n\"\"\"\nCreated on Sun Aug 30 16:39:35 2015\n\n@author: jorgemirandamontano\n\"\"\"\n\n##Part 1\nimport csv\n\nwith open('chipotle.tsv', mode='rU') as f:\n file_nested_list = [row for row in csv.reader(f, delimiter='\\t')]\n \n##Part 2\nheader = file_nested_list[0]\ndata = file_nested_list[1:]\n\n##Part 3\norders=len(set([row[0] for row in data]))\nprices=[float(row[4][1:-1]) for row in data]\n\nsum(prices) /orders\n\n##Part 4\ncans = []\nother = []\nfor row in data:\n if row[2][0:6] == \"Canned\":\n cans.append(row[3])\n other.append(row[3])\n\nuniq_sodas=[set(cans)]\n\n##Part 5\n\n\n\nburrito=0\ntoppings=0\n\nfor row in data:\n if row[2][-7:-1] == 'Burrit':\n burrito +=1\n toppings += (row[3].count(',') + 1)\n\n\ntoppings/float(burrito)\n","repo_name":"dataist2019/DAT8_Class","sub_path":"Homework/chipotle_homework.py","file_name":"chipotle_homework.py","file_ext":"py","file_size_in_byte":759,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"15"} +{"seq_id":"31981100664","text":"'''\nReverse Integer\n\nGiven a signed 32-bit integer x, return x with its digits reversed. \nIf reversing x causes the value to go outside the signed 32-bit integer range [-231, 231 - 1], \nthen return 0.\n'''\n\ndef reverse(x: int) -> int:\n isNegative = True if '-' in str(x) else False\n nums = [num for num in str(x).replace('-', '')]\n reverse_int = int(''.join(nums[::-1]))\n reverse_int = -reverse_int if isNegative else reverse_int\n if reverse_int < -2**31 or reverse_int >= 2**31:\n return 0\n else:\n return reverse_int\n\n\n\nprint(reverse(123))","repo_name":"iajaykarthick/Algo-Repertoire","sub_path":"Random/ReverseInteger.py","file_name":"ReverseInteger.py","file_ext":"py","file_size_in_byte":570,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"15"} +{"seq_id":"73812454090","text":"import argparse\nimport os\nfrom typing import Optional, Tuple\n\nimport numpy as np\nfrom PIL import Image\nfrom torch.utils.data import DataLoader\nfrom torchvision.datasets.utils import download_url\nfrom tqdm import tqdm\nfrom vissl.utils.download import download_and_extract_archive\nfrom vissl.utils.io import save_file\n\n\ntry:\n import av\nexcept ImportError:\n raise ValueError(\"You must have pyav installed to run this script: pip install av.\")\n\n\ndef get_argument_parser():\n \"\"\"\n List of arguments supported by the script\n \"\"\"\n parser = argparse.ArgumentParser()\n parser.add_argument(\n \"-i\",\n \"--input\",\n type=str,\n help=\"The input folder contains the expanded UCF-101 archive files\",\n )\n parser.add_argument(\n \"-o\",\n \"--output\",\n type=str,\n help=\"The output folder containing the disk_folder output\",\n )\n parser.add_argument(\n \"-d\",\n \"--download\",\n action=\"store_const\",\n const=True,\n default=False,\n help=\"To download the original dataset and decompress it in the input folder\",\n )\n parser.add_argument(\n \"-w\",\n \"--workers\",\n type=int,\n default=8,\n help=\"Number of parallel worker used to decode videos\",\n )\n return parser\n\n\ndef download_dataset(root: str):\n \"\"\"\n Download the K700 dataset video path, annotations and videos\n \"\"\"\n\n # Download the video path and the annotations\n for split in [\"train\", \"val\"]:\n download_url(\n root=root,\n url=f\"https://s3.amazonaws.com/kinetics/700_2020/{split}/k700_2020_{split}_path.txt\",\n )\n download_url(\n root=root,\n url=f\"https://s3.amazonaws.com/kinetics/700_2020/annotations/{split}.csv\",\n )\n\n # Download all the videos and expand the archive\n for split in [\"train\", \"val\"]:\n with open(os.path.join(root, f\"k700_2020_{split}_path.txt\")) as f:\n for line in f:\n video_batch_url = line.strip()\n split_root = os.path.join(root, split)\n download_and_extract_archive(\n url=video_batch_url, download_root=split_root\n )\n\n\nclass KineticsMiddleFrameDataset:\n \"\"\"\n Dataset used to parallelize the transformation of the dataset via a DataLoader\n \"\"\"\n\n def __init__(self, data_path: str, split: str):\n self.data_path = data_path\n self.split = split\n self.split_path = os.path.join(data_path, split)\n self.video_paths = []\n self.video_labels = []\n self._init_dataset()\n\n def _init_dataset(self):\n \"\"\"\n Find all the video paths and the corresponding labels\n \"\"\"\n for label in os.listdir(self.split_path):\n label_path = os.path.join(self.split_path, label)\n if not os.path.isdir(label_path):\n continue\n\n for file_name in os.listdir(label_path):\n file_ext = os.path.splitext(file_name)[1]\n if file_ext == \".mp4\":\n self.video_paths.append(os.path.join(label_path, file_name))\n self.video_labels.append(label)\n\n @staticmethod\n def _extract_middle_frame(file_path: str) -> Optional[Image.Image]:\n \"\"\"\n Extract the middle frame out of a video clip following\n the protocol of CLIP (https://arxiv.org/pdf/2103.00020.pdf)\n at Appendix A.1\n \"\"\"\n with av.open(file_path) as container:\n if len(container.streams.video) > 0:\n nb_frames = container.streams.video[0].frames\n vid_stream = container.streams.video[0]\n for i, frame in enumerate(container.decode(vid_stream)):\n if i - 1 == nb_frames // 2:\n return frame.to_image()\n return None\n\n def __len__(self):\n return len(self.video_paths)\n\n def __getitem__(self, idx: int) -> Tuple[Image.Image, str, str, str]:\n video_path = self.video_paths[idx]\n label = self.video_labels[idx]\n mid_frame = self._extract_middle_frame(video_path)\n video_name = os.path.split(video_path)[1]\n image_name = os.path.splitext(video_name)[0] + \".jpg\"\n return mid_frame, image_name, label, video_path\n\n\ndef clean_label(label: str) -> str:\n \"\"\"\n Return a label without spaces or parenthesis\n \"\"\"\n for c in \"()\":\n label = label.replace(c, \"\")\n for c in \" \":\n label = label.replace(c, \"_\")\n return label.strip(\"_\")\n\n\ndef create_split(input_path: str, output_path: str, split: str, num_workers: int):\n \"\"\"\n Create one split of the disk_folder format and the associated disk_filelist files\n \"\"\"\n image_paths = []\n image_labels = []\n error_paths = []\n\n # Create the disk_folder format\n dataset = KineticsMiddleFrameDataset(data_path=input_path, split=split)\n loader = DataLoader(\n dataset, num_workers=num_workers, batch_size=1, collate_fn=lambda x: x[0]\n )\n for mid_frame, image_name, label, video_path in tqdm(loader, total=len(dataset)):\n if mid_frame is not None:\n label = clean_label(label)\n label_folder = os.path.join(output_path, f\"{split}_images\", label)\n os.makedirs(label_folder, exist_ok=True)\n image_path = os.path.join(label_folder, image_name)\n with open(image_path, \"w\") as image_file:\n mid_frame.save(image_file)\n image_paths.append(image_path)\n image_labels.append(label)\n else:\n error_paths.append(video_path)\n\n # Save the disk_filelist format\n save_file(\n np.array(image_paths), filename=os.path.join(output_path, f\"{split}_images.npy\")\n )\n save_file(\n np.array(image_labels),\n filename=os.path.join(output_path, f\"{split}_labels.npy\"),\n )\n if len(error_paths):\n print(f\"Number of errors in '{split}' split: {len(error_paths)}\")\n error_paths_file = os.path.join(output_path, f\"{split}_errors.npy\")\n print(f\"Errors are saved in: {error_paths_file}\")\n save_file(error_paths, filename=error_paths_file)\n\n\nif __name__ == \"__main__\":\n \"\"\"\n Example usage:\n\n ```\n python extra_scripts/datasets/create_k77_data_files.py -i /path/to/k700 -o /output_path/k700 -d\n ```\n \"\"\"\n args = get_argument_parser().parse_args()\n if args.download:\n download_dataset(args.input)\n\n for split in [\"train\", \"val\"]:\n create_split(\n input_path=args.input,\n output_path=args.output,\n split=split,\n num_workers=args.workers,\n )\n","repo_name":"facebookresearch/vissl","sub_path":"extra_scripts/datasets/create_k700_data_files.py","file_name":"create_k700_data_files.py","file_ext":"py","file_size_in_byte":6677,"program_lang":"python","lang":"en","doc_type":"code","stars":3158,"dataset":"github-code","pt":"15"} +{"seq_id":"43579627553","text":"with open(\"/Users/nicholasprice/Desktop/Development/code/advent-cal-22/day 4/day-4-data.txt\", 'r') as file:\n groups = file.read()\n\n\ndef overlap(data):\n data = \"\".join(list(data)).splitlines()\n\n ans = 0 \n\n for i in range(len(data)):\n\n nums = []\n num = []\n for j in range(len(data[i])):\n if data[i][j] != '-' and data[i][j] != ',':\n num.append(data[i][j])\n else:\n nums.append(num)\n num = []\n nums.append(num)\n \n\n for a in range(len(nums)):\n nums[a] = int(''.join(nums[a]))\n\n\n\n first = [nums[0], nums[1]]\n second = [nums[2], nums[3]]\n\n overlap = False\n \n for i in range(min(nums), max(nums) + 1):\n if i >= min(first) and i >= min(second) and i <= max(first) and i <= max(second):\n overlap = True\n \n if overlap == True:\n ans += 1\n\n print(nums)\n print(f'{first} {second} {ans}')\n\n\noverlap(groups)","repo_name":"nichprice/advent-cal-22","sub_path":"day 4/problem-2.py","file_name":"problem-2.py","file_ext":"py","file_size_in_byte":1023,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"15"} +{"seq_id":"42627415881","text":"## Joshua = 6\r\n## Lahman = 6\r\n\r\n##-----Mat1-----\r\n\r\n##initialize array1\r\nrows1, cols1 = (6, 6)\r\narr1 = [[0 for i in range(cols1)] for j in range(rows1)]\r\n\r\n# itterate every value \r\ncount = 0 \r\nfor i in (range (0,6)) :\r\n for j in (range (0,6)) : \r\n count = count + 1\r\n arr1[j][i] = count\r\n\r\n## print Mat1 \r\nprint(\"Mat1\")\r\nfor row in arr1:\r\n print(row)\r\nprint(\"\\n\")\r\n\r\n#output matrix to file\r\nwith open(r'C:\\School\\Python_Output\\JLahman_mat1.txt', 'w') as f:\r\n for row in arr1:\r\n f.writelines(str(row)+ '\\n')\r\n f.close()\r\n\r\n##-----Mat2-----\r\n\r\n##initialize array2\r\nrows2, cols2 = (6, 6)\r\narr2 = [[0 for i in range(cols2)] for j in range(rows2)]\r\n\r\n# itterate every value \r\ncount = 0 \r\nfor i in (range (0,6)) :\r\n for j in (range (0,6)) : \r\n count = count + 1\r\n arr2[i][j] = count\r\n\r\n# print Mat2 \r\nprint(\"Mat2\")\r\nfor row in arr2:\r\n print(row)\r\nprint(\"\\n\")\r\n\r\n#output matrix to file\r\nwith open(r'C:\\School\\Python_Output\\JLahman_mat2.txt', 'w') as f:\r\n for row in arr2:\r\n f.writelines(str(row)+ '\\n')\r\n f.close()\r\n\r\n##-----Mat3-----\r\n\r\n##initialize array3\r\nrows3, cols3 = (6, 6)\r\narr3 = [[0 for i in range(cols3)] for j in range(rows3)]\r\n\r\n# itterate every value \r\ncount = 0 \r\nfor i in (range (0,6)) :\r\n for j in (range (0,6)) : \r\n count = count + 1\r\n arr3[j][i] = ('%1.1f' % (count * .2))\r\n\r\n# print Mat3 \r\nprint(\"Mat3\")\r\nfor row in arr3:\r\n print(row)\r\nprint(\"\\n\")\r\n\r\n#output matrix to file\r\nwith open(r'C:\\School\\Python_Output\\JLahman_mat3.txt', 'w') as f:\r\n for row in arr3:\r\n f.writelines(str(row)+ '\\n')\r\n f.close()\r\n\r\n##-----Mat4-----\r\n\r\n##initialize array4\r\nrows4, cols4 = (4, 6)\r\narr4 = [[0 for i in range(cols4)] for j in range(rows4)]\r\n\r\n# itterate every value \r\ncount = 0 \r\nfor i in (range (0,6)) :\r\n for j in (range (0,4)) : \r\n count = count + 1\r\n arr4[j][i] = 12 - (count*2)\r\n\r\n# print Mat4 \r\nprint(\"Mat4\")\r\nfor row in arr4:\r\n print(row)\r\nprint(\"\\n\")\r\n\r\n#output matrix to file\r\nwith open(r'C:\\School\\Python_Output\\JLahman_mat4.txt', 'w') as f:\r\n for row in arr4:\r\n f.writelines(str(row)+ '\\n')\r\n f.close()\r\n\r\n##-----Mat5-----\r\n\r\n##initialize array5\r\nrows5, cols5 = (4, 6)\r\narr5 = [[0 for i in range(cols5)] for j in range(rows5)]\r\n\r\n# itterate every value \r\ncount = 0 \r\nfor i in (range (0,4)) :\r\n for j in (range (0,6)) : \r\n count = count + 1\r\n arr5[i][j] = ('%1.1f' % (1.5*count - 7.5))\r\n\r\n# print Mat5 \r\nprint(\"Mat5\")\r\nfor row in arr5:\r\n print(row)\r\nprint(\"\\n\")\r\n\r\n#output matrix to file\r\nwith open(r'C:\\School\\Python_Output\\JLahman_mat5.txt', 'w') as f:\r\n for row in arr5:\r\n f.writelines(str(row)+ '\\n')\r\n f.close()\r\n\r\n##-----Mat6-----\r\n\r\n##initialize array6\r\nrows6, cols6 = (2, 4)\r\narr6 = [[0 for i in range(cols6)] for j in range(rows6)]\r\n\r\n# itterate every value \r\ncount = 0 \r\nfor i in (range (0,2)) :\r\n for j in (range (0,4)) : \r\n count = count + 1\r\n arr6[i][j] = (10*count - 20)\r\n\r\n# print Mat6 \r\nprint(\"Mat6\")\r\nfor row in arr6:\r\n print(row)\r\nprint(\"\\n\")\r\n\r\n#output matrix to file\r\nwith open(r'C:\\School\\Python_Output\\JLahman_mat6.txt', 'w') as f:\r\n for row in arr6:\r\n f.writelines(str(row)+ '\\n')\r\n f.close()","repo_name":"Joshua-Lahman/Program1","sub_path":"JLahman_p1.py","file_name":"JLahman_p1.py","file_ext":"py","file_size_in_byte":3265,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"15"} +{"seq_id":"18605395772","text":"# Funcao de ordenacao de arrays, nao tao eficiente quanto o quicksort.\n# Complexidade de O(n^2)\ndef indice_menor(lista):\n menor = lista[0]\n idx_menor = 0\n for i in range(1, len(lista)):\n if (lista[i] < menor):\n menor = lista[i]\n idx_menor = i\n return idx_menor\n\ndef ordenacao_selecao(lista):\n ret = []\n for i in range(len(lista)):\n idx_menor = indice_menor(lista)\n ret.append(lista.pop(idx_menor))\n return ret\n\nminha_lista = [7, 2, 4, 10, 21, 12]\nprint(ordenacao_selecao(minha_lista))","repo_name":"rafael-dosso/exercicios-algoritmos","sub_path":"ordenacao_selecao.py","file_name":"ordenacao_selecao.py","file_ext":"py","file_size_in_byte":548,"program_lang":"python","lang":"pt","doc_type":"code","stars":0,"dataset":"github-code","pt":"15"} +{"seq_id":"73888283851","text":"# ~~~~~============== HOW TO RUN ==============~~~~~\n# 1) Configure things in CONFIGURATION section\n# 2) Change permissions: chmod +x bot.py\n# 3) Run in loop: while true; do ./bot.py; sleep 1; done\n\nfrom __future__ import print_function\n\nimport sys\nimport socket\nimport json\nimport time\nimport math\nfrom collections import deque\n# ~~~~~============== CONFIGURATION ==============~~~~~\n# replace REPLACEME with your team name!\nteam_name=\"UNREGISTERED\"\n# This variable dictates whether or not the bot is connecting to the prod\n# or test exchange. Be careful with this switch!\ntest_mode = True\n\n# This setting changes which test exchange is connected to.\n# 0 is prod-like\n# 1 is slower\n# 2 is empty\ntest_exchange_index=0\nprod_exchange_hostname=\"production\"\n\n\n# Data Set of stock in action.\n# Dictionary tree\n# Symbol\n# set of data(100)\n# mean sell value \n# mean buy value\n\nData = {}\n\n# Trading in action(id)\norder_id_inaction = {} \n\n# Trade trace:\ntrade_track = {}\n\n# Track profit\nprofit = 0\n\nport=25000 + (test_exchange_index if test_mode else 0)\nexchange_hostname = \"test-exch-\" + team_name if test_mode else prod_exchange_hostname\nprint (exchange_hostname)\n# ~~~~~============== NETWORKING CODE ==============~~~~~\ndef connect():\n s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)\n s.connect((exchange_hostname, port))\n return s.makefile('rw', 1)\n\ndef write_to_exchange(exchange, obj):\n json.dump(obj, exchange)\n exchange.write(\"\\n\")\n\ndef read_from_exchange(exchange):\n return json.loads(exchange.readline())\n\n\n# ~~~~~============== MAIN LOOP ==============~~~~~\n\ndef main():\n exchange = connect()\n write_to_exchange(exchange, {\"type\": \"hello\", \"team\": team_name.upper()})\n hello_from_exchange = read_from_exchange(exchange)\n # A common mistake people make is to call write_to_exchange() > 1\n # time for every read_from_exchange() response.\n # Since many write messages generate marketdata, this will cause an\n # exponential explosion in pending messages. Please, don't do that!\n print(\"The exchange replied:\", hello_from_exchange, file=sys.stderr)\n symbols = read_from_exchange(exchange)[\"symbols\"]\n for symbol in symbols:\n Data[symbol] = {\"latest_data\":[],\"sell_mean\":0,\"buy_mean\":0,\"data_set\":deque(),\"trading_inaction\":{}}\n print (Data)\n # number to symbols. \n symbol_dict = {}\n for i in range(len(symbols)):\n symbol_dict[i] = symbols[i]\n\n order_count =0\n\n\n #section 2 variable\n BABAZ_FV = [(0,0),(0,0)]\n while True:\n # Get data of market\n try:\n lastest_data = read_from_exchange(exchange)\n except:\n print(\"Unexpected error:\", sys.exc_info()[0])\n raise\n # print (lastest_data)\n if lastest_data[\"type\"] == \"book\" :\n # Set Data\n symbol = lastest_data[\"symbol\"]\n symbol_data = Data[symbol]\n\n data_set = symbol_data[\"data_set\"]\n count = 0\n sum_buy = 0\n sum_sell = 0\n # Get mean of sell\n for price,amount in lastest_data[\"sell\"]:\n sum_sell = price*amount\n if len(lastest_data[\"sell\"]):\n mean_sell = sum_sell/len(lastest_data[\"sell\"]) \n else:\n mean_sell = symbol_data[\"sell_mean\"]\n # Get mean of buy\n for price,amount in lastest_data[\"buy\"]:\n sum_buy = price*amount\n if len(lastest_data[\"buy\"]):\n mean_buy = sum_buy/len(lastest_data[\"buy\"])\n else:\n mean_buy = symbol_data[\"buy_mean\"]\n\n data_set.append([mean_sell,mean_buy])\n data_remove = data_set.popleft()\n\n\n # No data set \n if not symbol_data[\"latest_data\"]:\n symbol_data[\"sell_mean\"] = mean_sell\n symbol_data[\"buy_mean\"] = mean_buy\n \n else:\n sell_entire_mean = symbol_data[\"sell_mean\"]\n sell_entire_mean = sell_entire_mean + (mean_sell - data_remove[0])\n # print (\"sell:\",sell_entire_mean,mean_sell)\n if sell_entire_mean > mean_sell :\n trade = {\"type\": \"add\", \"order_id\":order_count , \"symbol\": symbol, \"dir\": \"SELL\", \"price\": (sell_entire_mean + mean_sell)/2, \"size\": 2}\n write_to_exchange(exchange,trade)\n order_id_inaction[order_count] = trade\n order_count += 1 \n\n buy_entire_mean = symbol_data[\"buy_mean\"]\n buy_entire_mean = buy_entire_mean + (mean_buy - data_remove[1])\n # print (\"buy:\",buy_entire_mean,mean_buy)\n if buy_entire_mean < mean_buy:\n trade = {\"type\": \"add\", \"order_id\":order_count , \"symbol\": symbol, \"dir\": \"BUY\", \"price\": (mean_buy + buy_entire_mean)/2, \"size\": 2}\n write_to_exchange(exchange,trade)\n order_count += 1 \n \n symbol_data[\"latest_data\"] = lastest_data\n\n # 1. Bond exchange\n # Process data with only bonds.\n # if symbol ==\"Bond\":\n \n \n\n\n # trade = {\"type\": \"add\", \"order_id\":order_count , \"symbol\": \"BOND\", \"dir\": \"SELL\", \"price\": 1001, \"size\": 10}\n # write_to_exchange(exchange,trade)\n # order_count += 1\n # trade = {\"type\": \"add\", \"order_id\":order_count , \"symbol\": \"BOND\", \"dir\": \"BUY\", \"price\": 999, \"size\": 10}\n # write_to_exchange(exchange,trade)\n # order_count += 1 \n \n # # Part 2 Fair trade BABA,BABZ:\n # if symbol == \"BABZ\" or symbol == \"BABA\": \n # BABAZ = Data[symbol]\n # # print(BABAZ)\n # sell_value = float(\"inf\")\n # buy_value = -float(\"inf\")\n # for price, amount in BABAZ[\"sell\"] :\n # sell_value = min(sell_value,price)\n # for price, amount in BABAZ[\"buy\"] :\n # buy_value = max(buy_value,price)\n # mean = (sell_value+buy_value)/2\n # # Base case\n # if BABAZ_FV[0] == (0,0):\n # BABAZ_FV[0] = (sell_value,buy_value)\n # elif BABAZ_FV[0] == (0,0):\n # BABAZ_FV[1] = (sell_value,buy_value)\n # else:\n # if symbol == \"BABA\":\n # BABAZ_FV[0] = (sell_value,buy_value)\n # else:\n # BABAZ_FV[1] = (sell_value,buy_value)\n \n # BABA = BABAZ_FV[0]\n # BABZ = BABAZ_FV[1]\n # # completely encompassing\n # if BABA[0] >= BABZ[0] and BABA[1] <= BABZ[1]:\n # fv = (BABZ[0]+BABZ[1])/2\n # #BABZ is less.\n # elif BABA[0] > BABZ[0]:\n # fv = (BABZ[1]+BABA[0])/2\n # else:\n # fv = (BABZ[0]+BABA[1])/2\n # #fv of BABZ\n # trade = {\"type\": \"add\", \"order_id\":order_count , \"symbol\": \"BABA\", \"dir\": \"BUY\", \"price\": fv+1, \"size\": 10}\n # order_count +=1\n # write_to_exchange(exchange,trade)\n # trade = {\"type\": \"add\", \"order_id\":order_count , \"symbol\": \"BABA\", \"dir\": \"SELL\", \"price\": fv-1, \"size\": 10}\n # write_to_exchange(exchange,trade)\n # order_count+=1\n\n\n elif lastest_data[\"type\"] == \"error\":\n print (\"Error processing Order\")\n elif lastest_data[\"type\"] == \"reject\":\n order_id = order_id_inaction.pop(latest_data[\"order_id\"])\n elif lastest_data[\"type\"] == \"fill\":\n order_id = latest_data[\"order_id\"]\n price = lastest_data[\"price\"]\n size = lastest_data[\"size\"]\n Buy_sell = lastest_data[\"dir\"]\n symbol = lastest_data[\"symbol\"]\n\n cur_order = order_id_inaction[order_id]\n cur_size = cur_order[\"size\"]\n cur_price = cur_order[\"size\"]\n \n trade_track[\"price\"]\n\n cur_size -= size\n if cur_size == 0:\n order_id_inaction.pop(order_id)\n if price!= cur_price:\n cur_profit = abs(price-cur_price)*size\n print (\"Profit trade price difference : \", cur_profit)\n profit += cur_profit\n print (\"Total profit: \",profit)\n \n \n\n\n \n\n print (Buy_sell, \" price:\",price,\" amount:\",amount)\n \n\n\n\n \n {\"type\":\"fill\",\"order_id\":N,\"symbol\":\"SYM\",\"dir\":\"BUY\",\"price\":N,\"size\":N}\n\n \n \n \n\n\n \n \n\n\nif __name__ == \"__main__\":\n main()\n\n","repo_name":"frank217/JSTEC","sub_path":"version/exchange3.py","file_name":"exchange3.py","file_ext":"py","file_size_in_byte":8919,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"15"} +{"seq_id":"43592590663","text":"class Trie:\n\n def __init__(self):\n self.head = TrieNode()\n\n def insert(self, word: str) -> None:\n curr = self.head\n for w in word:\n if not curr.char[ord(w)-97]:\n curr.char[ord(w)-97] = TrieNode()\n curr = curr.char[ord(w)-97]\n curr.isEnd = True\n\n def search(self, word: str) -> bool:\n curr = self.head\n for w in word:\n if not curr.char[ord(w)-97]:\n return False\n curr = curr.char[ord(w)-97]\n return curr.isEnd\n\n def startsWith(self, prefix: str) -> bool:\n curr = self.head\n for w in prefix:\n if not curr.char[ord(w)-97]:\n return False\n curr = curr.char[ord(w)-97]\n return True\n \n \n###########################################################\n \nclass TrieNode:\n def __init__(self):\n self.char = [None]*26\n self.isEnd = False\n\n# Your Trie object will be instantiated and called as such:\n# obj = Trie()\n# obj.insert(word)\n# param_2 = obj.search(word)\n# param_3 = obj.startsWith(prefix)","repo_name":"aryanbk/Questions","sub_path":"0208-implement-trie-prefix-tree/0208-implement-trie-prefix-tree.py","file_name":"0208-implement-trie-prefix-tree.py","file_ext":"py","file_size_in_byte":1111,"program_lang":"python","lang":"en","doc_type":"code","stars":2,"dataset":"github-code","pt":"15"} +{"seq_id":"41088701103","text":"def selection_sort(list):\n sorted_list = []\n while len(list) > 0:\n sorted_list.append(list.pop(smallest(list)))\n return sorted_list\n\n\ndef smallest(list):\n smallest = list[0]\n position = 0\n for x in range(len(list)):\n if list[x] < smallest:\n smallest = list[x]\n position = x\n return position\n\n\nimport unittest\nclass SelectionSortTest(unittest.TestCase):\n\n unsorted = [3, 8, 15, 1, 6, 3 ,2, 5, 99, 43, 77, 23, 12, 1]\n sorted_list = [1, 1, 2, 3, 3, 5, 6, 8, 12, 15, 23, 43, 77, 99]\n\n def test_selection_sort(self):\n self.assertEqual(self.sorted_list, selection_sort(self.unsorted))\n\n\nif __name__ == \"__main__\":\n unittest.main()\n","repo_name":"erickmiller/AutomatousSourceCode","sub_path":"AutonomousSourceCode/data/raw/sort/adfd5ea9-c96d-44b1-987f-7779028406f9__selection_sort.py","file_name":"adfd5ea9-c96d-44b1-987f-7779028406f9__selection_sort.py","file_ext":"py","file_size_in_byte":701,"program_lang":"python","lang":"en","doc_type":"code","stars":3,"dataset":"github-code","pt":"15"} +{"seq_id":"19703042393","text":"import os\nimport azure.cognitiveservices.speech as speechsdk\n\nasync def speech_continuous_recognition(audio_file_path, transcript_file_path):\n speech_config = speechsdk.SpeechConfig(subscription=os.getenv(\"SPEECH_KEY\"), region=os.getenv(\"SPEECH_REGION\"))\n audio_config = speechsdk.audio.AudioConfig(use_default_microphone=False, filename=audio_file_path)\n speech_recognizer = speechsdk.SpeechRecognizer(speech_config=speech_config,\n audio_config=audio_config)\n \n def stop_cb(evt):\n print('CLOSING on {}'.format(evt))\n speech_recognizer.stop_continuous_recognition()\n # + END_OF_TRANSCRIPT\n\n def write_transcript(evt):\n with open(transcript_file_path, \"a\") as tfile:\n tfile.write(evt.result.text + \"\\n\")\n\n # For long-running multi-utterance recognition, use start_continuous_recognition() instead.\n speech_recognizer.recognized.connect(write_transcript)\n speech_recognizer.session_stopped.connect(stop_cb)\n speech_recognizer.canceled.connect(stop_cb)\n\n\n speech_recognizer.start_continuous_recognition()\n ","repo_name":"Priyam-bit/podcast_pulse","sub_path":"app/core/transcribe.py","file_name":"transcribe.py","file_ext":"py","file_size_in_byte":1129,"program_lang":"python","lang":"en","doc_type":"code","dataset":"github-code","pt":"15"} +{"seq_id":"31470675854","text":"from datetime import datetime, timedelta\n\nimport numpy\n\nfrom labours.plotting import apply_plot_style, deploy_plot, get_plot_path, import_pyplot\nfrom labours.utils import parse_date\n\n\ndef show_sentiment_stats(args, name, resample, start_date, data):\n from scipy.signal import convolve, slepian\n\n matplotlib, pyplot = import_pyplot(args.backend, args.style)\n\n start_date = datetime.fromtimestamp(start_date)\n data = sorted(data.items())\n mood = numpy.zeros(data[-1][0] + 1, dtype=numpy.float32)\n timeline = numpy.array(\n [start_date + timedelta(days=i) for i in range(mood.shape[0])]\n )\n for d, val in data:\n mood[d] = (0.5 - val.Value) * 2\n resolution = 32\n window = slepian(len(timeline) // resolution, 0.5)\n window /= window.sum()\n mood_smooth = convolve(mood, window, \"same\")\n pos = mood_smooth.copy()\n pos[pos < 0] = 0\n neg = mood_smooth.copy()\n neg[neg >= 0] = 0\n resolution = 4\n window = numpy.ones(len(timeline) // resolution)\n window /= window.sum()\n avg = convolve(mood, window, \"same\")\n pyplot.fill_between(timeline, pos, color=\"#8DB843\", label=\"Positive\")\n pyplot.fill_between(timeline, neg, color=\"#E14C35\", label=\"Negative\")\n pyplot.plot(timeline, avg, color=\"grey\", label=\"Average\", linewidth=5)\n legend = pyplot.legend(loc=1, fontsize=args.font_size)\n pyplot.ylabel(\"Comment sentiment\")\n pyplot.xlabel(\"Time\")\n apply_plot_style(\n pyplot.gcf(), pyplot.gca(), legend, args.background, args.font_size, args.size\n )\n pyplot.xlim(\n parse_date(args.start_date, timeline[0]),\n parse_date(args.end_date, timeline[-1]),\n )\n locator = pyplot.gca().xaxis.get_major_locator()\n # set the optimal xticks locator\n if \"M\" not in resample:\n pyplot.gca().xaxis.set_major_locator(matplotlib.dates.YearLocator())\n locs = pyplot.gca().get_xticks().tolist()\n if len(locs) >= 16:\n pyplot.gca().xaxis.set_major_locator(matplotlib.dates.YearLocator())\n locs = pyplot.gca().get_xticks().tolist()\n if len(locs) >= 16:\n pyplot.gca().xaxis.set_major_locator(locator)\n if locs[0] < pyplot.xlim()[0]:\n del locs[0]\n endindex = -1\n if len(locs) >= 2 and pyplot.xlim()[1] - locs[-1] > (locs[-1] - locs[-2]) / 2:\n locs.append(pyplot.xlim()[1])\n endindex = len(locs) - 1\n startindex = -1\n if len(locs) >= 2 and locs[0] - pyplot.xlim()[0] > (locs[1] - locs[0]) / 2:\n locs.append(pyplot.xlim()[0])\n startindex = len(locs) - 1\n pyplot.gca().set_xticks(locs)\n # hacking time!\n labels = pyplot.gca().get_xticklabels()\n if startindex >= 0:\n labels[startindex].set_text(timeline[0].date())\n labels[startindex].set_text = lambda _: None\n labels[startindex].set_rotation(30)\n labels[startindex].set_ha(\"right\")\n if endindex >= 0:\n labels[endindex].set_text(timeline[-1].date())\n labels[endindex].set_text = lambda _: None\n labels[endindex].set_rotation(30)\n labels[endindex].set_ha(\"right\")\n overall_pos = sum(2 * (0.5 - d[1].Value) for d in data if d[1].Value < 0.5)\n overall_neg = sum(2 * (d[1].Value - 0.5) for d in data if d[1].Value > 0.5)\n title = \"%s sentiment +%.1f -%.1f δ=%.1f\" % (\n name,\n overall_pos,\n overall_neg,\n overall_pos - overall_neg,\n )\n if args.mode == \"all\" and args.output:\n output = get_plot_path(args.output, \"sentiment\")\n else:\n output = args.output\n deploy_plot(title, output, args.background)\n","repo_name":"src-d/hercules","sub_path":"python/labours/modes/sentiment.py","file_name":"sentiment.py","file_ext":"py","file_size_in_byte":3556,"program_lang":"python","lang":"en","doc_type":"code","stars":1961,"dataset":"github-code","pt":"15"} +{"seq_id":"3288409343","text":"\"\"\"\n This script is for removing PTM assigned by the open search that are not\n true using PTMProphet post-processing.\n\"\"\"\nimport re\nimport sys\n\nfrom pyteomics import mass\n\nimport numpy as np\nfrom Bio import SeqIO\n\n\ndef verify_unimod(site, position):\n if not re.match(\"^[A-Z]$\", site):\n if site not in ['N-term', 'C-term']:\n raise ValueError('{}: Not A unimod site'.format(site))\n\n positions = [\n \"Anywhere\", \"Any N-term\", \"Any C-term\", \"Protein C-term\",\n \"Protein N-term\"\n ]\n if position not in positions:\n raise ValueError('{}: Not A unimod position'.format(position))\n\n\ndef _unimod_parser_map():\n '''\n create UNIMOD dictionairy {mono_mass -> full name (mono_mass)}\n '''\n unimod_dict = {}\n # connect UNIMOD database\n unimod_db = mass.Unimod(source='http://www.unimod.org/xml/unimod.xml')\n step = 0.0001\n for mod in unimod_db.mods:\n for site in mod['specificity']:\n err = 0.01 # dalton\n for mono_mass in np.arange(round(mod['mono_mass'] - err, 4),\n round(mod['mono_mass'] + err, 4) + step,\n step):\n key = str(round(mono_mass, 4))\n value = mod['full_name'] + '(' + str(\n round(mod['mono_mass'], 3)) + ')'\n try:\n unimod_dict[key].append(value)\n except KeyError:\n unimod_dict[key] = []\n unimod_dict[key].append(value)\n return unimod_dict\n\n\ndef _unimod_parser_():\n \"\"\"\n return:\n (dict) {\n \"PTM name/title\": {\n \"site\": [\"amino acid\" / \"N-term\" / C-term\"],\n \"Position\": [\"Anywhere\", \"Any N-term\", \"Any C-term\",\n \"Protein N-term\", \"Protein C-term\"]\n \"Mono_mass\": (float)\n }\n }\n \"\"\"\n desc_dict = {}\n # connect UNIMOD database\n unimod_db = mass.Unimod(source='http://www.unimod.org/xml/unimod.xml')\n for mod in unimod_db.mods:\n for name in ['full_name', 'title']:\n desc_dict[mod[name]] = {}\n desc_dict[mod[name]]['mono_mass'] = mod['mono_mass']\n site = [x['site'] for x in mod['specificity']]\n pos = [x['position'] for x in mod['specificity']]\n desc_dict[mod[name]]['site'] = site\n desc_dict[mod[name]]['position'] = pos\n return desc_dict\n\n\ndef prot_term_checker(peptide, mapped_proteins, db_dict):\n \"\"\"\n checks if the peptide falls on the Protein N/C-term\n \"\"\"\n conv_dict = {}\n conv_dict['N-term'] = 0\n conv_dict['C-term'] = len(peptide) - 1\n\n is_prot_nterm = []\n is_prot_cterm = []\n\n for protein in mapped_proteins:\n try:\n seq = str(db_dict[protein].seq)\n except KeyError:\n return None, None\n try:\n pep_start = seq.index(peptide) + 1\n except ValueError:\n peptide = peptide.replace('I', 'L')\n seq = seq.replace('I', 'L')\n pep_start = seq.index(peptide) + 1\n except ValueError:\n return None, None\n pep_end = pep_start + conv_dict['C-term']\n protein_end = len(seq)\n is_prot_cterm.append(pep_end == protein_end)\n is_prot_nterm.append(pep_start == 1)\n is_prot_nterm = any(is_prot_nterm)\n is_prot_cterm = any(is_prot_cterm)\n return is_prot_nterm, is_prot_cterm\n\n\ndef get_modified_aa(modified_pep):\n \"\"\"\n Given a PTMProphet format modified peptide, return a (dict)\n {\n \"amino acid letter\": [position of the modification starting from 1],\n ...\n }\n \"\"\"\n aa_dict_ = {}\n aa_index = 0\n for index, aa in enumerate(modified_pep):\n if aa.islower():\n aa = aa.upper()\n try:\n aa_dict_[aa].append(aa_index)\n except KeyError:\n aa_dict_[aa] = [index + 1]\n return aa_dict_\n\n\ndef verify_ptm(peptide, unimod, mod_name, aa_dict, is_prot_nterm,\n is_prot_cterm):\n \"\"\"\n Given a modification name, a dict of a peptide modified positions\n returns :\n - new moodification string format:\n \"position modification_name(average mass)\"\n\n \"\"\"\n new_mod = None\n\n original_mod = mod_name\n mod_name = mod_name.rsplit('(', 1)[0]\n mod_mass = original_mod.rsplit('(', 1)[1][:-1]\n try:\n mod_sites = unimod[mod_name]['site']\n mod_pos = unimod[mod_name]['position']\n except KeyError:\n return new_mod\n for site, position in zip(mod_sites, mod_pos):\n verify_unimod(site, position)\n original_site = site\n if \"N-term\" in site:\n site = 0\n elif \"C-term\" in site:\n site = len(peptide) - 1\n try:\n for pep_pos_loc in aa_dict[site]:\n if 'N-term' in position:\n if pep_pos_loc != 1:\n pep_pos_loc = -1\n if 'Prot' in position and not is_prot_nterm:\n pep_pos_loc = -1\n elif 'C-term' in position:\n if pep_pos_loc != len(peptide):\n pep_pos_loc = -1\n if 'Prot' in position and not is_prot_cterm:\n pep_pos_loc = -1\n if pep_pos_loc != -1:\n new_mod = mod_mass + '@' + str(pep_pos_loc) \n except KeyError:\n pass\n return new_mod\n\n\ndef unimod_annotate_tsv(input_file, database_file): \n DB = SeqIO.index(database_file, 'fasta')\n unimod = _unimod_parser_()\n unimod_map = _unimod_parser_map()\n list_of_mods = {}\n\n # pattern = re.compile('.+\\(([0-9]+\\.[0-9]+)\\)')\n fh = open(input_file)\n\n cols = {}\n header = fh.readline().strip('\\n').split('\\t')\n for index, col in enumerate(header):\n cols[col] = index\n modifications = []\n for line in fh:\n line = line.strip('\\n').split('\\t')\n modified_pep = line[cols['best_locs']]\n peptide = line[cols['peptide']]\n if modified_pep != '':\n try:\n massdiff = f\"{round(float(line[cols['massdiff']]), 4):.4f}\"\n obs_mods = list(set(unimod_map[massdiff]))\n except KeyError:\n modifications.append([])\n continue\n else:\n modifications.append([])\n continue\n # get the modified amino acids\n aa_dict = get_modified_aa(modified_pep)\n # get a listed of the mapped proteins\n list_mapped_prot = [line[cols['protein']].split(' ')[0]]\n # check if it's a Protein N/C-term peptide\n is_prot_nterm, is_prot_cterm = prot_term_checker(\n peptide, list_mapped_prot, DB)\n # in case something went wrong\n if is_prot_nterm is None or is_prot_cterm is None:\n modifications.append([])\n continue\n new_mod_line = []\n # for each suggested unimod modification\n for mod in obs_mods:\n new_mod = verify_ptm(peptide, unimod, mod, aa_dict,\n is_prot_nterm, is_prot_cterm)\n # if the PTM sis verified\n if new_mod:\n new_mod_line.append(new_mod)\n\n # in case no PTM got verified\n if not new_mod_line:\n modifications.append([])\n continue\n # replace the value of \"Observed Modifications\"\n modifications.append(new_mod_line)\n fh.close()\n\n return modifications","repo_name":"immuno-informatics/COD-dipp","sub_path":"scripts/Scavager-0.1.9_combined/scavager/scavager_opensearch_filtering.py","file_name":"scavager_opensearch_filtering.py","file_ext":"py","file_size_in_byte":7600,"program_lang":"python","lang":"en","doc_type":"code","stars":3,"dataset":"github-code","pt":"15"} +{"seq_id":"11106125095","text":"import csv, math\n\n# Assumes the information about the current semester is in a file called grades.csv\n# File Structure Example\n# course,units,grade\n# courseA,4,8\n# courseB,4,8\n# courseC,4,10\n# .\n# .\n# .\n\ncurrent_gpa = float(input(\"Current GPA - \"))\ncurrent_units = int(input(\"Current Units - \"))\ncurrent_creds = math.ceil(current_gpa*current_units)\n\nreader = csv.DictReader(open(\"grades.csv\"))\nunits = 0\ncreds = 0\nfor row in reader:\n units += int(row[\"units\"])\n creds += int(row[\"units\"])*int(row[\"grade\"])\n\nsgpa = round(creds/units, 3)\ngpa = round((current_creds + creds)/(current_units + units), 3)\n\nprint(\"-----------------------\")\nprint(\"Calculated SGPA - {}\".format(sgpa))\nprint(\"Calculated GPA - {}\".format(gpa))","repo_name":"v-shenoy/py-scripts","sub_path":"gpa_calculator/gpa_calculator.py","file_name":"gpa_calculator.py","file_ext":"py","file_size_in_byte":730,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"15"} +{"seq_id":"71550827213","text":"import math\nlog=math.log10\n# def calcDWf(roughness,ID,Re):\n# \t\"\"\"\n# \tgoudar-sonar eq for D-W f\n# \t\"\"\"\n# \ta=2/math.log(10)\n# \tb=roughness/(ID*3.7)\n# \td=math.log(10)*Re/(5.02)\n# \ts=b*d+math.log(d)\n# \tq=s**(s/(s+1))\n# \tg=b*d+math.log(d/q)\n# \tz=math.log(q/g)\n# \tdLA=z*g/(g+1)\n# \tdCFA=dLA*(1+(z/2)/(((g+1)**2)+(z/3.0)*(2*g-1)))\n# \tf=(a*(math.log(d/q)+dCFA))**-2\n# \treturn f\ndef calcDWf(roughness,ID,Re):\n\tif Re<2000:\n\t\treturn 64./Re\n\telse:\n\t\tF=lambda F: -2*log(roughness/(3.7*ID)+2.51*F/Re)\n\t\tF0=1/math.sqrt(.0001)\n\t\ttol=1/math.sqrt(1e-7)\n\t\terror=tol+1\n\t\twhile error>tol:\n\t\t\tF1=F(F0)\n\t\t\terror=abs(F1-F0)\n\t\t\tF0=F1\n\t\tf=1/(F1**2)\n\t\treturn f\ndef calcFf(roughness,ID,Re):\n\treturn calcDWf(roughness,ID,Re)/4","repo_name":"edgyUsername/TiebackSim","sub_path":"simulation/fluid_flow/g_s.py","file_name":"g_s.py","file_ext":"py","file_size_in_byte":696,"program_lang":"python","lang":"en","doc_type":"code","stars":3,"dataset":"github-code","pt":"15"} +{"seq_id":"27505102161","text":"# -*- mode: python ; coding: utf-8 -*-\nimport sys\nsys.setrecursionlimit(9000)\n\nblock_cipher = None\n\n\na = Analysis(['aboth.py'],\n pathex=['D:\\\\aboth\\\\aboth'],\n binaries=[],\n datas=[],\n hiddenimports=['sklearn.utils._cython_blas', 'sklearn.neighbors.typedefs','sklearn.neighbors.quad_tree','sklearn.tree._utils', 'pkg_resources.py2_warn'],\n hookspath=[],\n runtime_hooks=[],\n excludes=[],\n win_no_prefer_redirects=False,\n win_private_assemblies=False,\n cipher=block_cipher,\n noarchive=False)\n\t\t\t \npyz = PYZ(a.pure, a.zipped_data,\n cipher=block_cipher)\nexe = EXE(pyz,\n a.scripts,\n a.binaries,\n a.zipfiles,\n a.datas,\n [],\n name='aboth',\n debug=False,\n bootloader_ignore_signals=False,\n strip=False,\n upx=True,\n upx_exclude=[],\n console=True )\n","repo_name":"Pilonetto/aboth-","sub_path":"aboth.spec","file_name":"aboth.spec","file_ext":"spec","file_size_in_byte":990,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"15"} +{"seq_id":"3193896290","text":"import pytz\nimport os\nfrom datetime import datetime, timedelta\n\nCST = pytz.timezone('America/Chicago')\ndir_path = 'data/submission_records'\n\n\ndef get_CST_current():\n return datetime.now(CST)\n\n\ndef records_dir_check():\n if not os.path.exists(dir_path):\n os.mkdir(dir_path)\n\n\ndef trans_submission_date(submission_time):\n cur_time = get_CST_current()\n time_li = submission_time.strip().split(' ')\n time_diff = timedelta(days=0)\n # ignore mins and seconds\n # mins and seconds ago means just right now...\n if time_li[1] in 'days':\n if time_li[0] == 'a':\n time_diff = timedelta(days=1)\n else:\n time_diff = timedelta(days=int(time_li[0]))\n elif time_li[1] in 'hours':\n if time_li[0] in 'an':\n time_diff = timedelta(hours=1)\n else:\n time_diff = timedelta(hours=int(time_li[0]))\n submission_time = cur_time - time_diff\n return (submission_time, submission_time.isocalendar())\n\n\ndef create_record(path):\n records_dir_check()\n record_path = dir_path + '/' + path\n file_exist = os.path.exists(record_path)\n if not file_exist:\n file = open(record_path, 'w')\n file.close()\n return record_path\n","repo_name":"Samxus/leetcode-checkin-script","sub_path":"time_utils.py","file_name":"time_utils.py","file_ext":"py","file_size_in_byte":1220,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"15"} +{"seq_id":"16984786542","text":"from random import shuffle as kever\ndef insertionSort(arr):\n for i in range(1, len(arr)):\n key = arr[i]\n j = i - 1\n while j >= 0 and key < arr[j] :\n arr[j + 1] = arr[j]\n j -= 1\n arr[j + 1] = key\narr = list(range(30))\nkever(arr)\nprint(* arr)\ninsertionSort(arr)\nprint(* arr)","repo_name":"tomuwhu/tig","sub_path":"py/inssort.py","file_name":"inssort.py","file_ext":"py","file_size_in_byte":333,"program_lang":"python","lang":"en","doc_type":"code","stars":2,"dataset":"github-code","pt":"15"} +{"seq_id":"71590608013","text":"from collections import deque\n\ndef solution(maps):\n answer = 0\n global N, M\n N = len(maps); M = len(maps[0])\n visited = [[0 for _ in range(M)] for _ in range(N)]\n answer = bfs(maps, (0,0), visited)\n return answer\n\ndef bfs(graph, v, visited):\n x,y = v\n queue = deque()\n queue.append((x,y))\n visited[x][y] = 1\n \n while queue:\n x,y = queue.popleft()\n \n for dx,dy in [[-1,0],[1,0],[0,-1],[0,1]]:\n new_x = x+dx; new_y = y+dy\n if new_x<0 or new_x>=N or new_y<0 or new_y>=M:\n continue\n elif new_x==N-1 and new_y==M-1:\n return visited[x][y]+1\n elif graph[new_x][new_y]==1 and not visited[new_x][new_y]:\n visited[new_x][new_y] = visited[x][y]+1\n queue.append((new_x,new_y))\n \n return -1","repo_name":"Jhryu30/CodingDiary","sub_path":"프로그래머스/lv2/1844. 게임 맵 최단거리/게임 맵 최단거리.py","file_name":"게임 맵 최단거리.py","file_ext":"py","file_size_in_byte":856,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"15"} +{"seq_id":"10407642290","text":"#!/usr/bin/python\n#-*-coding:utf-8-*-\n'''@author:duncan'''\n\n# 该脚本为与neo4j交互层\n\n\nfrom neo4j.v1 import GraphDatabase,basic_auth\n\n\n\n\n\ndef Conn():\n # 加载驱动\n # 加密方式\n driver = GraphDatabase.driver(\"bolt://localhost:7687\",auth=basic_auth(\"neo4j\",\"123\"),encrypted=True)\n # 创建会话\n session = driver.session()\n return driver,session\n\ndef Close(session,driver):\n session.close()\n driver.close()\n\ndef CreateNodesFromCSV(path):\n '''\n :param path: CSV文件路径\n :return:\n '''\n driver,session = Conn()\n # 从CSV文件中创建结点\n statement = \"LOAD CSV WITH HEADERS FROM '%s' AS line\\\n CREATE (:TwitterUser { name:line.userid,userid: line.userid, screen_name:line.screen_name,followers_count:toInt(line.followers_count),friends_count:toInt(line.friends_count),favourites_count:line.favourites_count,location:line.location,verified:toInt(line.verified),category:line.category})\" % path\n # # 利用事务运行query\n with session.begin_transaction() as tx:\n tx.run(statement)\n tx.success = True\n # session.run(statement)\n Close(session,driver)\n","repo_name":"DuncanZhou/TwitterProject","sub_path":"Neo4jInteraction/TwitterWithNeo4j.py","file_name":"TwitterWithNeo4j.py","file_ext":"py","file_size_in_byte":1142,"program_lang":"python","lang":"en","doc_type":"code","stars":3,"dataset":"github-code","pt":"15"} +{"seq_id":"24883051463","text":"# 4. Пользователь вводит целое положительное число. Найдите самую большую цифру в числе. Для решения используйте цикл\n# while и арифметические операции.\n\nnumber = int(input(\"Введите целое положительное число:\"))\ntemp = number % 10 # берем последнюю цифру числа\nnumber = number // 10 # берем оставшуюся часть числа\n\nwhile number > 0: # сравниваем в цикле temp и последнюю цифру в оставшейся части числа.\n if number % 10 > temp: # если последняя цифра оставшейся части числа больше, то записываем ее.\n temp = number % 10\n\n number = number // 10\n\nprint(\"Самая большая цифра в числе:\", temp)\n","repo_name":"mvanisimov/PythonProject","sub_path":"lesson 1/task4.py","file_name":"task4.py","file_ext":"py","file_size_in_byte":936,"program_lang":"python","lang":"ru","doc_type":"code","stars":0,"dataset":"github-code","pt":"15"} +{"seq_id":"22582517918","text":"import unittest\nfrom src.coffee_shop import CoffeeShop\nfrom src.customer import Customer\nfrom src.drinks import Drinks\nfrom src.food import Food\n\nclass TestCoffeeShop(unittest.TestCase):\n \n def setUp(self):\n self.coffee_shop = CoffeeShop(\"Costa Coffee Branch 101\", 1000)\n self.drink1 = Drinks(\"Mocha\", 3, 2, 3)\n self.drink2 = Drinks(\"Espresso\", 4, 5, 7)\n self.all_drinks = [self.drink1, self.drink2]\n self.food1 = Food(\"falafel_wrap\", 5, 2)\n self.food2 = Food(\"brownie\", 3, 4)\n self.all_foods = [self.food1, self.food2]\n\n\n\n def test_coffee_shop_has_name(self):\n self.assertEqual(\"Costa Coffee Branch 101\", self.coffee_shop.name)\n # self.assertEqual(expected, actual)\n\n def test_increase_cash(self):\n self.coffee_shop.increase_cash_in_till(15) #action\n self.assertEqual(1015, self.coffee_shop.till) #results\n\n def test_putting_drinks_in_list(self): \n self.coffee_shop.put_drinks_in_shop(self.all_drinks)\n self.assertEqual(2, len(self.coffee_shop.drinks))\n\n def test_customer_transaction(self):\n self.coffee_shop.put_drinks_in_shop(self.all_drinks)\n self.customer1 = Customer(\"Becca\", 30, 21)\n self.coffee_shop.customer_transaction(self.drink2, self.customer1)\n self.coffee_shop.customer_transaction(self.drink1, self.customer1)\n self.coffee_shop.customer_food_transaction(self.food1, self.customer1)\n\n \n self.assertEqual(18, self.customer1.wallet)\n self.assertEqual(1012, self.coffee_shop.till)\n self.assertEqual(5, self.customer1.energy_level)\n\n # def test_check_coffee_shop_stock(self):\n \n # self.assertEqual(37, self.coffee_shop.check_stock_value())\n\n\n\n \n\n#Add caffeine_level to the Drink, and a energy level to the Customer. Every time a Customer buys a drink, the energy level should go up by the caffeine_level.","repo_name":"mashy1997/coffee_shop_lab","sub_path":"tests/coffee_shop_test.py","file_name":"coffee_shop_test.py","file_ext":"py","file_size_in_byte":1908,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"15"} +{"seq_id":"23780189122","text":"from web3 import Web3, HTTPProvider\nimport shared\nshared.init()\nfrom shared import web3, multicall\nfrom Utils.api import get_logs\nfrom itertools import islice\ndef connect_to_web3():\n \"\"\"\n Connect to Web3 server.\n Args:\n Returns:\n res: Boolean indicating that connection was succeed or not.\n web3: Web3 Object\n \"\"\"\n web3 = Web3(HTTPProvider('https://mainnet.infura.io/v3/d6243bb783b44485ad6636b6c3411377'))\n res = web3.isConnected()\n return res, web3\n\ndef split_chunks(data,n_elements):\n '''\n splitting the calls to aggregate them properly\n Args:\n data = array containing calls\n n_elements = Int. Calls we want to aggregate\n Returns:\n calls in chunks \n '''\n chunks = []\n n = len(data)\n \n if(n % n_elements!=0):\n n_chunks = int(n/n_elements)+1\n\n else:\n n_chunks = int(n/n_elements)\n \n for i in range(n_chunks-1):\n chunk = data[i*n_elements:(i+1)*n_elements]\n chunks.append(chunk)\n\n chunks.append(data[(n_chunks-1)*n_elements:]) \n return chunks\n\ndef get_decimals(tokens_contracts,number_agg):\n 'Get decimals of tokens'\n json_results = []\n calls = []\n for _,contract in tokens_contracts.items():\n calls.append(contract.functions.decimals())\n calls_splited = split_chunks(calls,int(len(calls)/number_agg))\n for call in calls_splited:\n try:\n json_results += multicall.aggregate(call,shared.BLOCKSTUDY).json['results']\n except: \n json_results += multicall_aggregator(call)\n\n return json_results\n\ndef multicall_aggregator(call):\n try:\n result = multicall.aggregate(call,shared.BLOCKSTUDY).json['results']\n except:\n if len(call) > 1:\n split_call = split_chunks(call,int(len(call)/2))\n result1 = multicall_aggregator(split_call[0])\n result2 = multicall_aggregator(split_call[1])\n result = result1+result2\n else:\n try:\n result = multicall.aggregate(call,shared.BLOCKSTUDY).json['results']\n except:\n result = []\n return result\n\ndef get_decimal_token(token_address):\n try:\n contract = web3.eth.contract(token_address,abi = shared.ABI)\n decimals = contract.functions.decimals().call()\n except:\n decimals = None\n return decimals\n\ndef chunks(data, SIZE=10000):\n it = iter(data)\n for i in range(0, len(data), SIZE):\n yield {k:data[k] for k in islice(it, SIZE)}\n\ndef get_pools(dex, factory): #v2 or sushi\n '''\n Args:\n dex = String. Choose the DEX you want to get the pools from\n factory = factory get_contracts of dex\n Returns:\n pool dictionary with the attributes 'address','dex','token0','token1','reserves0','reserves1','creation'\n '''\n # _,web3 = connect_to_web3()\n hash_create = '0x0d3648bd0f6ba80134a33ba9275ac585d9d315f0ad8355cddefde31afa28d0e9'\n if dex == 'uniswap_v2':\n from_block = 10008355\n #from_block = get_latest_block()-1000\n to_block = shared.BLOCKSTUDY\n number_batches = 20\n pools = get_logs(factory,'PairCreated',hash_create,from_block,to_block,number_batches)\n \n if dex == 'sushiswap':\n from_block = from_block = 10822038\n to_block = shared.BLOCKSTUDY\n number_batches = 20\n pools = get_logs(factory,'PairCreated',hash_create,from_block,to_block,number_batches)\n\n pool_dic = {}\n tokens = {}\n for pool in pools:\n pool_address = pool.args.pair\n token0 = pool.args.token0\n token1 = pool.args.token1\n tokens.update({token0:None})\n tokens.update({token1:None})\n pool_dic.update({pool_address:{ 'address':pool_address,\n 'dex':dex,\n 'token0':token0,\n 'token1':token1,\n 'reserves0':None,\n 'reserves1':None,\n 'creation':pool.blockNumber}}) \n\n return pool_dic,tokens\n\n\ndef clean_transfers(transfer_list):\n clean_transfer_list = []\n for transfer in transfer_list:\n dictionary = {\n 'from': transfer.args._from,\n 'to' : transfer.args._to,\n 'value': transfer.args._value,\n 'logIndex': transfer.logIndex,\n 'transactionIndex': transfer.transactionIndex,\n 'transactionHash': transfer.transactionHash,\n 'blockHash':transfer.blockHash,\n 'blockNumber': transfer.blockNumber\n }\n clean_transfer_list.append(dictionary)\n return clean_transfer_list","repo_name":"T2Project/BasicUtilsEth","sub_path":"Utils/eth_utils.py","file_name":"eth_utils.py","file_ext":"py","file_size_in_byte":4724,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"15"} +{"seq_id":"12529191492","text":"from problem import Problem\nfrom collections import namedtuple\nState=namedtuple(\"State\", [\"disk\",\"char\"])\n\nclass Hanoi(Problem):\n def __init__(self, n):\n self.size = n\n super().__init__(\"1\" * n, \"3\" * n)\n\n def actions(self, state):\n \n # state: 211\n # maga az érték az az hogy melyik rúdon van, az meg hogy hanyadik érték az az hogy mekkora a korong:\n # Itt most a legkisebb korong ( 0-ás index ) az a 2. oszlopon van.\n # A közepes korong és a legnagyobb az első oszlopon van.\n \n \n acts = []\n f1 = state.find(\"1\")\n f2 = state.find(\"2\")\n f3 = state.find(\"3\")\n print(f\"Current state: {state}\")\n \n \n # Ha találunk olyat ami az első oszlopon van és ez kisebb mint a 2. oszlopon lévő,\n # ergo kisebb a korong mint a 2. oszlopon lévő vagy a 2. oszlopon még nincs semmi (f2 == -1), akkor rá tudjuk pakolni\n if -1 < f1 and (f1 < f2 or f2 == -1):\n # Átrakjuk azt az a vizsgált elemet a 2. oszlopra (f2)\n acts.append(State(f1, \"2\"))\n\n # Tudunk áttenni a 3. oszlopra az 1. oszlopról.\n if -1 < f1 and (f1 < f3 or f3 == -1):\n acts.append(State(f1, \"3\"))\n\n if -1 < f2 and (f2 < f1 or f1 == -1):\n acts.append(State(f2, \"1\"))\n\n if -1 < f2 and (f2 < f3 or f3 == -1):\n acts.append(State(f2, \"3\"))\n\n if -1 < f3 and (f3 < f1 or f1 == -1):\n acts.append(State(f3, \"1\"))\n\n if -1 < f3 and (f3 < f2 or f2 == -1):\n acts.append(State(f3, \"2\"))\n\n return acts\n\n def result(self, state, action):\n # ez a következő állapot\n # disk az hogy hanyadik helyen áll, a char meg hogy hanydik oszlop\n \n disk, char = action\n \n # berakjuk a disket a megfelelő oszlopra\n # mivel a disk reprezentálja a az indexet hogy melyik korong hol van\n return state[0:disk] + char + state[disk + 1:]","repo_name":"moL3sz/Mestint","sub_path":"week3/hanoi.py","file_name":"hanoi.py","file_ext":"py","file_size_in_byte":1995,"program_lang":"python","lang":"hu","doc_type":"code","stars":0,"dataset":"github-code","pt":"15"} +{"seq_id":"23057996942","text":"\"\"\" Utilities for exporters \"\"\"\n\nfrom opennem.controllers.output.schema import StatType\nfrom opennem.schema.network import NetworkSchema\nfrom opennem.utils.version import get_version_components\n\nVERSION_MAJOR = get_version_components().major\nSTATS_FOLDER = \"stats\"\n\n\ndef get_export_output_path(\n network: NetworkSchema,\n stat_type: StatType,\n network_region: str | None = None,\n period=None,\n year: int | None = None,\n week_number: int | None = None,\n) -> str:\n \"\"\"Takes the attributes of an export and returns the path they should be saved to\"\"\"\n _path_components = [\n f\"v{VERSION_MAJOR}\",\n STATS_FOLDER,\n network.country,\n network.code,\n ]\n\n if network_region:\n _path_components.append(network_region)\n\n _path_components.append(stat_type.value)\n\n # only show the period when it's not explicitly a year\n if period and not year:\n _path_components.append(period.period_human)\n\n if week_number:\n _path_components.append(\"week\")\n\n if year:\n _path_components.append(str(year))\n\n if week_number:\n _path_components.append(str(week_number))\n\n dir_path = \"/\".join([str(i) for i in _path_components])\n\n return f\"{dir_path}.json\"\n","repo_name":"opennem/opennem","sub_path":"opennem/controllers/output/utils.py","file_name":"utils.py","file_ext":"py","file_size_in_byte":1237,"program_lang":"python","lang":"en","doc_type":"code","stars":52,"dataset":"github-code","pt":"15"} +{"seq_id":"21625262588","text":"from collections import namedtuple\n\nex_tuples = (10, 20, 30)\ndez, vinte, trinta = ex_tuples\n\nprint(dez)\n# print(vinte)\n# print(trinta)\n\n\nprint(ex_tuples[-2])\n\n\n# accessing tuple elements using slicing\nmy_tuple = (\"p\", \"r\", \"o\", \"g\", \"r\", \"a\", \"m\", \"i\", \"z\")\n\n\nEstados = namedtuple(\"Estados\", [\"nome\", \"sigla\"])\n\nestado_1 = Estados(\"Rio De Janeiro\", \"RJ\")\n\n\nprint(estado_1)\nprint(estado_1.nome)\n\nx = \"global\"\n\n\ndef f():\n x = \"enclosing\"\n\n def g():\n x = \"local\"\n print(x)\n\n g()\n\n\nf()\n","repo_name":"gbmsaraujo/python-bootcamp","sub_path":"aulas/books/data-structure/03-tuples/main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":505,"program_lang":"python","lang":"pt","doc_type":"code","stars":0,"dataset":"github-code","pt":"15"} +{"seq_id":"25490633695","text":"from typing import Dict, List, Tuple\n\nimport attr\n\nfrom backend.components import sops\nfrom backend.container_service.infras.hosts.constants import APPLY_HOST_TEMPLATE_ID, SOPS_BIZ_ID\n\n\n@attr.dataclass\nclass HostData:\n region: str\n vpc_name: str\n cvm_type: str\n disk_type: str\n disk_size: int\n replicas: int\n zone_id: str\n\n @classmethod\n def from_dict(cls, init_data: Dict) -> \"HostData\":\n fields = [f.name for f in attr.fields(cls)]\n return cls(**{k: v for k, v in init_data.items() if k in fields})\n\n\ndef create_and_start_host_application(cc_app_id: str, username: str, host_data: HostData) -> Tuple[int, str]:\n \"\"\"创建并启动申请主机任务流程\"\"\"\n client = sops.SopsClient()\n # 组装创建任务参数\n task_name = f\"[{cc_app_id}]apply host resource\"\n data = sops.CreateTaskParams(\n name=task_name,\n constants={\n \"${appID}\": cc_app_id,\n \"${user}\": username,\n \"${qcloudRegionId}\": host_data.region,\n \"${cvm_type}\": host_data.cvm_type,\n \"${diskSize}\": host_data.disk_size,\n \"${replicas}\": host_data.replicas,\n \"${vpc_name}\": host_data.vpc_name,\n \"${zone_id}\": host_data.zone_id,\n \"${disk_type}\": host_data.disk_type,\n },\n )\n # 创建任务\n resp_data = client.create_task(bk_biz_id=SOPS_BIZ_ID, template_id=APPLY_HOST_TEMPLATE_ID, data=data)\n task_id = resp_data[\"task_id\"]\n task_url = resp_data[\"task_url\"]\n\n # 启动任务\n client.start_task(bk_biz_id=SOPS_BIZ_ID, task_id=task_id)\n\n return task_id, task_url\n\n\ndef get_task_state_and_steps(task_id: str) -> Dict:\n \"\"\"获取任务总状态及步骤状态\"\"\"\n client = sops.SopsClient()\n resp_data = client.get_task_status(bk_biz_id=SOPS_BIZ_ID, task_id=task_id)\n\n # NOTE: 现阶段不处理SUSPENDED(暂停)状态,当任务处于RUNNING状态, 认为任务处于执行中\n steps = {}\n for step_id, detail in (resp_data.get(\"children\") or {}).items():\n name = detail.get(\"name\") or \"\"\n # NOTE: 过滤掉sops中的开始和结束节点(两个空标识节点)\n if \"EmptyEndEvent\" in name or \"EmptyStartEvent\" in name:\n continue\n steps[name] = {\"state\": detail[\"state\"], \"step_id\": step_id}\n\n # 返回任务状态, 步骤名称及状态\n return {\"state\": resp_data[\"state\"], \"steps\": steps}\n\n\ndef get_applied_ip_list(task_id: str, step_id: str) -> List[str]:\n \"\"\"获取申领的机器列表\"\"\"\n client = sops.SopsClient()\n resp_data = client.get_task_node_data(bk_biz_id=SOPS_BIZ_ID, task_id=task_id, node_id=step_id)\n\n # 获取返回的IP列表\n # outputs 结构: [{key: xxx, value: str}, {key: log_outputs, value: {ip_list: \"127.0.0.1,127.0.0.2\"}}]\n outputs = resp_data[\"outputs\"]\n\n ips = \"\"\n for i in outputs:\n if i[\"key\"] != \"log_outputs\":\n continue\n # NOTE: 接口返回中是以英文逗号分隔的字符串\n ips = i[\"value\"][\"ip_list\"]\n\n return ips.split(\",\")\n","repo_name":"TencentBlueKing/bk-bcs","sub_path":"bcs-ui/backend/container_service/infras/hosts/terraform/engines/sops.py","file_name":"sops.py","file_ext":"py","file_size_in_byte":3051,"program_lang":"python","lang":"en","doc_type":"code","stars":735,"dataset":"github-code","pt":"15"} +{"seq_id":"42243918816","text":"import json\r\nimport os\r\nimport re\r\nimport shutil\r\nimport tempfile\r\nimport time\r\nimport uuid\r\nimport zipfile\r\nfrom datetime import datetime\r\n\r\nimport girder_client\r\n\r\nGIRDER_URL = 'http://ismi17.diagnijmegen.nl/girder/api/v1'\r\n\r\n\r\ndef submit_results(user, csv_results, description=None):\r\n client = girder_client.GirderClient(apiUrl=GIRDER_URL)\r\n upload_challenge_data(client, user, 'prostatex', csv_results, metadata=description)\r\n print(\r\n \"Done. The results of your submission will appear shortly on the leaderboard at http://ismi17.diagnijmegen.nl/\")\r\n\r\n\r\ndef upload_challenge_data(client, user, challenge_name, results_file, metadata=None):\r\n working_directory = tempfile.mkdtemp()\r\n results_folder = tempfile.mkdtemp()\r\n\r\n try:\r\n create_results_csv(results_file, results_folder)\r\n create_challengr_json(results_folder)\r\n\r\n results_zip = zip_directory(results_folder, working_directory)\r\n upload_file_to_server(client, user, results_zip, challenge_name, metadata)\r\n finally:\r\n shutil.rmtree(working_directory)\r\n shutil.rmtree(results_folder)\r\n\r\n\r\ndef create_results_csv(results_file, results_folder):\r\n print('Validating the csv file')\r\n output_file = os.path.join(results_folder, 'algorithm_result.csv')\r\n\r\n with open(os.path.abspath(results_file), 'r') as f:\r\n filedata = f.readlines()\r\n\r\n # First line must have the correct format\r\n filedata[0] = 'proxid,clinsig\\n'\r\n\r\n for line in filedata[1:]:\r\n # Check that the filename has the correct format\r\n file_id = line.split(',')[0]\r\n if not re.match('^ProstateX-[0-9]{4}-[0-9]{1,}$', file_id):\r\n raise (ValueError(\r\n 'The format of the filename is not correct, it should be in the format of\\n ProstateX-0000-0\\nyours is: \\n %s' % file_id))\r\n\r\n # Check that the label can be converted to an int\r\n try:\r\n float(line.split(',')[1])\r\n except ValueError:\r\n raise (ValueError(\r\n 'The format of your csv file is incorrect. It should be comma separated, the 1st column is proxid, the 2nd the clinical significance. We could not convert your label to a float.'))\r\n\r\n with open(output_file, 'w') as f:\r\n f.writelines(filedata)\r\n\r\n\r\ndef upload_file_to_server(client, user, file, challenge_name, metadata=None):\r\n print('Uploading results to server')\r\n client.authenticate(username=user['username'], password=user['password'])\r\n\r\n # The following will just return the first item in the list!!!\r\n collection = client.get('collection', {'text': challenge_name, 'limit': 1})[0]\r\n folder = client.get('folder', {'parentId': collection['_id'],\r\n 'parentType': 'collection',\r\n 'name': user['username'].lower()})[0]\r\n\r\n item = client.createItem(folder['_id'], 'Submission %s' % datetime.utcnow())\r\n\r\n if metadata is not None:\r\n client.addMetadataToItem(item['_id'], metadata)\r\n\r\n # Upload file data\r\n client.uploadFileToItem(item['_id'], file)\r\n\r\n\r\ndef zip_directory(input_dir, output_dir):\r\n \"\"\"\r\n Creates a temporary directory and creates a zipfile with the algorithm result\r\n :param folder:\r\n :return:\r\n \"\"\"\r\n print('Compressing results')\r\n input_dir = os.path.abspath(input_dir)\r\n output_dir = os.path.abspath(output_dir)\r\n\r\n foldername = os.path.split(input_dir)[1]\r\n temp_zip_file = os.path.join(output_dir, foldername + '.zip')\r\n\r\n with zipfile.ZipFile(temp_zip_file, 'w', zipfile.ZIP_DEFLATED) as z:\r\n for root, dirs, files in os.walk(input_dir):\r\n for f in files:\r\n z.write(os.path.join(root, f), os.path.relpath(os.path.join(root, f), input_dir))\r\n\r\n return temp_zip_file\r\n\r\n\r\ndef create_challengr_json(results_folder):\r\n json_filename = os.path.join(results_folder, 'challengr.json')\r\n print('Creating %s' % json_filename)\r\n\r\n foldername = os.path.basename(os.path.normpath(results_folder))\r\n\r\n challengr_metadata = {\"timestamp\": time.time(), \"algorithmfields\": {\r\n \"fields\": [],\r\n \"description\": \"\",\r\n \"uuid\": str(uuid.uuid1()),\r\n \"name\": \"\"}, \"uid\": \"\", \"timings\": {}, \"parametrization\": {}, 'uid': str(foldername)}\r\n\r\n with open(json_filename, 'w') as f:\r\n f.write(json.dumps(challengr_metadata))\r\n\r\n\r\nif __name__ == \"__main__\":\r\n \"\"\"Example usage:\"\"\"\r\n submit_results({'username': 'jeftha.spunda', 'password': 'FU2PEA5N'},\r\n 'predictions.csv',\r\n description={'notes': '15K epochs, window 500-1100'})\r\n","repo_name":"jspunda/prostatex","sub_path":"utils/prostatex_submission.py","file_name":"prostatex_submission.py","file_ext":"py","file_size_in_byte":4627,"program_lang":"python","lang":"en","doc_type":"code","stars":13,"dataset":"github-code","pt":"15"} +{"seq_id":"3574364417","text":"import numpy as np\n\nfrom config.game_config import GameConfig\n\n\nclass Markov():\n def __init__(self, reward_grid, reward_category, actions, gamma, mode_space):\n self.i_rewards = reward_grid # immediate_reward\n\n self.s_states = [] # search\n self.c_states = [] # crash\n self.e_states = [] # end\n for i, row in enumerate(reward_grid):\n for j, reward in enumerate(row):\n if reward == reward_category[0]:\n self.s_states.append([i, j])\n if reward == reward_category[1]:\n self.c_states.append([i, j])\n if reward == reward_category[2]:\n self.e_states.append([i, j])\n\n self.actions = actions\n self.gamma = gamma\n\n self.v_values = np.zeros_like(reward_grid, dtype=np.float)\n for state in self.c_states:\n self.v_values[state[0]][state[1]] = -10000\n\n self.pi_values = np.ones((reward_grid.shape[0], reward_grid.shape[1], len(actions)), dtype=np.int) * (1/len(actions))\n self.q_values = np.zeros_like(self.pi_values, dtype=np.float)\n\n self.mode_space = mode_space\n self.mode = None\n\n def change_mode(self, mode):\n self.v_values = np.zeros_like(self.v_values, dtype=np.float)\n for state in self.c_states:\n self.v_values[state[0]][state[1]] = -10000\n self.pi_values = np.ones(self.pi_values.shape, dtype=np.int) * (1/len(self.actions))\n self.q_values = np.zeros_like(self.q_values, dtype=np.float)\n\n if self.mode == 'random':\n self.policy_evaluation()\n print(self.v_values)\n if self.mode == 'policy_iteration':\n self.policy_iteration()\n print(self.v_values)\n if self.mode == 'value_iteration':\n self.value_iteration()\n print(np.around(self.v_values, decimals=2))\n\n def get_next_state(self, state, action):\n next_state = state.copy()\n if action == 'e':\n next_state[1] += 1\n if action == 'w':\n next_state[1] -= 1\n if action == 's':\n next_state[0] += 1\n if action == 'n':\n next_state[0] -= 1\n if not (next_state in self.s_states or next_state in self.e_states):\n next_state = state.copy()\n return next_state\n\n # pi(a|s)\n def get_pi_value(self, state, action):\n return self.pi_values[state[0]][state[1]][self.actions.index(action)]\n\n # v_pi(s)\n def state_value_function(self, state):\n value = 0\n for i, action in enumerate(self.actions):\n self.q_values[state[0]][state[1]][i] = self.action_value_function(state, action)\n value += self.get_pi_value(state, action) * self.q_values[state[0]][state[1]][i]\n return value\n\n # q_pi(s,a)\n def action_value_function(self, state, action):\n next_state = self.get_next_state(state, action)\n if next_state == state:\n return self.i_rewards[state[0]][state[1]] + self.gamma * self.v_values[state[0]][state[1]]\n else:\n return self.i_rewards[state[0]][state[1]] + self.gamma * self.v_values[next_state[0]][next_state[1]]\n\n def policy_evaluation(self):\n k = 0\n while True:\n last_v_values = self.v_values.copy()\n for i, state in enumerate(self.s_states):\n self.v_values[state[0]][state[1]] = self.state_value_function(state)\n k += 1\n last_v_values = np.around(last_v_values, decimals=0)\n self.v_values = np.around(self.v_values, decimals=0)\n if (last_v_values == self.v_values).all():\n break\n print(f'{k} iterations for policy evaluation in {self.mode} mode.')\n\n def policy_iteration(self):\n k = 0\n while True:\n last_pi_values = self.pi_values.copy()\n self.v_values = np.zeros_like(self.v_values, dtype=np.float)\n for state in self.c_states:\n self.v_values[state[0]][state[1]] = -10000\n self.policy_evaluation()\n for i, state in enumerate(self.s_states):\n q_value_slice = self.q_values[state[0]][state[1]]\n max_q_value = max(q_value_slice)\n for j, q_value in enumerate(q_value_slice):\n if q_value == max_q_value:\n self.pi_values[state[0]][state[1]][j] = 1 / list(q_value_slice).count(max_q_value)\n else:\n self.pi_values[state[0]][state[1]][j] = 0\n k += 1\n if (last_pi_values == self.pi_values).all():\n break\n print(f'{k} iterations for policy iteration in {self.mode} mode.')\n\n def value_iteration(self):\n k = 0\n while True:\n last_v_values = self.v_values.copy()\n for i, state in enumerate(self.s_states):\n value_candidate = []\n for i, action in enumerate(self.actions):\n self.q_values[state[0]][state[1]][i] = self.action_value_function(state, action)\n value_candidate.append(self.get_pi_value(state, action) * self.q_values[state[0]][state[1]][i])\n self.v_values[state[0]][state[1]] = max(value_candidate)\n k += 1\n if (last_v_values == self.v_values).all():\n break\n print(f'{k} iterations for value iteration in {self.mode} mode.')\n\n def give_action_advice(self, state):\n v_values_candidate = []\n for action in self.actions:\n next_state = self.get_next_state(state, action)\n v_values_candidate.append(self.v_values[next_state[0]][next_state[1]])\n action_candidate = []\n for i, v_value in enumerate(v_values_candidate):\n if v_value == max(v_values_candidate):\n action_candidate.append(i)\n action_candidate = np.array(action_candidate, dtype=np.int)\n # print(action_candidate)\n return self.actions[np.random.choice(action_candidate, 1)[0]]\n","repo_name":"Bearsuny/rl-homework","sub_path":"algorithm/markov.py","file_name":"markov.py","file_ext":"py","file_size_in_byte":6066,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"15"} +{"seq_id":"35617873066","text":"#!/usr/bin/python\n\nfrom ucsmsdk.ucsconstants import NamingId\nfrom ucsmsdk.mometa.vnic.VnicFc import VnicFc\nfrom ucsmsdk.mometa.vnic.VnicSanConnPolicy import VnicSanConnPolicy\nfrom ucsmsdk.mometa.vnic.VnicFcNode import VnicFcNode\n\nDOCUMENTATION = '''\n---\nmodule: ucs_san_con\nshort_description: Create and Delete ucs lan_conn_policy\nauthor: \"Kyle Jones (@excilsploft)\"\nversion_added: \"\"\ndescription:\n - Create UCS san_conn_policy in a UCS version 2.2X and greater. This module,\n allows you to create a policy, assign an hba based on a template, name it,\n order it and Assign a vnic policy.\nnotes:\n - This only works with existing hba templates and vnic policies.\nrequirements:\n - \"python >= 2.7.5\"\n - \"ucsmsdk\"\noptions:\n san_con_name:\n description:\n - \"A UCS san connection policy name\"\n required: true\n default: None\n san_con_descr:\n description:\n - \"description label for the policy\"\n required: false\n default: None\n state:\n description:\n - \"a choice, either 'present' or 'absent'\"\n org_name:\n description:\n - \"organizational object name to create the policy under\"\n required: true\n default: None\n wwnn_pool: \"world wide node name pool\"\n hbas:\n description:\n - \"a list of vnic dictionaries examples as below\n name: vnic name\n order: order in policy\n templ: vnic template\n policy: policy name for the vnic\"\n\n required: true\n default: None\n'''\n\nEXAMPLES = '''\n# Create a san conn policy exchange server on dev ucs\n- ucs_san_conn:\n state: present\n hostname: dev_ucsm_hostname\n username: admin\n password: admin\n port: 443\n org_name: myorgname\n san_con_name: exchange\n san_con_descr: exchange server san con policy\n wwnn_pool: exchange_fc_pool\n hbas:\n - name: hba1\n order: 1\n templ: exchange_a\n policy: Windows\n\n - name: hba2\n order: 2\n templ: exchange_b\n policy: Windows\n'''\n\n\ndef get_san_con(handle, org_obj, name):\n \"\"\"verify the san conn policy exists\"\"\"\n\n ret_val = None\n filter_str = '(name, \"{0}\", type=\"eq\")'.format(name)\n san_con_list = handle.query_children(in_mo=org_obj,\n class_id=NamingId.VNIC_SAN_CONN_POLICY,\n filter_str=filter_str,\n hierarchy=False)\n for san in san_con_list:\n if san.name == name:\n ret_val = san\n break\n\n return ret_val\n\ndef san_con_present(handle, params):\n \"\"\"make the san con policy \"\"\"\n\n org_obj = get_org(handle, params['org_name'])\n\n if org_obj:\n san_con_pol = VnicSanConnPolicy(parent_mo_or_dn=org_obj,\n name=params['san_con_name'],\n descr=params['san_con_descr'])\n\n fc_node = VnicFcNode(parent_mo_or_dn=san_con_pol,\n ident_pool_name=params['wwnn_pool'])\n for hba in params['hbas']:\n hba_obj = VnicFc(parent_mo_or_dn=san_con_pol,\n name=hba['name'],\n order=str(hba['order']),\n nw_templ_name=hba['templ'],\n adaptor_profile_name=hba['policy'])\n\n handle.add_mo(san_con_pol, True)\n handle.commit()\n\n if get_san_con(handle, org_obj, params['san_con_name']):\n #return ({'changed': True, 'failed': False})\n return True\n else:\n #return ({'changed': False, 'failed': True})\n return False\n\ndef san_con_absent(handle, params):\n \"\"\"remove the san con policy\"\"\"\n\n org_obj = get_org(handle, params['org_name'])\n\n if org_obj:\n filter_str = '(name, \"{0}\", type=\"eq\")'.format(params['san_con_name'])\n san_con_list = handle.query_children(in_mo=org_obj,\n class_id=NamingId.VNIC_SAN_CONN_POLICY,\n filter_str=filter_str,\n hierarchy=False)\n for s_con in san_con_list:\n if s_con.name == params['san_con_name']:\n handle.remove_mo(s_con)\n handle.commit()\n break\n\n if get_san_con(handle, org_obj, params['san_con_name']):\n #return ({'changed': True, 'failed': False})\n return True\n else:\n #return ({'changed': False, 'failed': True})\n return False\n\ndef main():\n \"\"\"main entry point\"\"\"\n\n spec = get_ucs_argument_spec(**dict(\n org_name=dict(\n required=True,\n type=\"str\"\n ),\n san_con_name=dict(\n required=True,\n type=\"str\"\n ),\n san_con_descr=dict(\n required=False,\n type=\"str\"\n ),\n wwnn_pool=dict(\n required=True,\n type=\"str\"\n ),\n hbas=dict(\n type=\"list\"\n ),\n state=dict(\n default=\"present\",\n choices=[\"present\", \"absent\"],\n type=\"str\"\n ),\n ))\n\n\n module = AnsibleModule(argument_spec=spec)\n\n handle = get_handle(module)\n\n if module.params['state'] == 'present':\n result = san_con_present(handle, module.params)\n else:\n result = san_con_absent(handle, module.params)\n\n module.exit_json(changed=result)\n\n\nfrom ansible.module_utils.basic import *\nfrom ucs import *\n\nif __name__ == '__main__':\n main()\n","repo_name":"stoffee/ansible-ucs","sub_path":"library/ucs_san_conn.py","file_name":"ucs_san_conn.py","file_ext":"py","file_size_in_byte":5580,"program_lang":"python","lang":"en","doc_type":"code","stars":2,"dataset":"github-code","pt":"15"} +{"seq_id":"12321066292","text":"from math import *\n\ndef f(x):\n return exp(x)\n\n'''\nIntegração tomando por x o valor mais à esquerda.\n'''\ndef int_esq(a, b, N):\n s = 0.\n h = (b-a)/float(N)\n x = a\n for i in range(N):\n s += f(x)\n x += h\n return h*s\n\n'''\nIntegração tomando por x o valor mais à direita.\n'''\ndef int_dir(a, b, N):\n s = 0.\n h = (b-a)/float(N)\n x = a + h\n for i in range(N):\n s += f(x)\n x += h\n return h*s\n\n'''\nIntegração tomando por x o valor mais ao meio.\n'''\ndef int_meio(a, b, N):\n s = 0.\n h = (b-a)/float(N)\n x = a + h/2.\n for i in range(N):\n s += f(x)\n x += h\n return h*s\n\n'''\nIntegração utilizando a regra do trapézio\n'''\ndef int_trapezio(a, b, N):\n s = 0.\n h = (b-a)/float(N)\n x = a\n for i in range(N):\n s += (f(x) + f(x+h))\n x += h\n return (h/2.) * s\n\n'''\nIntegração utlizando 1/3 de Simpson\n'''\ndef int_simpson_1_3(a, b, N):\n s = 0.\n h = (b-a)/float(N)\n x = a\n for i in range(ceil(N/2)):\n s += f(x) + 4*f(x+h) + f(x+2*h)\n x += 2*h\n return (h/3.) * s\n\n'''\nIntegração utlizando 3/8 de Simpson\n'''\ndef int_simpson_3_8(a, b, N):\n s = 0.\n h = (b-a)/float(N)\n x = a\n for i in range(ceil(N/3)):\n s += f(x) + 3*f(x+h) + 3*f(x+2*h) + f(x+3*h)\n x += 3*h\n return (3./8.) * h * s\n\n'''\nIntegração utlizando a regra Boole\n'''\ndef int_boole(a, b, N):\n s = 0.\n h = (b-a)/float(N)\n x = a\n for i in range(ceil(N/4)):\n s += 7*f(x) + 32*f(x+h) + 12*f(x+2*h) + 32*f(x+3*h) + 7*f(x+4*h)\n x += 4*h\n return (4./90.) * h * s\n\na = 0\nb = 1\nN = 12000\n\nprint(\"ESQ: \", abs(int_esq(a, b, N)) - exp(b) + exp(a))\nprint(\"DIR: \", abs(int_dir(a, b, N)) - exp(b) + exp(a))\nprint(\"MEIO: \", abs(int_meio(a, b, N)) - exp(b) + exp(a))\nprint(\"TRAP: \", abs(int_trapezio(a, b, N)) - exp(b) + exp(a))\nprint(\"1/3 SIMP: \", abs(int_simpson_1_3(a, b, N)) - exp(b) + exp(a))\nprint(\"3/8 SIMP: \", abs(int_simpson_3_8(a, b, N)) - exp(b) + exp(a))\nprint(\"BOOLE: \", abs(int_boole(a, b, N)) - exp(b) + exp(a))\n","repo_name":"eduardo-paes/CalculoNumerico","sub_path":"CalculoNumerico/IntegracaoNumerica/integracao.py","file_name":"integracao.py","file_ext":"py","file_size_in_byte":1963,"program_lang":"python","lang":"pt","doc_type":"code","stars":0,"dataset":"github-code","pt":"15"} +{"seq_id":"43250465712","text":"import json\n\nfilename = \"../../../data/nist_attack.json\"\ndef get_related_ttps(mitigation):\n ttps = set()\n with open(filename,\"r\") as f:\n mapping_list = json.load(f)[\"Mappings\"]\n for m in mapping_list:\n if m[\"Control ID\"] == mitigation:\n if \".\" not in m[\"Technique ID\"]:\n ttps.add(m[\"Technique ID\"])\n return list(ttps)\n\nprint(get_related_ttps(\"RA-5\"))\n","repo_name":"Nazianzenov/cti_prioritization","sub_path":"proof-of-concept/script/mitigation scripts/nist_json.py","file_name":"nist_json.py","file_ext":"py","file_size_in_byte":403,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"15"} +{"seq_id":"36136098971","text":"import fp\nfrom fp import cfg\n\nclass wired(fp.base):\n\t\"\"\"Generator for wired resistors, capacitors, ...\"\"\"\n\n\tdef __init__(self, name, model, description, tags, package_width, package_height, pad_width, pad_height, pad_grid, pad_distance, count, drill):\n\t\tsuper(wired, self).__init__(name, model, description, tags)\n\nclass wired_resistor(fp.base):\n\t\"\"\"Wired resistor with beveled edges\"\"\"\n\n\tdef __init__(self, name, description, tags, package_width, package_height, pad_diameter, pad_distance, pad_drill):\n\t\tsuper(wired_resistor, self).__init__(name, description, tags)\n\n\t\tbevel = math.sqrt(package_width * package_width + package_height * package_height) * 0.1\n\t\tfp.base.add(self, fp.beveled_rectangle(cfg.FOOTPRINT_PACKAGE_LAYER, 0, 0, package_width, package_height, bevel, cfg.FOOTPRINT_PACKAGE_LINE_WIDTH, True))\n\t\tfp.base.add(self, fp.pad(cfg.FOOTPRINT_THD_LAYERS, 1, fp.technology.thru_hole, fp.type.circle, -pad_distance / 2, 0, pad_diameter, pad_diameter, pad_drill))\n\t\tfp.base.add(self, fp.pad(cfg.FOOTPRINT_THD_LAYERS, 2, fp.technology.thru_hole, fp.type.circle, pad_distance / 2, 0, pad_diameter, pad_diameter, pad_drill))\n","repo_name":"PiWare/kicad_library","sub_path":"script/fpgen/wired.py","file_name":"wired.py","file_ext":"py","file_size_in_byte":1132,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"15"} +{"seq_id":"16614914318","text":"import logging as log\n\nfrom flask import current_app as app\n\nfrom main.database.db import MongoDB\nfrom main.services.wallet_service import WalletService\n\n\nclass OrderService:\n \"\"\" doc string for OrderService \"\"\"\n\n def __init__(self):\n super(OrderService, self).__init__()\n self.collection = \"orders\"\n self.mongo = MongoDB()\n self.wallet_service = WalletService()\n\n def orders_list(self, user_id):\n \"\"\" List orders for the user \"\"\"\n orders = self.mongo.find(self.collection, {\"user_id\" : user_id})\n if orders:\n return orders\n else:\n return []\n\n def place_order(self, order_entry):\n \"\"\" Assume INR based orders. \"\"\"\n user = order_entry[\"user\"]\n symbol = order_entry[\"symbol\"]\n price = order_entry[\"price\"]\n pair_quantity = order_entry[\"pairQuantity\"]\n\n # Check if user has sufficient INR to purchase\n if order_entry[\"side\"] == \"BUY\":\n wallet_balances = user[\"Balances\"]\n for balance_entry in wallet_balances:\n if balance_entry[\"symbol\"] == \"inr\":\n inr_balance = balance_entry[\"quantity\"]\n\n if inr_balance <= order_entry[\"pairQuantity\"]:\n return {\"status\": -1, \"message\": \"Insufficient Balance\"}\n\n # all is good - perform buy\n # buy symbol + sell INR\n\n order_entry = {\n \"user_id\": user[\"_id\"],\n \"symbol\": symbol,\n \"price\": price,\n \"pairQuantity\": pair_quantity,\n \"status\": \"ToBeExecuted\"\n }\n\n self.mongo.save(self.collection, order_entry)\n self.wallet_service.update_balance_for_sell(user[\"UserInfo\"][\"_id\"], \"inr\", price * pair_quantity)\n self.wallet_service.update_balance_for_buy(user[\"UserInfo\"][\"_id\"], symbol, pair_quantity)\n return {\"status\": 0, \"message\": \"Order successfully placed\"}\n else:\n # Sell operation\n wallet_balances = user[\"Balances\"]\n for balance_entry in wallet_balances:\n if balance_entry[\"symbol\"] == symbol:\n balance = balance_entry[\"quantity\"]\n\n if balance <= order_entry[\"pairQuantity\"]:\n return {\"status\": -1, \"message\": \"Insufficient Balance\"}\n\n # all is good - perform buy\n # buy symbol + sell INR\n\n order_entry = {\n \"user_id\": user[\"_id\"],\n \"symbol\": symbol,\n \"price\": price,\n \"pairQuantity\": pair_quantity,\n \"status\": \"ToBeExecuted\"\n }\n\n self.mongo.save(self.collection, order_entry)\n self.wallet_service.update_balance_for_sell(user[\"UserInfo\"][\"_id\"], symbol,pair_quantity)\n self.wallet_service.update_balance_for_buy(user[\"UserInfo\"][\"_id\"], \"inr\", price * pair_quantity)\n return {\"status\": 0, \"message\": \"Order successfully placed\"}","repo_name":"gskfreelance/backend_flask","sub_path":"main/services/order_service.py","file_name":"order_service.py","file_ext":"py","file_size_in_byte":3012,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"15"} +{"seq_id":"20464570629","text":"import os\nimport sys\nimport json\nimport boto3\nimport http.client\nfrom dateutil.parser import parse\n\nslack_host = os.environ.get(\"SLACK_HOST\")\nslack_channel = os.environ.get(\"SLACK_CHANNEL\")\n# Colours\nGREEN = '#36a64f'\nRED = '#ff0000'\nBLUE = '#439FE0'\nGRAY = '#dddddd'\nBLACK = '#000000'\n\nssm_client = boto3.client('ssm')\n\nheaders = {\n 'Content-Type': 'application/json',\n}\n\n\ndef getAwsAccountName(id):\n if id == '472057503814':\n return 'prod'\n elif id == '843407916570':\n return 'dev (new)'\n elif id == '620123204273':\n return 'dev (old)'\n elif id == '602836945884':\n return 'agha'\n else:\n return id\n\n\ndef getCreatorFromId(id):\n if id == 'c9688651-7872-3753-8146-ffa41c177aa1':\n return f\"{id} (Vlad Saveliev - unimelb)\"\n elif id == '590dfb6c-6e4f-3db8-9e23-2d1039821653':\n return f\"{id} (Vlad Saveliev)\"\n elif id == '567d89e4-de8b-3688-a733-d2a979eb510e':\n return f\"{id} (Peter - unimelb)\"\n elif id == 'bd68e368-7587-3e22-a30e-9a2e1714b7c1':\n return f\"{id} (Peter Diakumis)\"\n elif id == '1678890e-b107-3974-a47d-0bb532a64ad6':\n return f\"{id} (Roman Valls - unimelb)\"\n elif id == '9c925fa3-9b93-3f14-92a3-d35488ab1cc4':\n return f\"{id} (Roman Valls)\"\n elif id == '8abf754b-e94f-3841-b44b-75d10d33588b':\n return f\"{id} (Sehrish unimelb)\"\n elif id == 'd24913a8-676f-39f3-9250-7cf22fbc48c8':\n return f\"{id} (Sehrish Kanwal)\"\n elif id == '7eec7332-f780-3edc-bb70-c4f711398f1c':\n return f\"{id} (Florian - unimelb)\"\n elif id == '6039c53c-d362-3dd6-9294-46f08d8994ff':\n return f\"{id} (Florian Reisinger)\"\n elif id == '57a99faa-ae79-33f8-9736-454a36b06a43':\n return f\"{id} (Service User)\"\n elif id == 'ef928f99-662d-3e9f-8476-303131e9a58a':\n return f\"{id} (Karey Cheong)\"\n elif id == 'a46c2704-4568-3a39-b934-45bc9b352ac8':\n return f\"{id} (Voula Dimitriadis)\"\n elif id == '6696900a-96ea-372a-bc00-ca6bbe19bf7b':\n return f\"{id} (Kym Pham)\"\n elif id == '3ed6bc8a-ba5a-3ec3-9e25-361703c7ba20':\n return f\"{id} (Egan Lohman)\"\n elif id == 'b2f0ff65-c77b-37bc-af87-68a89c2f8d27':\n return f\"{id} (Alexis Lucattini)\"\n elif id == '46258763-7c48-3a1c-8c5f-04003bf74e5a':\n return f\"{id} (Alexis - unimelb)\"\n elif id == 'aa9f1c02-3963-3c3b-ad0d-9b6f6e26a405':\n return f\"{id} Pratik Soares (Illumina)\"\n elif id == 'e44e09eb-60c7-3a0f-9313-46f7454ede92':\n return f\"{id} Andrei Seleznev (Illumina)\"\n elif id == 'e3c89a8a-23a7-36cf-a1dc-281d96ed1aab':\n return f\"{id} Yinan Wang (Illumina)\"\n elif id == '41fc4571-741c-386e-be44-cf9ae7313f53':\n return f\"{id} Victor Lin\"\n else:\n return f\"{id} (unknown)\"\n\n\ndef getWgNameFromId(wid):\n if wid == 'wid:e4730533-d752-3601-b4b7-8d4d2f6373de':\n return 'development'\n elif wid == 'wid:9c481003-f453-3ff2-bffa-ae153b1ee565':\n return 'collab-illumina-dev'\n elif wid == 'wid:acddbfda-4980-38ed-99fa-94fe79523959':\n return 'clinical-genomics-workgroup'\n elif wid == 'wid:4d2aae8c-41d3-302e-a814-cdc210e4c38b':\n return 'production'\n else:\n return 'unknown'\n\n\ndef getSSMParam(name):\n \"\"\"\n Fetch the parameter with the given name from SSM Parameter Store.\n \"\"\"\n return ssm_client.get_parameter(\n Name=name,\n WithDecryption=True\n )['Parameter']['Value']\n\n\ndef call_slack_webhook(sender, topic, attachments):\n slack_webhook_endpoint = '/services/' + getSSMParam(\"/slack/webhook/id\")\n\n connection = http.client.HTTPSConnection(slack_host)\n\n post_data = {\n \"channel\": slack_channel,\n \"username\": sender,\n \"text\": \"*\" + topic + \"*\",\n \"icon_emoji\": \":aws_logo:\",\n \"attachments\": attachments\n }\n print(f\"Slack POST data: {json.dumps(post_data)}\")\n\n connection.request(\"POST\", slack_webhook_endpoint, json.dumps(post_data), headers)\n response = connection.getresponse()\n print(f\"Slack webhook response: {response}\")\n connection.close()\n\n return response.status\n\n\ndef slack_message_not_supported(sns_record):\n print(\"Trying to parse message for currently unsupported message format...\")\n aws_account = sns_record.get('TopicArn').split(':')[4]\n sns_record_date = parse(sns_record.get('Timestamp'))\n\n sns_msg_atts = sns_record.get('MessageAttributes')\n stratus_action = sns_msg_atts['action']['Value']\n stratus_action_date = sns_msg_atts['actiondate']['Value']\n stratus_action_type = sns_msg_atts['type']['Value']\n stratus_produced_by = sns_msg_atts['producedby']['Value']\n\n sns_msg = json.loads(sns_record.get('Message'))\n print(f\"Extracted message: {json.dumps(sns_msg)}\")\n\n iap_id = sns_msg['id']\n iap_crated_time = sns_msg['timeCreated'] if sns_msg.get('timeCreated') else \"N/A\"\n iap_created_by = sns_msg['createdBy'] if sns_msg.get('createdBy') else \"N/A\"\n\n slack_color = GRAY\n\n slack_sender = \"Illumina Application Platform\"\n slack_topic = f\"Notification from {stratus_action_type}\"\n slack_attachment = [\n {\n \"fallback\": f\"Unsupported notification\",\n \"color\": slack_color,\n \"title\": f\"IAP ID: {iap_id}\",\n \"fields\": [\n {\n \"title\": \"Action\",\n \"value\": stratus_action,\n \"short\": True\n },\n {\n \"title\": \"Action Type\",\n \"value\": stratus_action_type,\n \"short\": True\n },\n {\n \"title\": \"Action Date\",\n \"value\": stratus_action_date,\n \"short\": True\n },\n {\n \"title\": \"Produced By\",\n \"value\": stratus_produced_by,\n \"short\": True\n },\n {\n \"title\": \"Task Created At\",\n \"value\": iap_crated_time,\n \"short\": True\n },\n {\n \"title\": \"Task Created By\",\n \"value\": getCreatorFromId(iap_created_by),\n \"short\": True\n },\n {\n \"title\": \"AWS Account\",\n \"value\": getAwsAccountName(aws_account),\n \"short\": True\n }\n ],\n \"footer\": \"IAP Notification\",\n \"ts\": int(sns_record_date.timestamp())\n }\n ]\n return slack_sender, slack_topic, slack_attachment\n\n\ndef slack_message_from_wes_runs_historyevents(sns_record):\n # NOTE: wes.runs.historyevents action: \"started\", \"succeeded\", \"failed\", \"aborted\"\n print(\"Parsing wes.runs.historyevents notification....\")\n aws_account = sns_record.get('TopicArn').split(':')[4]\n sns_record_date = parse(sns_record.get('Timestamp'))\n\n sns_msg_atts = sns_record.get('MessageAttributes')\n stratus_action = sns_msg_atts['action']['Value']\n stratus_action_type = sns_msg_atts['type']['Value']\n if sns_msg_atts.get('actionDate'):\n stratus_action_date = sns_msg_atts['actionDate']['Value']\n else:\n stratus_action_date = sns_msg_atts['actiondate']['Value']\n if sns_msg_atts.get('producedBy'):\n stratus_produced_by = sns_msg_atts['producedBy']['Value']\n else:\n stratus_produced_by = sns_msg_atts['producedby']['Value']\n\n sns_msg = json.loads(sns_record.get('Message'))\n print(f\"Extracted message: {json.dumps(sns_msg)}\")\n\n wes_run = sns_msg['WorkflowRun']\n wes_run_id = wes_run['Id']\n\n wes_run_name = 'unknown' # TODO: not part of the event/notification?\n wes_run_status = wes_run['Status']\n wes_run_crated_time = wes_run['TimeCreated']\n wes_run_created_by = wes_run['CreatedBy']\n wes_run_description = wes_run['WorkflowVersion']['Description']\n\n action = stratus_action.lower()\n status = wes_run_status.lower()\n if action == 'started':\n slack_color = BLUE\n elif action == 'succeeded':\n slack_color = GREEN\n elif action == 'failed' or action == 'aborted':\n slack_color = RED\n else:\n slack_color = BLACK\n\n slack_sender = \"Illumina Application Platform\"\n slack_topic = f\"Notification from {stratus_action_type}\"\n slack_attachment = [\n {\n \"fallback\": f\"WES run {wes_run_name}: {wes_run_status}\",\n \"color\": slack_color,\n \"pretext\": wes_run_name,\n \"title\": f\"Task ID: {wes_run_id}\",\n \"text\": wes_run_description,\n \"fields\": [\n {\n \"title\": \"Action\",\n \"value\": stratus_action,\n \"short\": True\n },\n {\n \"title\": \"Action Type\",\n \"value\": stratus_action_type,\n \"short\": True\n },\n {\n \"title\": \"Action Status\",\n \"value\": status,\n \"short\": True\n },\n {\n \"title\": \"Action Date\",\n \"value\": stratus_action_date,\n \"short\": True\n },\n {\n \"title\": \"Produced By\",\n \"value\": stratus_produced_by,\n \"short\": True\n },\n {\n \"title\": \"Task Created At\",\n \"value\": wes_run_crated_time,\n \"short\": True\n },\n {\n \"title\": \"Task Created By\",\n \"value\": getCreatorFromId(wes_run_created_by),\n \"short\": True\n },\n {\n \"title\": \"AWS Account\",\n \"value\": getAwsAccountName(aws_account),\n \"short\": True\n }\n ],\n \"footer\": \"IAP TES Task\",\n \"ts\": int(sns_record_date.timestamp())\n }\n ]\n return slack_sender, slack_topic, slack_attachment\n\n\ndef slack_message_from_wes_runs(sns_record):\n # NOTE: wes.runs.historyevents action: \"created\", \"updated\", \"aborted\"\n print(\"Parsing wes.runs notification....\")\n aws_account = sns_record.get('TopicArn').split(':')[4]\n sns_record_date = parse(sns_record.get('Timestamp'))\n\n sns_msg_atts = sns_record.get('MessageAttributes')\n stratus_action = sns_msg_atts['action']['Value']\n stratus_action_type = sns_msg_atts['type']['Value']\n if sns_msg_atts.get('actionDate'):\n stratus_action_date = sns_msg_atts['actionDate']['Value']\n else:\n stratus_action_date = sns_msg_atts['actiondate']['Value']\n if sns_msg_atts.get('producedBy'):\n stratus_produced_by = sns_msg_atts['producedBy']['Value']\n else:\n stratus_produced_by = sns_msg_atts['producedby']['Value']\n\n sns_msg = json.loads(sns_record.get('Message'))\n print(f\"Extracted message: {json.dumps(sns_msg)}\")\n\n slack_sender = ''\n slack_topic = ''\n slack_attachment = ''\n\n return slack_sender, slack_topic, slack_attachment\n\n\ndef slack_message_from_tes_runs(sns_record):\n # NOTE: IAP NES TES status: \"Pending\", \"Running\", \"Completed\", \"Failed\", \"TimedOut\", \"Aborted\"\n\n aws_account = sns_record.get('TopicArn').split(':')[4]\n sns_record_date = parse(sns_record.get('Timestamp'))\n\n sns_msg_atts = sns_record.get('MessageAttributes')\n stratus_action = sns_msg_atts['action']['Value']\n stratus_action_date = sns_msg_atts['actiondate']['Value']\n stratus_action_type = sns_msg_atts['type']['Value']\n stratus_produced_by = sns_msg_atts['producedby']['Value']\n\n sns_msg = json.loads(sns_record.get('Message'))\n print(f\"Extracted message: {json.dumps(sns_msg)}\")\n\n task_id = sns_msg['id']\n task_name = sns_msg['name']\n task_status = sns_msg['status']\n task_description = sns_msg['description']\n if 'SHOWCASE' in task_name:\n task_description = 'SFN task callback token'\n task_crated_time = sns_msg['timeCreated']\n task_created_by = sns_msg['createdBy']\n\n action = stratus_action.lower()\n status = task_status.lower()\n if action == 'created':\n slack_color = BLUE\n elif action == 'updated' and (status == 'pending' or status == 'running'):\n slack_color = GRAY\n elif action == 'updated' and status == 'completed':\n slack_color = GREEN\n elif action == 'updated' and (status == 'aborted' or status == 'failed' or status == 'timedout'):\n slack_color = RED\n else:\n slack_color = BLACK\n\n slack_sender = \"Illumina Application Platform\"\n slack_topic = f\"Notification from {stratus_action_type}\"\n slack_attachment = [\n {\n \"fallback\": f\"Task {task_name} update: {task_status}\",\n \"color\": slack_color,\n \"pretext\": task_name,\n \"title\": f\"Task ID: {task_id}\",\n \"text\": task_description,\n \"fields\": [\n {\n \"title\": \"Action\",\n \"value\": stratus_action,\n \"short\": True\n },\n {\n \"title\": \"Action Type\",\n \"value\": stratus_action_type,\n \"short\": True\n },\n {\n \"title\": \"Action Status\",\n \"value\": status.upper(),\n \"short\": True\n },\n {\n \"title\": \"Action Date\",\n \"value\": stratus_action_date,\n \"short\": True\n },\n {\n \"title\": \"Produced By\",\n \"value\": stratus_produced_by,\n \"short\": True\n },\n {\n \"title\": \"Task Created At\",\n \"value\": task_crated_time,\n \"short\": True\n },\n {\n \"title\": \"Task Created By\",\n \"value\": getCreatorFromId(task_created_by),\n \"short\": True\n },\n {\n \"title\": \"AWS Account\",\n \"value\": getAwsAccountName(aws_account),\n \"short\": True\n }\n ],\n \"footer\": \"IAP TES Task\",\n \"ts\": int(sns_record_date.timestamp())\n }\n ]\n return slack_sender, slack_topic, slack_attachment\n\n\ndef slack_message_from_gds_uploaded(sns_record):\n # TODO: extend to other gds actions, items\n aws_account = sns_record.get('TopicArn').split(':')[4]\n sns_record_date = parse(sns_record.get('Timestamp'))\n\n sns_msg_atts = sns_record.get('MessageAttributes')\n stratus_action = sns_msg_atts['action']['Value']\n stratus_action_date = sns_msg_atts['actiondate']['Value']\n stratus_action_type = sns_msg_atts['type']['Value']\n stratus_produced_by = sns_msg_atts['producedby']['Value']\n\n sns_msg = json.loads(sns_record.get('Message'))\n print(f\"Extracted message: {json.dumps(sns_msg)}\")\n\n file_id = sns_msg['id']\n file_name = sns_msg['name']\n file_path = sns_msg['path']\n volume_name = sns_msg['volumeName']\n file_crated_time = sns_msg['timeCreated']\n file_created_by = sns_msg['createdBy']\n\n slack_color = GREEN\n\n slack_sender = \"Illumina Application Platform\"\n slack_topic = f\"Notification from {stratus_action_type}\"\n slack_attachment = [\n {\n \"fallback\": f\"File {file_name} {stratus_action}\",\n \"color\": slack_color,\n \"pretext\": file_name,\n \"title\": f\"File ID: {file_id}\",\n \"text\": file_path,\n \"fields\": [\n {\n \"title\": \"Action\",\n \"value\": stratus_action,\n \"short\": True\n },\n {\n \"title\": \"Action Type\",\n \"value\": stratus_action_type,\n \"short\": True\n },\n {\n \"title\": \"Volumn name\",\n \"value\": volume_name,\n \"short\": True\n },\n {\n \"title\": \"Action Date\",\n \"value\": stratus_action_date,\n \"short\": True\n },\n {\n \"title\": \"Produced By\",\n \"value\": stratus_produced_by,\n \"short\": True\n },\n {\n \"title\": \"File Created At\",\n \"value\": file_crated_time,\n \"short\": True\n },\n {\n \"title\": \"File Created By\",\n \"value\": getCreatorFromId(file_created_by),\n \"short\": True\n },\n {\n \"title\": \"AWS Account\",\n \"value\": getAwsAccountName(aws_account),\n \"short\": True\n }\n ],\n \"footer\": \"IAP GDS Event\",\n \"ts\": int(sns_record_date.timestamp())\n }\n ]\n return slack_sender, slack_topic, slack_attachment\n\n\ndef slack_message_from_bssh_runs(sns_record):\n # TODO: parse ACL, extract workgroup ID and map to workgroup name\n aws_account = sns_record.get('TopicArn').split(':')[4]\n sns_record_date = parse(sns_record.get('Timestamp'))\n\n sns_msg_atts = sns_record.get('MessageAttributes')\n stratus_action = sns_msg_atts['action']['Value']\n stratus_action_date = sns_msg_atts['actiondate']['Value']\n stratus_action_type = sns_msg_atts['type']['Value']\n stratus_produced_by = sns_msg_atts['producedby']['Value']\n\n sns_msg = json.loads(sns_record.get('Message'))\n print(f\"Extracted message: {json.dumps(sns_msg)}\")\n\n run_id = sns_msg['id']\n name = sns_msg['name']\n folder_path = sns_msg['gdsFolderPath']\n volume_name = sns_msg['gdsVolumeName']\n date_modified = sns_msg['dateModified']\n instrument_run_id = sns_msg['instrumentRunId']\n status = sns_msg['status']\n\n acl = sns_msg['acl']\n if len(acl) == 1:\n owner = getWgNameFromId(acl[0])\n else:\n print(\"Multiple IDs in ACL, expected 1!\")\n owner = 'undetermined'\n\n # Map status to colour\n # https://support.illumina.com/help/BaseSpace_Sequence_Hub/Source/Informatics/BS/Statuses_swBS.htm\n # Sequencing statuses\n # •\tRunning—The instrument is sequencing the run.\n # •\tPaused—A user paused the run on the instrument control software.\n # •\tStopped—The instrument has been put into a Stopped state through the instrument control software.\n # File Upload and Analysis statuses\n # •\tUploading—The instrument completed sequencing and is uploading files.\n # •\tFailed Upload—The instrument failed to upload files to the BaseSpace Sequence Hub.\n # •\tPending Analysis—The file has uploaded completely and is waiting for the Generate FASTQ analysis to begin.\n # •\tAnalyzing—The Generate FASTQ analysis is running.\n # •\tComplete—The sequencing run and subsequent Generate FASTQ analysis completed successfully.\n # •\tFailed—Either the sequencing run was failed using the instrument control software or Generate FASTQ failed to complete.\n # •\tRehybing—A flow cell has been sent back to a cBot for rehybing. When the new run is complete, the rehybing status is changed to Failed.\n # •\tNeeds Attention—There is an issue with the sample sheet associated with the run. The run can be requeued after the sample sheet is fixed.\n # •\tTimed Out—There is an issue with the sample sheet associated with the run. The run can be requeued after the sample sheet is fixed.\n if status == 'Uploading' or status == 'Running':\n slack_color = BLUE\n elif status == 'PendingAnalysis' or status == 'Complete':\n slack_color = GREEN\n elif status == 'FailedUpload' or status == 'Failed' or status == 'TimedOut':\n slack_color = RED\n else:\n print(f\"Unsupported status {status}. Not reporting to Slack!\")\n sys.exit(0)\n\n slack_sender = \"Illumina Application Platform\"\n slack_topic = f\"Notification from {stratus_action_type}\"\n slack_attachment = [\n {\n \"fallback\": f\"Run {instrument_run_id}: {status}\",\n \"color\": slack_color,\n \"pretext\": name,\n \"title\": f\"Run: {instrument_run_id}\",\n \"text\": folder_path,\n \"fields\": [\n {\n \"title\": \"Action\",\n \"value\": stratus_action,\n \"short\": True\n },\n {\n \"title\": \"Action Type\",\n \"value\": stratus_action_type,\n \"short\": True\n },\n {\n \"title\": \"Status\",\n \"value\": status,\n \"short\": True\n },\n {\n \"title\": \"Volumn name\",\n \"value\": volume_name,\n \"short\": True\n },\n {\n \"title\": \"Action Date\",\n \"value\": stratus_action_date,\n \"short\": True\n },\n {\n \"title\": \"Modified Date\",\n \"value\": date_modified,\n \"short\": True\n },\n {\n \"title\": \"Produced By\",\n \"value\": stratus_produced_by,\n \"short\": True\n },\n {\n \"title\": \"BSSH run ID\",\n \"value\": run_id,\n \"short\": True\n },\n {\n \"title\": \"Run owner\",\n \"value\": owner,\n \"short\": True\n },\n {\n \"title\": \"AWS Account\",\n \"value\": getAwsAccountName(aws_account),\n \"short\": True\n }\n ],\n \"footer\": \"IAP GDS Event\",\n \"ts\": int(sns_record_date.timestamp())\n }\n ]\n return slack_sender, slack_topic, slack_attachment\n\n\ndef lambda_handler(event, context):\n # Log the received event in CloudWatch\n print(f\"Received event: {json.dumps(event)}\")\n print(\"Invocation context:\")\n print(f\"LogGroup: {context.log_group_name}\")\n print(f\"LogStream: {context.log_stream_name}\")\n print(f\"RequestId: {context.aws_request_id}\")\n print(f\"FunctionName: {context.function_name}\")\n\n # we expect events of a defined format\n records = event.get('Records')\n if len(records) == 1:\n record = records[0]\n if record.get('EventSource') == 'aws:sns' and record.get('Sns'):\n sns_record = record.get('Sns')\n\n if sns_record.get('MessageAttributes'):\n if sns_record['MessageAttributes']['type']['Value'] == 'gds.files':\n slack_sender, slack_topic, slack_attachment = slack_message_from_gds_uploaded(sns_record)\n elif sns_record['MessageAttributes']['type']['Value'] == 'tes.runs':\n slack_sender, slack_topic, slack_attachment = slack_message_from_tes_runs(sns_record)\n elif sns_record['MessageAttributes']['type']['Value'] == 'bssh.runs':\n slack_sender, slack_topic, slack_attachment = slack_message_from_bssh_runs(sns_record)\n elif sns_record['MessageAttributes']['type']['Value'] == 'wes.runs':\n slack_sender, slack_topic, slack_attachment = slack_message_from_wes_runs(sns_record)\n elif sns_record['MessageAttributes']['type']['Value'] == 'wes.runs.historyevents':\n slack_sender, slack_topic, slack_attachment = slack_message_from_wes_runs_historyevents(sns_record)\n else:\n slack_sender, slack_topic, slack_attachment = slack_message_not_supported(sns_record)\n else:\n raise ValueError(\"Unexpected Message Format!\")\n else:\n raise ValueError(\"Unexpected Message Format!\")\n\n # Forward the data to Slack\n try:\n print(f\"Slack sender: ({slack_sender}), topic: ({slack_topic}) and attachments: {json.dumps(slack_attachment)}\")\n # if we couldn't assign any sensible value, there is no point in sending a slack message\n if slack_sender or slack_topic or slack_attachment:\n response = call_slack_webhook(slack_sender, slack_topic, slack_attachment)\n print(f\"Response status: {response}\")\n else:\n ValueError(\"Could not extract sensible values from event! Not sending Slack message.\")\n except Exception as e:\n print(e)\n raise ValueError('Error sending message to Slack')\n\n return event\n","repo_name":"umccr/infrastructure","sub_path":"cdk/apps/slack/lambdas/iap/notify_slack.py","file_name":"notify_slack.py","file_ext":"py","file_size_in_byte":24970,"program_lang":"python","lang":"en","doc_type":"code","stars":9,"dataset":"github-code","pt":"15"} +{"seq_id":"73128374092","text":"def rotate_square_image_ccw(matrix):\n length = len(matrix)\n inL = len(matrix[0])\n # transpose\n for i in range(0, length):\n for j in range(i, inL):\n matrix[i][j], matrix[j][i] = matrix[j][i], matrix[i][j]\n #horizontal \n for j in range(0, int(round((length)/2))):\n matrix[j], matrix[length-1-j] = matrix[length-1-j], matrix[j]\n return matrix\n","repo_name":"BinamB/Firecode","sub_path":"Level 3/rotateSquareImage.py","file_name":"rotateSquareImage.py","file_ext":"py","file_size_in_byte":386,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"15"} +{"seq_id":"71198744971","text":"from backend.transact.Wallet import Wallet\nfrom backend.utils.utils import BlockchainUtils\nimport requests\n\ndef post_transaction(sender, receiver, amount, type):\n transaction = sender.create_transaction(receiver.public_key_string(), amount, type)\n url = 'http://localhost:5005/transaction'\n package = {'transaction': BlockchainUtils.encode(transaction)}\n request = requests.post(url, json=package)\n print(request.text)\n\ndef test_interaction():\n bob = Wallet()\n alice = Wallet()\n alice.from_key('backend/keys/stakerPrivateKey.pem')\n exchange = Wallet()\n\n # # forger: genesis\n # post_transaction(exchange, alice, 100, 'EXCHANGE')\n # post_transaction(exchange, bob, 100, 'EXCHANGE')\n # post_transaction(exchange, alice, 25, 'STAKE')\n\n # # forger: most likely Alice\n # post_transaction(alice, bob, 1, 'TRANSFER')\n\n # forger: genesis\n post_transaction(exchange, alice, 1000, 'EXCHANGE')\n post_transaction(exchange, bob, 100, 'EXCHANGE')\n post_transaction(exchange, bob, 10, 'EXCHANGE')\n\n # forger: most likely Alice\n post_transaction(exchange, alice, 25, 'STAKE')\n post_transaction(alice, bob, 1, 'TRANSFER')\n post_transaction(alice, bob, 1, 'TRANSFER')\n\ndef old_transaction():\n bob = Wallet()\n alice = Wallet()\n exchange = Wallet()\n\n transaction = exchange.create_transaction(alice.public_key_string(), 10, 'EXCHANGE')\n url = 'http://localhost:5005/transaction'\n package = {'transaction': BlockchainUtils.encode(transaction)}\n request = requests.post(url, json=package)\n print(request.text)\n\n\nif __name__ == '__main__':\n test_interaction()\n # old_transaction()","repo_name":"chunoxie/posblockchain","sub_path":"backend/tests/Interaction.py","file_name":"Interaction.py","file_ext":"py","file_size_in_byte":1655,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"15"} +{"seq_id":"29777159456","text":"from __future__ import unicode_literals\n\nimport sys\nimport os\n\nimport wx\nimport wx.lib.agw.persist as PERSIST\n\nfrom .info import (\n __appname__,\n __projecturl__\n)\n\nfrom .version import __version__\n\nfrom survey_data import SurveyReader, SurveyWriter\n\n\nclass MainFrame(wx.Frame):\n FRAME_STYLE = wx.DEFAULT_FRAME_STYLE ^ (wx.RESIZE_BORDER | wx.MAXIMIZE_BOX)\n SURVEY_LABEL_TEXT = \"Survey File:\"\n SURVEY_FILE_CTRL_MESSAGE = \"Select Survey Data File\"\n\n LICENSE_LABEL_TEXT = \"Add standard header in exported file\"\n LICENSE_TEXT = \"\"\"This survey data is made available under the Open Data Commons Attribution License:\nhttp://opendatacommons.org/licenses/by/1.0/\"\"\"\n\n PRECALCULATE_LABEL = \"Precalculate average values from duplicated shots.\"\n HIDE_PRECALCULATED_LABEL = \"Hide duplicated shots used for precalculation.\"\n MOVE_SPLAYS_LABEL = \"Move splay shots to the end of trip data.\"\n SHOW_ROLL_LABEL = \"Add DistoX roll value as a comment.\"\n\n ALERT_UNSUPPORTED_FILE_TYPE_CAPTION = \"Unsupported file\"\n ALERT_UNSUPPORTED_FILE_TYPE_MESSAGE = \"Can't recognize this file as a \" \\\n \"survey data, probably it isn't \" \\\n \"supported yet.\"\n ALERT_FINISHED_CAPTION = \"File saved\"\n ALERT_FINISHED_MESSAGE = \"All data have been exported to the file you selected.\"\n\n def __init__(self, parent=None):\n wx.Frame.__init__(self, parent, wx.ID_ANY, __appname__,\n style=self.FRAME_STYLE, name=\"MainFrame\")\n self.__active = False\n\n supported_files = SurveyReader.supported_files()\n supported_extensions = []\n for supported_file in supported_files:\n supported_extensions.append(supported_file[-1])\n supported_extensions = list(set(supported_extensions))\n\n file_types_string = \"\"\n for extension in supported_extensions:\n file_types_string += \"*.%s;\" % extension\n file_types_string = file_types_string.strip(';')\n\n wildcard = \"Supported files (%s)|%s\" % (\n file_types_string, file_types_string)\n\n if hasattr(self, 'SetMinClientSize'):\n self.SetMinClientSize(wx.Size(400, -1))\n\n self._panel = wx.Panel(self)\n\n self._source_file_label = wx.StaticText(self._panel,\n label=self.SURVEY_LABEL_TEXT)\n self._source_file_ctrl = wx.FilePickerCtrl(self._panel,\n message=self.SURVEY_FILE_CTRL_MESSAGE,\n wildcard=wildcard)\n\n self._writers = SurveyWriter.__subclasses__()\n writer_types = []\n for writer in self._writers:\n writer_types.append(writer.file_type())\n\n self._writers_panel = wx.RadioBox(self._panel, label=\"Convert to:\",\n majorDimension=1,\n choices=writer_types,\n style=wx.RA_SPECIFY_ROWS,\n name=\"SelectedWriter\")\n\n self._license_checkbox = wx.CheckBox(self._panel, style=wx.CHK_2STATE,\n label=self.LICENSE_LABEL_TEXT,\n name=\"AddLicense\")\n self._license_checkbox.SetValue(True)\n self._license_textfield = wx.TextCtrl(self._panel,\n style=wx.TE_MULTILINE,\n size=(-1, 60),\n name=\"LicenseText\")\n self._license_textfield.SetValue(self.LICENSE_TEXT)\n\n self._advanced_options_panel = wx.CollapsiblePane(self._panel, label=\"Advanced Options:\",\n style=wx.CP_DEFAULT_STYLE | wx.CP_NO_TLW_RESIZE,\n name=\"AdvancedOptions\")\n collapsible_panel = self._advanced_options_panel.GetPane()\n self._precalculate_checkbox = wx.CheckBox(collapsible_panel, style=wx.CHK_2STATE,\n label=self.PRECALCULATE_LABEL,\n name=\"Precalculate\")\n self._hide_precalculate_checkbox = wx.CheckBox(collapsible_panel, style=wx.CHK_2STATE,\n label=self.HIDE_PRECALCULATED_LABEL,\n name=\"HidePrecalculate\")\n self._move_splays_checkbox = wx.CheckBox(collapsible_panel, style=wx.CHK_2STATE,\n label=self.MOVE_SPLAYS_LABEL,\n name=\"MoveSplays\")\n self._show_roll_checkbox = wx.CheckBox(collapsible_panel, style=wx.CHK_2STATE,\n label=self.SHOW_ROLL_LABEL,\n name=\"ShowRoll\")\n self._advanced_options_panel.Bind(wx.EVT_COLLAPSIBLEPANE_CHANGED, self._on_panel)\n\n self._save_button = wx.Button(self._panel, label=\"Save\")\n self._save_button.Bind(wx.EVT_BUTTON, self._on_save)\n\n if sys.platform == \"win32\":\n self._source_file_ctrl.GetPickerCtrl().SetLabel(\"Browse...\")\n\n self._add_sizers()\n\n self._toggle_export_interface(False)\n\n self.Center()\n\n self._register_and_restore()\n\n self.Bind(wx.EVT_CLOSE, self._on_exit)\n self._source_file_ctrl.Bind(wx.EVT_FILEPICKER_CHANGED,\n self._on_file_selected)\n\n def _register_and_restore(self):\n mgr = PERSIST.PersistenceManager.Get()\n mgr.RegisterAndRestore(self)\n mgr.RegisterAndRestore(self._writers_panel)\n mgr.RegisterAndRestore(self._license_checkbox)\n mgr.RegisterAndRestore(self._license_textfield)\n mgr.RegisterAndRestore(self._advanced_options_panel)\n mgr.RegisterAndRestore(self._precalculate_checkbox)\n mgr.RegisterAndRestore(self._hide_precalculate_checkbox)\n mgr.RegisterAndRestore(self._move_splays_checkbox)\n mgr.RegisterAndRestore(self._show_roll_checkbox)\n self.Fit()\n\n def _on_exit(self, event):\n mgr = PERSIST.PersistenceManager.Get()\n mgr.SaveAndUnregister()\n event.Skip()\n\n def _on_panel(self, event):\n self.Fit()\n event.Skip()\n\n def _on_save(self, event):\n header = \"\"\n if self._license_checkbox.GetValue():\n header = self._license_textfield.GetValue()\n\n idx = self._writers_panel.GetSelection()\n writer = self._writers[idx]\n survey_file_path = self._source_file_ctrl.GetPath()\n save_file_name = os.path.basename(survey_file_path)\n save_file_name = os.path.splitext(save_file_name)[0]\n save_file_name += \".\" + writer.file_extension()\n save_file_dialog = wx.FileDialog(self, message=\"Save As\",\n defaultFile=save_file_name,\n style=wx.FD_SAVE |\n wx.FD_OVERWRITE_PROMPT)\n if save_file_dialog.ShowModal() == wx.ID_OK:\n footer = \"Created with %s v%s (%s)\" % (\n __appname__, __version__, __projecturl__)\n self._file_reader = SurveyReader(self._file_reader.file_path)\n writer(self._file_reader, save_file_dialog.GetPath(), self._precalculate_checkbox.GetValue(),\n self._hide_precalculate_checkbox.GetValue(), self._move_splays_checkbox.GetValue(),\n self._show_roll_checkbox.GetValue(), header,\n footer)\n alert = wx.MessageDialog(self, self.ALERT_FINISHED_MESSAGE,\n self.ALERT_FINISHED_CAPTION,\n wx.OK | wx.ICON_INFORMATION)\n alert.Center()\n alert.ShowModal()\n alert.Destroy()\n\n save_file_dialog.Destroy()\n event.Skip()\n\n def _on_file_selected(self, event):\n survey_file_path = self._source_file_ctrl.GetPath()\n self._file_reader = SurveyReader(survey_file_path)\n export_possible = self._file_reader is not None\n self._toggle_export_interface(export_possible)\n if not export_possible:\n self._alert_unsupported_survey_file()\n event.Skip()\n\n def _add_sizers(self):\n horizontal_sizer = wx.BoxSizer(wx.HORIZONTAL)\n vertical_sizer = wx.BoxSizer(wx.VERTICAL)\n source_file_sizer = wx.BoxSizer(wx.HORIZONTAL)\n\n source_file_sizer.Add(self._source_file_label, 0,\n wx.ALIGN_CENTER_VERTICAL)\n source_file_sizer.AddSpacer(5)\n source_file_sizer.Add(self._source_file_ctrl, 1)\n\n vertical_sizer.Add(source_file_sizer, 0, wx.TOP | wx.BOTTOM | wx.EXPAND,\n 0)\n vertical_sizer.Add(wx.StaticLine(self._panel), 0,\n wx.TOP | wx.BOTTOM | wx.EXPAND, 10)\n\n vertical_sizer.Add(self._writers_panel, 0,\n wx.TOP | wx.BOTTOM | wx.EXPAND,\n 0)\n\n vertical_sizer.Add(wx.StaticLine(self._panel), 0,\n wx.TOP | wx.BOTTOM | wx.EXPAND, 10)\n vertical_sizer.Add(self._license_checkbox, 0,\n wx.ALIGN_CENTER_HORIZONTAL, 0)\n vertical_sizer.AddSpacer(5)\n vertical_sizer.Add(self._license_textfield, 0,\n wx.TOP | wx.BOTTOM | wx.EXPAND, 0)\n\n vertical_sizer.AddSpacer(5)\n vertical_sizer.Add(self._advanced_options_panel, 0,\n wx.TOP | wx.BOTTOM | wx.EXPAND, 0)\n\n collapsible_panel = self._advanced_options_panel.GetPane()\n collapsible_panel_sizer = wx.BoxSizer(wx.VERTICAL)\n collapsible_panel_sizer.Add(self._precalculate_checkbox, wx.GROW | wx.ALL, 0)\n collapsible_panel_sizer.Add(self._hide_precalculate_checkbox, wx.GROW | wx.ALL, 0)\n collapsible_panel_sizer.Add(self._move_splays_checkbox, wx.GROW | wx.ALL, 0)\n collapsible_panel_sizer.Add(self._show_roll_checkbox, wx.GROW | wx.ALL, 0)\n collapsible_panel_sizer.Add(wx.StaticLine(collapsible_panel), 0,\n wx.TOP | wx.BOTTOM | wx.EXPAND, 10)\n collapsible_panel.SetSizer(collapsible_panel_sizer)\n\n vertical_sizer.Add(self._save_button, 0, wx.ALIGN_RIGHT,\n 0)\n\n horizontal_sizer.Add(vertical_sizer, 1, wx.EXPAND | wx.ALL, 10)\n self._panel.SetSizer(horizontal_sizer)\n\n main_sizer = wx.BoxSizer(wx.VERTICAL)\n main_sizer.Add(self._panel, 1, wx.EXPAND)\n self.SetSizer(main_sizer)\n\n def _alert_unsupported_survey_file(self):\n alert = wx.MessageDialog(self, self.ALERT_UNSUPPORTED_FILE_TYPE_MESSAGE,\n self.ALERT_UNSUPPORTED_FILE_TYPE_CAPTION,\n wx.OK | wx.ICON_ERROR)\n alert.Center()\n alert.ShowModal()\n alert.Destroy()\n\n def _toggle_export_interface(self, active):\n self._writers_panel.Enable(active)\n self._save_button.Enable(active)\n","repo_name":"amlynarczyk/SurveyDataConverter","sub_path":"survey_data_converter/main_frame.py","file_name":"main_frame.py","file_ext":"py","file_size_in_byte":11283,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"15"} +{"seq_id":"73965141451","text":"import read.reader as reader\nimport build.builder as builder\nimport sys\n\n# read args\nargs = [a.lower() for a in sys.argv]\ntry:\n action = args[1]\n assert action in ['read', 'build']\n params = args[2:]\nexcept:\n print('error: invalid arguments')\n print(' run.py read # read and process new data')\n print(' run.py read # read and process new data from book1 only')\n print(' run.py build # rebuild html page')\n exit(1)\n\n\nif action == 'read':\n reader.read(books=params)\n\nif action == 'build':\n records = reader.get()\n builder.build(records)\n","repo_name":"jackarnold84/book-tracker","sub_path":"run.py","file_name":"run.py","file_ext":"py","file_size_in_byte":609,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"15"} +{"seq_id":"753947836","text":"#мпортим всё необходимое\nfrom flask import Flask\nfrom schematics.models import Model\nfrom schematics.types import StringType, EmailType, BooleanType, IntType, ListType, ModelType, DateTimeType\nfrom .my_types import One2One\n\n# required означает является ли наличие в переменной чего либо\n# required=True : обязательно; required=False : не обязательно\n\n# default означает значение переменной если оно не задано\n\n# name означает имя модели\n\n#Создаем модель\nclass UserType(Model):\n _name = 'user_type'\n id = IntType(required=False)\n type_name = StringType(required=True)\n\n#Создаем модель создания пользователся\nclass UserAddModel(Model):\n _name = 'users_add'\n id = IntType(required=False)\n age = IntType(default=None, required=False)\n phone = StringType(default=None, required=False)\n address = StringType(default=None, required=False)\n sex = IntType(default=None, required=False)\n users = IntType(default=None, required=False)\n\n#Создаем модель пользователя\nclass UserModel(Model):\n _name = 'users'\n id = IntType(required=False)\n first_name = StringType(required=True)\n last_name = StringType(required=False, default='')\n type = ModelType(UserType, required=True)\n descr = StringType(required=False, default='')\n user_photo = StringType(required=False, default='')\n user_photos = StringType(required=False, default='')\n email = EmailType(required=True)\n nickname = StringType(required=True)\n password = StringType(required=True)\n users_add = One2One(UserAddModel)\n\n#Создаем модель отношений между пользователями\nclass UserRelation(Model):\n _name = 'user_relation'\n id = IntType(required=False)\n user1 = IntType(required=True)\n user2 = IntType(required=True)\n block = IntType(required=True, default=0)\n\n#Создаем модель групп\nclass GroupUserModel(Model):\n id = IntType(required=False)\n group = ModelType(UserModel, required=True)\n user = ModelType(UserModel, required=True)\n\n#Создаем модель постов\nclass PostModel(Model):\n _name = 'post'\n id = IntType(required=False)\n title = StringType(required=True)\n photos = StringType(required=False, default='')\n text = StringType(required=False, default=None)\n likes = IntType(required=True, default=0)\n user = ModelType(UserModel, required=True)\n\n\n#Создаем модель комментариев\nclass CommentsModel(Model):\n _name = 'comment'\n id = IntType(required=False)\n text = StringType(required=False, default=None)\n likes = IntType(required=True, default=0)\n user = ModelType(UserModel, required=True)\n post = ModelType(PostModel, required=True)\n\n#Создаем модель сообщений\nclass MessageModel(Model):\n id = IntType(required=False)\n user_from = ModelType(UserModel, required=True)\n user_to = ModelType(UserModel, required=True)\n is_read = BooleanType(required=True, default=False)\n\n\nif __name__ == '__main__':\n pass","repo_name":"SkinFish/SN-Project","sub_path":"models/file.py","file_name":"file.py","file_ext":"py","file_size_in_byte":3225,"program_lang":"python","lang":"ru","doc_type":"code","stars":0,"dataset":"github-code","pt":"15"} +{"seq_id":"7880201873","text":"import NodeClient\r\nimport time\r\n\r\nclient1 = NodeClient.NodeClient(\"Client1\", \"127.0.0.1\", 5000)\r\nclient1.start()\r\n\r\ntime.sleep(2)\r\nprint(\"\\nHello! This is Music Streaming service\")\r\nwhile True:\r\n time.sleep(2)\r\n userinput = input(\r\n \"Enter [/auth] to authenticate your client \\n\"\r\n \"Enter [/list] to get list of songs \\n\"\r\n \"Enter specific file name in [filename.wav] manner to play a song\\n\")\r\n client1.postMessage(userinput)","repo_name":"Kanciachu/Distributed-system","sub_path":"Client.py","file_name":"Client.py","file_ext":"py","file_size_in_byte":470,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"15"} +{"seq_id":"71205092492","text":"def convert_time(t):\n time_spent = (t).seconds\n h = (time_spent - time_spent % 3600) // 3600\n m = (time_spent - time_spent % 60 - h*3600) // 60\n s = (time_spent - h*3600 - m*60)\n\n return f\"{str(h).zfill(2)}:{str(m).zfill(2)}:{str(s).zfill(2)}\"\n \n\ndef generate_description(update2, changes):\n description = \"\"\n for k, v1 in changes.items():\n v2 = update2[k]\n description += f\"The `{k}` changed from `{v1}` to `{v2}`, \"\n description = description[:-2]+\".\"\n return description\n\n\n \n\n\ndef send_webhook(embed, url, data, time_elapsed, changes=None):\n from discord_webhook import DiscordWebhook, DiscordEmbed\n webhook = DiscordWebhook(url=url)\n if embed.description == \"\" and changes:\n embed.description = generate_description(data, changes)\n for k, v in data.items():\n if (k in changes) if changes else False:\n embed.add_embed_field(name=\"Previous \"+k, value=f\"`{changes[k]}`\", inline=True)\n embed.add_embed_field(name=k, value=f\"`{v}`\", inline=(True if k in changes else False) if changes else False)\n embed.add_embed_field(name=\"\", value=\"\", inline=False)\n\n if changes:\n embed.add_embed_field(name=\"Time Elapsed\", value=f\"`{convert_time(time_elapsed)}`\", inline=True)\n embed.set_footer(text=\"Programmed by BBernYY on GitHub.\", icon_url=\"https://avatars.githubusercontent.com/u/66414852?s=48&v=4\")\n webhook.add_embed(embed)\n response = webhook.execute()\n\ndef removed_key(dictionary, key):\n out = dict(dictionary)\n out.pop(key)\n return out\n\n\n\ndef check_for_updates(interval_seconds, url, show_changes):\n def decorator(func):\n import time\n from datetime import datetime\n update1 = func()\n time1 = datetime.now()\n while True:\n update2 = func()\n changes = {}\n for k, v1 in update1.items():\n if k == \"%/info/%\":\n continue\n v2 = update2[k]\n if v1 != v2:\n changes[k] = v1\n if changes != {}:\n time2 = datetime.now()\n send_webhook(url=url, data=removed_key(update2, \"%/info/%\"), time_elapsed=time2-time1, changes=changes if show_changes else None, **update2[\"%/info/%\"])\n time1 = datetime.now()\n\n update1 = dict(update2) # this is so the values dont tangle\n time.sleep(interval_seconds)\n return decorator\n\ndef main(): # OUTDATED! USE HYPIXEL.PY !!!\n import random\n @check_for_updates(1, \"Update!\", \"https://discord.com/api/webhooks/1066438058376974396/qSoY0VHorM1-bkFbZrOZIdGKIh7h7XobKE21dwqejV2dgNlR2OL0G5o_KRGLmpTrU77z\", True)\n def func():\n r1, r2 = random.random(), random.random()\n return({\"test1\": 1 if r1 > 0.5 else 0, \"test2\": 0 if r2 > 0.5 else 1})\n # return({\"test1\": 1, \"test2\": 0})\n \n\nif __name__ == \"__main__\":\n main()","repo_name":"BBernYY/HyTracker2","sub_path":"main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":2913,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"15"} +{"seq_id":"4317735344","text":"# import os\n# import random\n#\n#\n# def read_all_interacts(filename, interact_lst): # read interactions from a file\n# interaction_file = open(filename)\n# line = interaction_file.readline() # read lines from original interaction file\n# while line:\n# db_id1, db_id2, interact_level = line[0:-1].split('\\t') # get two drugs' ids and interaction level\n# interact_lst.append((db_id1, db_id2, interact_level)) # create a list of tuples (id1, id2, interaction)\n# line = interaction_file.readline() # read next line\n# interaction_file.close()\n# return interact_lst\n#\n# def two_folds():\n# interact_lst = []\n# for i in range(1, 11):\n# filename = 'data/all/' + str(i) + '/interacts.csv'\n# lst = read_all_interacts(filename, interact_lst)\n# random.shuffle(lst)\n# samples_each_fold = 49455 # number of samples in each fold:9891*10 = 98910 = 315*314\n# interact_lists = [] # a list of 10 interaction lists\n# for i in range(0, 2): # 10 folds\n# fold = lst[i * samples_each_fold:samples_each_fold * (i + 1)] # interactions in each fold\n# interact_lists.append(fold)\n#\n# # write to dataset\n# j = 33\n# for i in range(1, 3):\n# interact_list = interact_lists[i - 1] # interaction list of fold i\n# path = 'data/all_dataset' + str(j) + '/all/' + str(i) # path: data/all_datasetj/all/(1~10)\n# if not os.path.exists(path):\n# os.makedirs(path)\n#\n# pos = [] # list of positive interactions\n# neg = [] # list of negative interactions\n# all = [] # list of all interactions\n# ids = [] # list of ids\n# # read all interacts\n# for item in interact_list:\n# line = item[0] + '\\t' + item[1] + '\\t' + str(item[2]) + '\\n' # create line to write in interaction file\n# if item[2] == '1': # positive interactions\n# pos.append(line)\n# all.append(line)\n# line = item[0] + '\\t' + item[1] + '\\n' # create line to write in ids file\n# ids.append(line)\n# elif item[2] == '0': # negative interactions\n# neg.append(line)\n# all.append(line)\n# line = item[0] + '\\t' + item[1] + '\\n'\n# ids.append(line)\n#\n# filename = path + '/interacts.csv' # file of all interactions\n# with open(filename, 'w') as f:\n# f.writelines(all)\n# filename = path + '/interacts_negatives.csv' # file of negative interactions\n# with open(filename, 'w') as f:\n# f.writelines(neg)\n# filename = path + '/interacts_positives.csv' # file of positive interactions\n# with open(filename, 'w') as f:\n# f.writelines(pos)\n# filename = path + '/interactsids.csv' # file of ids\n# with open(filename, 'w') as f:\n# f.writelines(ids)\n#\n# def exchange():\n# # 读取两个文件夹,从中间切开交换\n# f1 = 'data/all_dataset33/all/1/interacts.csv'\n# f2 = 'data/all_dataset33/all/2/interacts.csv'\n# interacts_1 = []\n# interacts_1 = read_all_interacts(f1, interacts_1)\n# interacts_2 = []\n# interacts_2 = read_all_interacts(f2, interacts_2)\n# new_1 = interacts_1[0:24727]\n# new_1.extend(interacts_2[24727:49455])\n# new_2 = interacts_2[0:24727]\n# new_2.extend(interacts_1[24727:49455])\n#\n# interact_lists = []\n# interact_lists.append(new_1)\n# interact_lists.append(new_2)\n# # write to dataset\n# j = 34\n# for i in range(1, 3):\n# interact_list = interact_lists[i - 1] # interaction list of fold i\n# path = 'data/all_dataset' + str(j) + '/all/' + str(i) # path: data/all_datasetj/all/(1~10)\n# if not os.path.exists(path):\n# os.makedirs(path)\n#\n# pos = [] # list of positive interactions\n# neg = [] # list of negative interactions\n# all = [] # list of all interactions\n# ids = [] # list of ids\n# # read all interacts\n# for item in interact_list:\n# line = item[0] + '\\t' + item[1] + '\\t' + str(item[2]) + '\\n' # create line to write in interaction file\n# if item[2] == '1': # positive interactions\n# pos.append(line)\n# all.append(line)\n# line = item[0] + '\\t' + item[1] + '\\n' # create line to write in ids file\n# ids.append(line)\n# elif item[2] == '0': # negative interactions\n# neg.append(line)\n# all.append(line)\n# line = item[0] + '\\t' + item[1] + '\\n'\n# ids.append(line)\n#\n# filename = path + '/interacts.csv' # file of all interactions\n# with open(filename, 'w') as f:\n# f.writelines(all)\n# filename = path + '/interacts_negatives.csv' # file of negative interactions\n# with open(filename, 'w') as f:\n# f.writelines(neg)\n# filename = path + '/interacts_positives.csv' # file of positive interactions\n# with open(filename, 'w') as f:\n# f.writelines(pos)\n# filename = path + '/interactsids.csv' # file of ids\n# with open(filename, 'w') as f:\n# f.writelines(ids)\n# # Generate folds\n# interact_lst = []\n# for i in range(1, 11): # from original dataset data/all/(1~10)/interacts.csv read all interaction data\n# filename = 'data/all/' + str(i) + '/interacts.csv'\n# lst = read_all_interacts(filename, interact_lst)\n#\n#\n#\n#\n# # shuffle the list\n# # If this line is commented out, the order of interactions will be same as the original dataset\n# # If keep this line, the result will be wrong\n# random.shuffle(lst)\n#\n# # divide list\n# samples_each_fold = 9891 # number of samples in each fold:9891*10 = 98910 = 315*314\n# interact_lists = [] # a list of 10 interaction lists\n# for i in range(0, 10): # 10 folds\n# fold = lst[i*samples_each_fold:samples_each_fold*(i+1)] # interactions in each fold\n# interact_lists.append(fold)\n#\n# # write to dataset\n# j = 3\n# for i in range(1, 11):\n# interact_list = interact_lists[i - 1] # interaction list of fold i\n# path = 'data/all_dataset'+ str(j) +'/all/' + str(i) # path: data/all_datasetj/all/(1~10)\n# if not os.path.exists(path):\n# os.makedirs(path)\n#\n# pos = [] # list of positive interactions\n# neg = [] # list of negative interactions\n# all = [] # list of all interactions\n# ids = [] # list of ids\n# # read all interacts\n# for item in interact_list:\n# line = item[0] + '\\t' + item[1] + '\\t' + str(item[2]) + '\\n' # create line to write in interaction file\n# if item[2] == '1': # positive interactions\n# pos.append(line)\n# all.append(line)\n# line = item[0] + '\\t' + item[1] + '\\n' # create line to write in ids file\n# ids.append(line)\n# elif item[2] == '0': # negative interactions\n# neg.append(line)\n# all.append(line)\n# line = item[0] + '\\t' + item[1] + '\\n'\n# ids.append(line)\n#\n# filename = path + '/interacts.csv' # file of all interactions\n# with open(filename, 'w') as f:\n# f.writelines(all)\n# filename = path + '/interacts_negatives.csv' # file of negative interactions\n# with open(filename, 'w') as f:\n# f.writelines(neg)\n# filename = path + '/interacts_positives.csv' # file of positive interactions\n# with open(filename, 'w') as f:\n# f.writelines(pos)\n# filename = path + '/interactsids.csv' # file of ids\n# with open(filename, 'w') as f:\n# f.writelines(ids)\n\n\n# end\n\nimport os\nimport sys\nimport itertools as it\nimport pandas as pd\nimport numpy as np\nimport csv\n\n\n\ndef create(dataset_name):\n\t#Change this line accordingly based on where you place this script\n\tdata_dir = os.path.join('data', 'all')\n\n\tinteractions = pd.DataFrame()\n\n\tfor i in range(1, 11):\n\t\tinteracts_file = os.path.join(data_dir, str(i), 'interacts.csv')\n\n\t\tinteracts = set()\n\t\twith open(interacts_file, 'r') as f:\n\t\t\treader = csv.reader(f, delimiter='\\t')\n\t\t\tfor row in reader:\n\t\t\t\tif (row[1], row[0], row[2]) not in interacts:\n\t\t\t\t\tinteracts.add(tuple(row))\n\n\t\tinteracts = [list(t) for t in interacts]\n\t\tints_df = pd.DataFrame(interacts, columns=['d1', 'd2', 'val'])\n\t\tints_df['fold'] = i\n\t\tinteractions = pd.concat([interactions, ints_df])\n\n\tinteractions['fold'] = np.random.permutation(interactions.fold)\n\n\n\tfor i in range(1, 11):\n\t\tout = os.path.join(data_dir, '..', '..', dataset_name, 'all', str(i))\n\n\t\tif not os.path.exists(out):\n\t\t\tos.makedirs(out)\n\n\t\tvalid_interacts = interactions.loc[interactions.fold == i, ['d1', 'd2', 'val']]\n\t\tsymmetric = valid_interacts[['d2', 'd1', 'val']]\n\t\tsymmetric = symmetric.rename(columns={'d2':'d1', 'd1':'d2'})\n\n\t\tints = pd.concat([valid_interacts, symmetric])\n\t\tids = ints[['d1', 'd2']]\n\n\t\tints.to_csv(os.path.join(out, 'interacts.csv'), sep='\\t', header=False, index=False)\n\t\tids.to_csv(os.path.join(out, 'interactsids.csv'), sep='\\t', header=False, index=False)\n\n\nfor i in range(1,31):\n\tdataset_name = 'all_dataset' + str(i)\n\tcreate(dataset_name)\n","repo_name":"HaoboGu/Structure-Similarity","sub_path":"CreateFolds.py","file_name":"CreateFolds.py","file_ext":"py","file_size_in_byte":9216,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"15"} +{"seq_id":"28397076571","text":"import math \n\ndef solution(n):\n answer = 0\n primes = [True] * (n + 1) \n primes[1] = False\n \n \n for i in range(2, int(math.sqrt(n)) + 1):\n k = 2\n while i * k <= n:\n primes[i * k] = False\n k += 1\n \n for i in range(1, n + 1):\n if primes[i]:\n answer += 1\n \n return answer","repo_name":"ZeroMin-K/Algorithm-Study","sub_path":"프로그래머스/Level 1/소수찾기-review.py","file_name":"소수찾기-review.py","file_ext":"py","file_size_in_byte":355,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"15"} +{"seq_id":"23334106612","text":"def process():\n\t'''\n\tprocesses_POI.txt and return a list of dicts containing the points lat, long and discription\n\tpoi_list = [{'lat': lat#, 'lon': lon#, 'disc': 'text'}, {...}, ...]\n\t'''\n\tpoi_list = []\n\t\n\twith open('POI_trailheads.txt', 'r') as f:\n\t\tread_data = f.readlines()\n\t\n\tfor line in read_data:\n\t\tparts = line.split(\",\")\n\t\tpoint_data = {\"lat\": float(parts[1].strip()), \"lon\": float(parts[2].strip()), \"disc\": parts[0].strip()}\n\t\tpoi_list.append(point_data)\n\t\t\n\treturn poi_list","repo_name":"brianLeeson/CIS322-proj5-leaflet-map","sub_path":"process_POI.py","file_name":"process_POI.py","file_ext":"py","file_size_in_byte":484,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"15"} +{"seq_id":"71212696333","text":"__copyright__ = ('Copyright Amazon.com, Inc. or its affiliates. '\n 'All Rights Reserved.')\n__version__ = '2.10.2a'\n__license__ = 'MIT-0'\n__author__ = 'Akihiro Nakajima'\n__url__ = 'https://github.com/aws-samples/siem-on-amazon-opensearch-service'\n\nfrom siem import utils\n\n\ndef convert_text_into_dict(temp_value):\n if isinstance(temp_value, dict):\n return temp_value\n elif isinstance(temp_value, str):\n return {'value': temp_value}\n elif isinstance(temp_value, list):\n if len(temp_value) == 0:\n return {}\n elif isinstance(temp_value[0], str):\n return {'value': temp_value}\n elif isinstance(temp_value[0], dict):\n return temp_value\n return {'value': repr(temp_value)}\n\n\ndef extract_instance_id(logdata):\n event_source = logdata.get('eventSource', '')\n event_name = logdata.get('eventName', '')\n instance_id = None\n if event_source == 'ssm.amazonaws.com':\n if event_name in ('StartSession', 'GetConnectionStatus'):\n if logdata.get('requestParameters'):\n instance_id = logdata.get(\n 'requestParameters', {}).get('target')\n elif event_name in ('PutComplianceItems'):\n if logdata.get('requestParameters'):\n instance_id = logdata.get(\n 'requestParameters', {}).get('resourceId', '')\n m = utils.RE_INSTANCEID.match(instance_id)\n if not m:\n instance_id = ''\n elif event_source in ('sts.amazonaws.com'):\n if logdata.get('userAgent') == 'ec2.amazonaws.com':\n instance_id = logdata.get(\n 'requestParameters', {}).get('roleSessionName')\n\n elif event_source in ('cloudhsm.amazonaws.com'):\n logdata['related'] = {'hosts': []}\n try:\n cluster_id = logdata.get('requestParameters', {}).get('clusterId')\n except Exception:\n cluster_id = None\n if cluster_id:\n logdata['related']['hosts'].append(cluster_id)\n try:\n hsm_id = logdata['responseElements']['hsmId']\n except Exception:\n try:\n hsm_id = logdata['responseElements']['hsm']['hsmId']\n except Exception:\n hsm_id = None\n if hsm_id:\n logdata['cloud']['instance'] = {'id': hsm_id}\n logdata['related']['hosts'].append(hsm_id)\n\n if instance_id:\n logdata['cloud']['instance'] = {'id': instance_id}\n return logdata\n\n\ndef transform(logdata):\n if 'errorCode' in logdata or 'errorMessage' in logdata:\n logdata['event']['outcome'] = 'failure'\n else:\n logdata['event']['outcome'] = 'success'\n try:\n name = logdata['user']['name']\n if ':' in name:\n logdata['user']['name'] = name.split(':')[-1].split('/')[-1]\n except KeyError:\n pass\n logdata = extract_instance_id(logdata)\n\n # https://github.com/aws-samples/siem-on-amazon-elasticsearch/issues/33\n try:\n response_cred = logdata['responseElements']['credentials']\n except (KeyError, TypeError):\n response_cred = None\n if isinstance(response_cred, str):\n logdata['responseElements']['credentials'] = {}\n if 'arn:aws:iam' in response_cred:\n logdata['responseElements']['credentials']['iam'] = response_cred\n elif 'arn:aws-cn:iam' in response_cred:\n logdata['responseElements']['credentials']['iam'] = response_cred\n elif 'arn:aws-us-gov:iam' in response_cred:\n logdata['responseElements']['credentials']['iam'] = response_cred\n else:\n logdata['responseElements']['credentials']['value'] = response_cred\n\n # https://github.com/aws-samples/siem-on-amazon-elasticsearch/issues/108\n try:\n logdata['requestParameters']['tags'] = convert_text_into_dict(\n logdata['requestParameters']['tags'])\n except (KeyError, TypeError):\n pass\n\n # https://github.com/aws-samples/siem-on-amazon-elasticsearch/issues/114\n try:\n logdata['responseElements']['policy'] = convert_text_into_dict(\n logdata['responseElements']['policy'])\n except (KeyError, TypeError):\n pass\n\n # https://github.com/aws-samples/siem-on-amazon-elasticsearch/issues/139\n try:\n logdata['requestParameters']['disableApiTermination'] = (\n logdata['requestParameters']['disableApiTermination']['value'])\n except (KeyError, TypeError):\n pass\n\n # https://github.com/aws-samples/siem-on-amazon-opensearch-service/issues/299\n try:\n logdata['requestParameters']['disableApiStop'] = (\n logdata['requestParameters']['disableApiStop']['value'])\n except (KeyError, TypeError):\n pass\n\n # https://github.com/aws-samples/siem-on-amazon-elasticsearch/issues/242\n try:\n status = logdata['responseElements']['status']\n except (KeyError, TypeError):\n status = None\n if status and isinstance(status, str):\n logdata['responseElements']['status'] = {'status': status}\n\n event_source = logdata.get('eventSource', None)\n if not event_source:\n pass\n elif event_source == 'athena.amazonaws.com':\n # #153\n try:\n tableMetadataList = (\n logdata['responseElements']['tableMetadataList'])\n except (KeyError, TypeError):\n tableMetadataList = None\n if tableMetadataList:\n for tableMetadata in tableMetadataList:\n old_field = 'projection.date.interval.unit'\n new_field = 'projection.date.interval_unit'\n try:\n tableMetadata['parameters'][new_field] = (\n tableMetadata['parameters'].pop(old_field))\n except KeyError:\n pass\n try:\n partableMetadata = (\n logdata['responseElements']['tableMetadata'])\n except (KeyError, TypeError):\n partableMetadata = None\n if partableMetadata:\n old_field = 'projection.part_date.interval.unit'\n new_field = 'projection.part_date.interval_unit'\n try:\n partableMetadata['parameters'][new_field] = (\n partableMetadata['parameters'].pop(old_field))\n except KeyError:\n pass\n\n elif event_source == 'glue.amazonaws.com':\n # #156, #166\n try:\n configuration = logdata['requestParameters']['configuration']\n except (KeyError, TypeError):\n configuration = None\n if configuration and isinstance(configuration, str):\n logdata['requestParameters']['configuration'] = {\n 'text': configuration}\n elif event_source == 'cognito-idp.amazonaws.com':\n # #163\n try:\n session = logdata['responseElements']['session']\n except (KeyError, TypeError):\n session = None\n if session and isinstance(session, str):\n logdata['responseElements']['session'] = {'value': session}\n elif event_source == 'ecs.amazonaws.com':\n # #167\n try:\n command = logdata['requestParameters']['command']\n except (KeyError, TypeError):\n command = None\n if command and isinstance(command, str):\n logdata['requestParameters']['command'] = {'command': command}\n elif event_source in ('ssm.amazonaws.com', 'sqlworkbench.amazonaws.com'):\n try:\n params = logdata['requestParameters']['parameters']\n except (KeyError, TypeError):\n params = None\n if params and isinstance(params, str):\n logdata['requestParameters']['parameters'] = {'value': params}\n elif event_source in ('redshift-data.amazonaws.com'):\n try:\n db = logdata['responseElements']['database']\n except (KeyError, TypeError):\n db = None\n if db and isinstance(db, str):\n logdata['responseElements']['database'] = {'name': db}\n elif event_source in ('cloud9.amazonaws.com'):\n try:\n settings = logdata['requestParameters']['settings']\n except (KeyError, TypeError):\n settings = None\n if settings and isinstance(settings, str):\n logdata['requestParameters']['settings'] = {'value': settings}\n elif event_source in ('s3.amazonaws.com'):\n try:\n rules = (logdata['requestParameters']['ReplicationConfiguration']\n ['Rule'])\n except (KeyError, TypeError):\n rules = None\n if rules and isinstance(rules, list):\n for i, rule in enumerate(rules):\n if rule.get('Filter'):\n rules[i]['Filter'] = str(rule['Filter'])\n elif event_source in ('inspector2.amazonaws.com'):\n try:\n ids = logdata['requestParameters']['accountIds']\n except (KeyError, TypeError):\n ids = None\n if ids and isinstance(ids, list) and isinstance(ids[0], dict):\n logdata['requestParameters']['accountIds'] = str(ids)\n elif event_source in ('codeguru-security.amazonaws.com'):\n if logdata['requestParameters'].get('resourceId'):\n logdata['requestParameters']['resourceId'] = repr(\n logdata['requestParameters']['resourceId'])\n elif event_source in ('dynamodb.amazonaws.com'):\n try:\n logdata['requestParameters']['items'] = convert_text_into_dict(\n logdata['requestParameters']['items'])\n except (KeyError, TypeError):\n pass\n\n return logdata\n","repo_name":"aws-samples/siem-on-amazon-opensearch-service","sub_path":"source/lambda/es_loader/siem/sf_cloudtrail.py","file_name":"sf_cloudtrail.py","file_ext":"py","file_size_in_byte":9628,"program_lang":"python","lang":"en","doc_type":"code","stars":487,"dataset":"github-code","pt":"15"} +{"seq_id":"32801400209","text":"#! /usr/bin/env python\n# -*- coding: UTF-8 -*-\n\nimport sys\nsys.path.append(\"prog_utils/\")\n\nimport pygame\nif not pygame.font:\n print(\"Fehler pygame.font Modul konnte nicht geladen werden!\")\nif not pygame.mixer:\n print(\"Fehler pygame.mixer Modul konnte nicht geladen werden!\")\n\nimport load_files\nimport display\nimport world\n\n\ndef mainloop():\n main_config = load_files.Config(\"config.cfg\")\n graphics = main_config.read_section(\"Graphics\")\n a = load_files.Resources()\n\n pygame.init()\n dimensions = (int(graphics[\"screen_width\"]), int(graphics[\"screen_height\"]))\n screen = pygame.display.set_mode(dimensions)\n\n pygame.display.set_caption(\"BloX - L²K\")\n pygame.mouse.set_visible(1)\n pygame.key.set_repeat(1, 30)\n\n clock = pygame.time.Clock()\n\n running = True\n overworld = world.World()\n overworld.get_chunk((0, 0, 1))\n\n win = display.Window(screen)\n pos = [-50.0, -200.0, 16.0]\n speed = 2\n while running:\n clock.tick(60)\n\n screen.fill((0, 0, 0))\n for event in pygame.event.get():\n if event.type == pygame.QUIT:\n running = False\n\n if event.type == pygame.KEYDOWN:\n if event.key == pygame.K_ESCAPE:\n pygame.event.post(pygame.event.Event(pygame.QUIT))\n elif event.key == pygame.K_a:\n pos[0] -= speed\n elif event.key == pygame.K_d:\n pos[0] += speed\n elif event.key == pygame.K_w:\n pos[1] -= speed\n elif event.key == pygame.K_s:\n pos[1] += speed\n elif event.key == pygame.K_q:\n pos[2] -= 1\n elif event.key == pygame.K_e:\n pos[2] += 1\n\n# dirt = dirt_tile.load_tile()\n win.draw_screen(screen, pos, 64, overworld.get_chunk((0, 0, 0)), 0.25)\n pygame.display.flip()\n\nif __name__ == \"__main__\":\n mainloop()","repo_name":"GNARFcorp/l2k","sub_path":"main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":1967,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"15"} +{"seq_id":"4501575230","text":"#!/usr/bin/python\n# -*- coding: utf-8 -*-\n#\n# Licensed under the GNU General Public License, version 3.\n# See the file http://www.gnu.org/licenses/gpl.txt\n\nfrom pisi.actionsapi import shelltools\nfrom pisi.actionsapi import mesontools\nfrom pisi.actionsapi import pisitools\nfrom pisi.actionsapi import get\n\ndef setup():\n shelltools.export(\"AUTOPOINT\", \"true\")\n options = \"-Dpackage-name='GStreamer for PisiLinux' \\\n -Dpackage-origin='https://www.pisilinux.org' \\\n -Dptp-helper-permissions=capabilities \\\n -Ddbghelp=disabled \\\n \"\n if get.buildTYPE() == \"emul32\":\n shelltools.export(\"CC\", \"%s -m32\" % get.CC())\n shelltools.export(\"CXX\", \"%s -m32\" % get.CXX())\n shelltools.export(\"PKG_CONFIG_PATH\", \"/usr/lib32/pkgconfig\")\n \n options += \" --bindir=/usr/bin32 \\\n --libdir=/usr/lib32 \\\n --libexecdir=/usr/libexec32 \\\n -Dexamples=disabled \\\n -Dintrospection=disabled \\\n \"\n \n mesontools.configure(options)\n\ndef build():\n mesontools.build()\n \ndef install():\n mesontools.install()\n \n if get.buildTYPE() == \"emul32\":\n pisitools.removeDir(\"/usr/bin32\")\n pisitools.removeDir(\"/usr/libexec32\")\n return\n\n pisitools.dodoc(\"AUTHORS\", \"ChangeLog\", \"COPYING*\", \"NEWS\", \"README*\")\n","repo_name":"pisilinux/main","sub_path":"multimedia/video/gstreamer/actions.py","file_name":"actions.py","file_ext":"py","file_size_in_byte":1402,"program_lang":"python","lang":"en","doc_type":"code","stars":62,"dataset":"github-code","pt":"15"} +{"seq_id":"24599296811","text":"import networkx as nx\n\nwith open('input') as f:\n inp = [x.strip() for x in f.readlines()]\n\ngrid = {}\nfor j, y in enumerate(inp):\n for i, x in enumerate(y):\n grid[complex(i, j)] = x\n\ndef update_grid(g):\n new_g = {}\n for p in g:\n bugs = 0\n for d in [1, -1, 1j, -1j]:\n try:\n bugs += int(g[p+d] == '#')\n except KeyError:\n pass\n if g[p] == '#' and bugs != 1:\n new_g[p] = '.'\n elif g[p] == '.' and bugs in [1,2]:\n new_g[p] = '#'\n else:\n new_g[p] = g[p]\n \n return new_g\n\ndef bio_rating(g):\n points = 0\n count = 0\n for j in range(5):\n for i in range(5):\n if g[complex(i, j)] == '#':\n points += 2**count\n count += 1\n return points\n \n# Part 1\ngrid_cp = dict(grid)\ngrids = [grid_cp]\n\nwhile True:\n grid_cp = update_grid(grid_cp)\n if grid_cp in grids:\n break\n grids.append(grid_cp) \n\nprint(bio_rating(grid_cp))\n \n# Part 2\ndef get_neighbors(p):\n layer = p[0]\n tile = p[1]\n neighs = []\n # Same-layer neighbors\n for d in [1, -1, 1j, -1j]:\n if 0<=(tile+d).imag<=4 and 0<=(tile+d).real<=4 and tile+d != 2+2j:\n neighs.append((layer, tile+d))\n # Outer neighbors\n if tile.imag == 0:\n neighs.append((layer-1, 2+1j))\n if tile.imag == 4:\n neighs.append((layer-1, 2+3j))\n if tile.real == 0:\n neighs.append((layer-1, 1+2j))\n if tile.real == 4:\n neighs.append((layer-1, 3+2j)) \n # Inner neighbors\n if tile == 2+1j:\n for i in range(5):\n neighs.append((layer+1, i))\n if tile == 2+3j:\n for i in range(5):\n neighs.append((layer+1, i+4j))\n if tile == 1+2j:\n for i in range(5):\n neighs.append((layer+1, complex(0, i)))\n if tile == 3+2j:\n for i in range(5):\n neighs.append((layer+1, complex(4, i)))\n return neighs\n\ndef create_graph(l):\n g = nx.Graph()\n for i in range(5):\n for j in range(5):\n tile = complex(i, j)\n if l == 0:\n bug = (grid[tile] == '#')\n else:\n bug = False\n if i != 2 or j != 2:\n g.add_node((l, tile), bug = bug)\n for d in [1, -1, 1j, -1j]:\n if 0<=(tile+d).imag<=4 and 0<=(tile+d).real<=4 and tile+d != 2+2j:\n g.add_edge((l, tile), (l, tile+d))\n return g\n\ndef update_graph(g):\n g_new = g.copy()\n n_ls = max([p[0] for p in g.nodes()])\n n_ls_w_bugs = max([p[0] for p in g.nodes() if g.nodes[p]['bug']])\n if n_ls_w_bugs == n_ls:\n g_new = nx.compose(g_new, create_graph(n_ls+1))\n g_new = nx.compose(g_new, create_graph(-n_ls-1)) \n n_ls = max([p[0] for p in g_new.nodes()])\n for p in g.nodes():\n for n in [x for x in get_neighbors(p) if abs(x[0]) <= n_ls]:\n g_new.add_edge(p, n)\n g_new_cp = g_new.copy()\n for p in g_new_cp.nodes():\n bugs = sum([g_new_cp.nodes[n]['bug'] for n in g_new_cp.neighbors(p)])\n if p not in g.nodes():\n g_new.nodes[p]['bug'] = bugs in [1, 2]\n else:\n if g.nodes[p]['bug'] and bugs != 1:\n g_new.nodes[p]['bug'] = False\n elif not g.nodes[p]['bug'] and bugs in [1,2]:\n g_new.nodes[p]['bug'] = True\n else:\n g_new.nodes[p]['bug'] = g.nodes[p]['bug'] \n return g_new\n\ndef print_graph(g):\n dict = {True: '#', False: '.'}\n l_min = min([p[0] for p in g.nodes()])\n l_max = max([p[0] for p in g.nodes()])\n for l in range(l_min, l_max+1):\n print(f'Layer {l}:')\n for j in range(5):\n temp = []\n for i in range(5):\n try:\n temp.append(dict[g.nodes[(l, complex(i, j))]['bug']])\n except KeyError:\n temp.append(' ')\n print(''.join(temp))\n\ng = create_graph(0)\nfor i in range(200):\n g = update_graph(g)\n\nprint(sum(nx.get_node_attributes(g, 'bug').values()))","repo_name":"snhansen/adventofcode","sub_path":"2019/day24/solution.py","file_name":"solution.py","file_ext":"py","file_size_in_byte":4107,"program_lang":"python","lang":"en","doc_type":"code","stars":2,"dataset":"github-code","pt":"15"} +{"seq_id":"38456955648","text":"import csv\n\n\nwith open('posts.csv', 'r') as readFile:\n\treader = csv.reader(readFile)\n\tlines = list(reader)\n\ntext = \"\"\n\nfor l in lines:\n\ttext += l[1]\n\ttext += \" \\n\"\n\nf = open(\"all_text.txt\", \"a\")\nf.write(text)\nf.close()\n\n","repo_name":"IDIAS-Tufts/IDIAS","sub_path":"reparse.py","file_name":"reparse.py","file_ext":"py","file_size_in_byte":220,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"15"} +{"seq_id":"31741515811","text":"# -*- coding: utf-8 -*-\n\"\"\"\nCreated on Tue Jul 18 14:05:14 2023\n\n@author: Takeshi\n\"\"\"\n\nimport pandas as pd\nfrom sklearn.ensemble import RandomForestClassifier\ndef main(train_data_name = \"animal_combos_train.csv\",test_data_name = 'animal_combos_test.csv'):\n #input data\n train_data=pd.read_csv(train_data_name)\n test_data=pd.read_csv(test_data_name)\n \n #split data\n train_y=train_data.iloc[:,-1]\n train_x=train_data.iloc[:,1:-1] \n test_x=test_data.iloc[:,1:] \n \n \n # ランダムフォレストモデルを作成する create RF\n rf = RandomForestClassifier(n_estimators=100, random_state=42)\n \n # モデルをトレーニングする training model\n rf.fit(train_x, train_y)\n \n # テストセットを予測する predicted test set\n y_pred = rf.predict(test_x)\n y_pred_prob = rf.predict_proba(test_x)\n #print(f'y:{y_pred},y_p:{y_pred_prob[:,1]}')\n return y_pred\n\n# main(train_data_name,test_data_name) ;if file change, train_data_name = 'file_name'\nmain()","repo_name":"jesicabauer/gRIPS-Fujitsu-2023","sub_path":"flask-server/random_forest_tks.py","file_name":"random_forest_tks.py","file_ext":"py","file_size_in_byte":1019,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"15"} +{"seq_id":"8340751296","text":"words = [];\nmy_list = [];\n\nwhile True:\n word = input(\"type a word: \");\n if word == '':\n break;\n else:\n words.append(word);\n\nfor word in words:\n my_list.append(list(set(word)))\n\nfor item in my_list:\n print(item)\n","repo_name":"pachecosamuel/Python-Course-Fundamentals","sub_path":"1 - fundamentals/aula045Challenge.py","file_name":"aula045Challenge.py","file_ext":"py","file_size_in_byte":240,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"15"} +{"seq_id":"13323123659","text":"import json\nimport os\n\nfrom typing import Dict\nfrom application.configuration.models.network_configuration_enum import NetworkConfigurationEnum\nfrom object_detection.utils.config_util import get_configs_from_pipeline_file\nfrom application.paths.services.path_service import PathService\nfrom domain.exceptions.configuration_exception import ConfigurationPipelineNotFound\nfrom domain.models.network_information import NetworkInformation\nfrom domain.models.paths import Paths\nfrom domain.services.contract.abstract_configuration_service import AbstractConfigurationService\nfrom shared.helpers.object_classes_from_json import get_labels_from_json_file\nfrom domain.exceptions.configuration_exception import DefaultConfigurationFileNotFound\n\n\nclass ConfigurationService(AbstractConfigurationService):\n \"\"\"\n A class used to return configuration\n\n ...\n\n Attributes\n ----------\n network_instances : Dict[str, AbstractConfigureNetworkService]\n dict containing created instance of class AbstractConfigureNetworkService\n network_mappings :Dict[str, AbstractConfigureNetworkService]\n dict used to map between configuration network name and configuration class template\n\n Methods\n -------\n get_configurations( network_info: NetworkInformation) -> str\n take a network name and return str the pipeline.config corresponding to that network name\n\n get_config_file_content( network_info: NetworkInformation) -> Dict[str, str]:\n take network name and return dict containing the configs using TF internal function\n get_default_configuration(network_info: NetworkInformation) -> Dict\n take network name and return the default configuration (batch, num_classes etc.)\n from the default_config.json file\n \"\"\"\n\n def __init__(self, path: PathService):\n self.path: Paths = path.get_paths()\n\n def _get_network_learning_rate_base(self,network_architecture:str)-> float :\n network_path: str = os.path.join(self.path.weights_dir,network_architecture,\"pipeline.config\")\n content :Dict[str, str] = get_configs_from_pipeline_file(network_path)\n return round(content['train_config'].optimizer.momentum_optimizer.learning_rate.cosine_decay_learning_rate.learning_rate_base, 5)\n\n\n def get_configurations(self, network_info: NetworkInformation) -> str:\n try:\n network_path: str = os.path.join(self.path.weights_dir, network_info.network_architecture,\n \"pipeline.config\")\n content: str = open(network_path, \"r\").read()\n return content\n except Exception as e:\n raise ConfigurationPipelineNotFound(additional_message=e.__str__(), pipeline_path=network_path)\n\n def get_config_file_content(self, network_info: NetworkInformation) -> Dict[str, str]:\n try:\n network_path: str = os.path.join(self.path.weights_dir, network_info.network_architecture,\n \"pipeline.config\")\n return get_configs_from_pipeline_file(network_path)\n except Exception as e:\n raise ConfigurationPipelineNotFound(additional_message=e.__str__(), pipeline_path=network_path)\n\n def get_default_configuration(self, network_info: NetworkInformation) -> Dict:\n try:\n with open(self.path.default_configuration_file, 'r') as default_configs:\n json_default_configs = json.load(default_configs)\n\n num_classes = len(get_labels_from_json_file(self.path.object_classes_path))\n json_default_configs['num_classes'] = num_classes\n json_default_configs['learning_rate']= self._get_network_learning_rate_base(network_architecture = network_info.network_architecture)\n if network_info.network_architecture not in [NetworkConfigurationEnum.SSD_RESNET50_V1_FPN_640x640.value, NetworkConfigurationEnum.SSD_MOBILENET_V1_FPN_640x640.value] :\n del json_default_configs['width']\n del json_default_configs['height']\n return json_default_configs\n except Exception as e:\n raise DefaultConfigurationFileNotFound(additional_message=e.__str__(),\n default_configuration_file=self.path.default_configuration_file)\n","repo_name":"BMW-InnovationLab/BMW-TensorFlow-Training-GUI","sub_path":"training_api/application/configuration/services/configuration_service.py","file_name":"configuration_service.py","file_ext":"py","file_size_in_byte":4309,"program_lang":"python","lang":"en","doc_type":"code","stars":953,"dataset":"github-code","pt":"15"} +{"seq_id":"32123651834","text":"import requests\nfrom bs4 import BeautifulSoup\n\ndef get_subdomains(url):\n subdomains = []\n page = requests.get(url)\n soup = BeautifulSoup(page.content, \"html.parser\")\n links = [link.get(\"href\") for link in soup.find_all(\"a\")]\n for link in links:\n if link and link.startswith(\"http\"):\n subdomain = link.split(\"//\")[1].split(\".\")[0]\n if subdomain not in subdomains:\n subdomains.append(subdomain)\n return subdomains\n\nurl = \"https://targetURL_PEPINILLO.com\"\nprint(get_subdomains(url))\n","repo_name":"xesard/phyton_tools","sub_path":"scan_sub_domains.py","file_name":"scan_sub_domains.py","file_ext":"py","file_size_in_byte":542,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"15"} +{"seq_id":"31210655165","text":"from ChessPiece import ChessPiece\nfrom chess_app.ChessEngine.Selecter import Select \n\nclass Horse(ChessPiece):\n\t\n\tdef __init__(self):\n\t\tsuper(Horse, self).__init__()\n\n\t# gets all the possible positions that can moved by the horse\n\tdef movablePlaces(self, x, y):\n\t\tmatrix = self.live_chessboard_matrix\n\t\tplaceIds = []\n\t\tif x >= 0 and x <= 7 and y >= 0 and y <= 7:\n\t\t\tselect1 = Select()\n\t\t\ttopThenRightElement = select1.selectFromParentId(matrix ,self.id_gen(y+2, x-1))\n\t\t\tselect2 = Select()\n\t\t\ttopThenLeftElement = select2.selectFromParentId(matrix ,self.id_gen(y+2, x+1))\n\t\t\tselect3 = Select()\n\t\t\tbottomThenRightElement = select3.selectFromParentId(matrix ,self.id_gen(y-2, x+1))\n\t\t\tselect4 = Select()\n\t\t\tbottomThenLeftElement = select4.selectFromParentId(matrix ,self.id_gen(y-2, x-1))\n\t\t\tselect5 = Select()\n\t\t\trightThenTopElement = select5.selectFromParentId(matrix ,self.id_gen(y+1, x-2))\n\t\t\tselect6 = Select()\n\t\t\trightThenBottomElement = select6.selectFromParentId(matrix ,self.id_gen(y-1, x-2))\n\t\t\tselect7 = Select()\n\t\t\tleftThenTopElement = select7.selectFromParentId(matrix ,self.id_gen(y+1, x+2))\n\t\t\tselect8 = Select()\n\t\t\tleftThenBottomElement = select8.selectFromParentId(matrix ,self.id_gen(y-1, x+2))\n\t\t\t\n\t\t\tif topThenRightElement.parent_id != None and topThenRightElement.parent_id != \"\":\n\t\t\t\tif not self.isType(topThenRightElement.piece_id, \"comp_\"):\n\t\t\t\t\tplaceIds.append(topThenRightElement.parent_id)\t\n\t\t\t\n\t\t\tif topThenLeftElement.parent_id != None and topThenLeftElement.parent_id != \"\": \n\t\t\t\tif not self.isType(topThenLeftElement.piece_id, \"comp_\"):\n\t\t\t\t\tplaceIds.append(topThenLeftElement.parent_id)\t\t\n\t\t\t\n\t\t\tif bottomThenRightElement.parent_id != None and bottomThenRightElement.parent_id != \"\":\n\t\t\t\tif not self.isType(bottomThenRightElement.piece_id, \"comp_\"):\n\t\t\t\t\tplaceIds.append(bottomThenRightElement.parent_id)\n\t\t\t\n\t\t\tif bottomThenLeftElement.parent_id != None and bottomThenLeftElement.parent_id != \"\":\n\t\t\t\tif not self.isType(bottomThenLeftElement.piece_id, \"comp_\"):\n\t\t\t\t\tplaceIds.append(bottomThenLeftElement.parent_id)\n\t\t\t\n\t\t\tif rightThenTopElement.parent_id != None and rightThenTopElement.parent_id != \"\":\n\t\t\t\tif not self.isType(rightThenTopElement.piece_id, \"comp_\"):\n\t\t\t\t\tplaceIds.append(rightThenTopElement.parent_id)\n\t\t\t\n\t\t\tif rightThenBottomElement.parent_id != None and rightThenBottomElement.parent_id != \"\":\n\t\t\t\tif not self.isType(rightThenBottomElement.piece_id, \"comp_\"):\n\t\t\t\t\tplaceIds.append(rightThenBottomElement.parent_id)\n\t\t\t\n\t\t\tif leftThenTopElement.parent_id != None and leftThenTopElement.parent_id != \"\":\n\t\t\t\tif not self.isType(leftThenTopElement.piece_id, \"comp_\"):\n\t\t\t\t\tplaceIds.append(leftThenTopElement.parent_id)\n\t\t\t\n\t\t\tif leftThenBottomElement.parent_id != None and leftThenBottomElement.parent_id != \"\":\n\t\t\t\tif not self.isType(leftThenBottomElement.piece_id, \"comp_\"):\n\t\t\t\t\tplaceIds.append(leftThenBottomElement.parent_id)\n\t\t\t\n\t\t\n\t\treturn placeIds\n\t\n\t# checkes if a position is being attcked by the horse\n\tdef attackingPlaces(self, x, y):\n\t\tmatrix = self.live_chessboard_matrix\n\t\thorseMovablePlaces = self.movablePlaces(x, y)\n\t\tattackingHorsePlaces = []\n\t\t\n\t\tfor i in range(len(horseMovablePlaces)):\n\t\t\tattackingSelect = Select()\n\t\t\tnext_val = attackingSelect.selectFromParentId(matrix, horseMovablePlaces[i])\n\t\t\t\n\t\t\tif next_val!=None:\n\t\t\t\tif next_val.piece_id != 0 or next_val.piece_id != None:\n\t\t\t\t\tif self.isType(next_val.piece_id, \"player_horse\"):\n\t\t\t\t\t\t\tattackingHorsePlaces.append(next_val.parent_id)\n\t\t\t\t\t\t\n\t\t\t\t\t\n\t\treturn attackingHorsePlaces\n\t\n","repo_name":"samjeg/talkingchess5","sub_path":"chess_app/ChessEngine/ChessPieces/Horse.py","file_name":"Horse.py","file_ext":"py","file_size_in_byte":3508,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"15"} +{"seq_id":"36545043528","text":"import turtle\nimport math\nfrom math import pi\np = turtle.Turtle()\np.pensize(5)\n\nclass draw_circle():\n def __init__(self, r, x, y):\n self.r = r\n self.x = x\n self.y = y\n \n def draw(self):\n p.penup()\n p.goto(self.x, self.y)\n p.pendown()\n p.circle(self.r)\n \n def caculate_c(self):\n return (2 * pi * self.r)\n\n def caculate_s(self):\n return (pi * math.pow(self.r, 2))\n\napp = draw_circle(200, -40, -40)\napp.draw()\nprint(f\"Chu vi hinh tron la {round(app.caculate_c(), 2)}\")\nprint(f\"Dien tich hinh tron la {round(app.caculate_s(), 2)}\")\n\nturtle.done()","repo_name":"longdp121/Python_codegym","sub_path":"class, object/Draw_circle.py","file_name":"Draw_circle.py","file_ext":"py","file_size_in_byte":623,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"15"} +{"seq_id":"30450660133","text":"# -*- coding: utf-8 -*-\n\"\"\"\nCreated on Mon Jun 05 10:18:23 2017\n\n@author: lenovo\n\"\"\"\nfrom collections import Counter\nimport numpy as np\nfrom sklearn.ensemble import AdaBoostClassifier\nfrom sklearn.metrics import confusion_matrix\nimport logging\n\nclass Ensemble():\n # In[] n_subset number of subset, version:'easy_ensemble' or 'balance_cascade'\n def __init__(self,version='easy_ensemble',random_seed=None,n_subset=10,n_tree=10):\n self.random_seed = random_seed\n self.version = version\n self.n_subset = n_subset\n self.ensemble = {}\n self.ensemble['adclf'] = []\n self.ensemble['bias'] = []\n self.stats_c = {}\n self.min_c = None\n self.maj_c = None\n self.x_shape = None\n self.logger = logging.getLogger(__name__)\n\n # In[] find the class statistics before sampling\n def fit(self,x,y):\n self.logger.info('compute classes statistics...')\n self.x_shape = x.shape\n self.stats_c = Counter(y)\n self.min_c = min(self.stats_c,key=self.stats_c.get)\n self.maj_c = max(self.stats_c,key=self.stats_c.get)\n self.logger.info('%s classes detected: %s'\n %(len(self.stats_c), ','.join(str(self.stats_c))))\n\n # In[] x,y: subset need to be sampled not all set\n def under_sample(self,x,y,num_samples):\n random_state = np.random.RandomState(self.random_seed)\n sel_id = random_state.choice(range(len(x)),size=num_samples)\n return x[sel_id],y[sel_id]\n\n # In[] tune bias to be false positive\n def bias_tune(self,false_positive,adaclf,x,y):\n estimators = adaclf.estimators_\n weights = adaclf.estimator_weights_\n res = np.zeros_like(y)\n ind = np.where(y==self.maj_c)\n for i,clf in enumerate(estimators):\n res = res+clf.predict(x)*weights[i]\n res = res[ind]\n res = sorted(res,reversed=True)\n bias = res[round(false_positive*len(ind))]\n return bias\n\n # In[]\n def sample(self,x,y):\n self.fit(x,y)\n num_samples = self.stats_c[self.min_c]\n x_min = x[y==self.min_c]\n y_min = y[y==self.min_c]\n x_maj = x[y==self.maj_c]\n y_maj = y[y==self.maj_c]\n x_sample = x_min.copy()\n y_sample = y_min.copy()\n samples = []\n for _ in range(self.n_subset):\n x_under_samp,y_under_sample = self.under_sample(x_maj,y_maj,num_samples)\n x_samp = np.vstack((x_sample,x_under_samp))\n y_samp = np.hstack((y_sample,y_under_sample))\n samples.append((x_samp,y_samp))\n for x_samp,y_samp in samples:\n adaboost_clf = AdaBoostClassifier(base_estimator='DecisionTreeClassifier',\n n_estimators=20)\n adaboost_clf.fit(x_samp,y_samp)\n if self.version == 'easy_ensemble':\n self.ensemble['adclf'].append(adaboost_clf)\n else:\n t = np.power((self.stats_c[self.min_c]*1.0/self.stats_c[self.maj_c]),\n 1.0/(self.n_subset+1))\n adaboost_clf = AdaBoostClassifier(base_estimator='DecisionTreeClassifier',\n n_estimators=20)\n adaboost_clf.fit(x_samp,y_samp)\n bias = self.bias_tune(t,adaboost_clf,x_samp,y_samp)\n self.ensemble['adclf'].append(adaboost_clf)\n self.ensemble['bias'].append(bias)\n return self.ensemble\n","repo_name":"imxtyler/MachineLearning","sub_path":"algorithm/utils/unbalanced/ensemble.py","file_name":"ensemble.py","file_ext":"py","file_size_in_byte":3492,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"15"} +{"seq_id":"34496783280","text":"\r\naluno = dict()\r\n#Ler nome e média\r\naluno['nome'] = str(input('Nome: '))\r\naluno['média'] = float(input(f'média de {aluno[\"nome\"]}: '))\r\n\r\nif aluno['média'] >= 7:\r\n aluno['situação'] = 'Aprovado'\r\nelif 5 <= aluno['média'] < 7:\r\n aluno['situação'] = 'Recuperação'\r\n#restrições\r\nelse:\r\n aluno['situação'] = 'Reprovado'\r\n#Mostre o conteúdo da estrutura de cada aluno\r\nfor k, v in aluno.items():\r\n print(f'{k} é igual a {v}')","repo_name":"joaotogali/Curso-em-video-Python","sub_path":"M3/Dicionários/ex090.py","file_name":"ex090.py","file_ext":"py","file_size_in_byte":450,"program_lang":"python","lang":"pt","doc_type":"code","stars":0,"dataset":"github-code","pt":"15"} +{"seq_id":"45399197453","text":"from unittest import result\r\n\r\n\r\ncList = []\r\ncc = ''\r\ndef factorial(n):\r\n for i in range(1, n+1):\r\n cList.append(i)\r\n return result\r\n\r\n\r\n# Program Start\r\n\r\n\r\nx = 30\r\nprint(\"sum(%d) = %d\" % (x, factorial(x)))\r\nprint(cList)\r\nprint(\"Done By Grace\")","repo_name":"scanteak88/Python_Lab7","sub_path":"Lab7-1.py","file_name":"Lab7-1.py","file_ext":"py","file_size_in_byte":258,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"15"} +{"seq_id":"70127678092","text":"class UnionFind:\n def __init__(self, n):\n self.parent = list(range(n))\n self.rank = [0] * n\n self.color_sets = [set() for _ in range(n)]\n\n def find(self, x):\n if self.parent[x] != x:\n self.parent[x] = self.find(self.parent[x])\n return self.parent[x]\n\n def move(self, x, y):\n root_x = self.find(x)\n root_y = self.find(y)\n\n # If x and y are both roots, make y the new root\n if root_x == x and root_y == y and x != y:\n self.color_sets[root_y].update(self.color_sets[root_x])\n self.color_sets[root_x].clear()\n self.parent[root_x] = root_y\n return\n\n # If x is a root but y is not, make y the new root and move balls\n if root_x == x and root_y != y:\n self.parent[root_x] = root_y\n self.color_sets[root_y].update(self.color_sets[root_x])\n self.color_sets[root_x].clear()\n return\n\n # If x is not a root, no need to move balls, just update the parent\n if root_x != x:\n self.parent[x] = root_y\n\n\ndef main():\n N, Q = map(int, input().split())\n ball_colors = list(map(int, input().split()))\n\n uf = UnionFind(N)\n for i in range(N):\n uf.color_sets[i].add(ball_colors[i])\n\n for _ in range(Q):\n a, b = map(int, input().split())\n a -= 1\n b -= 1\n uf.move(a, b)\n print(len(uf.color_sets[uf.find(b)]))\n\n\nif __name__ == \"__main__\":\n main()\n","repo_name":"pedestrian618/atcoder","sub_path":"abc329/e.py","file_name":"e.py","file_ext":"py","file_size_in_byte":1489,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"15"} +{"seq_id":"7330406221","text":"from os import name\nimport sys\n\nfrom manager import Manager\nfrom config import Config\n\nConfig()\nmanager = Manager(f\"{Config.datapath}/{Config.datafilename}\")\n\nif len(sys.argv) == 1:\n print(\"You must use `enter` or `exit`\")\nelse:\n if sys.argv[1] == \"enter\":\n manager.enter()\n elif sys.argv[1] == \"exit\":\n manager.exit()\n elif sys.argv[1] == \"history\":\n manager.history()\n\nmanager.close()\n","repo_name":"akahenry/punch-the-clock","sub_path":"main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":420,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"15"} +{"seq_id":"7455593439","text":"# https://www.codechef.com/problems/CHEFA\n\nbasic_input = int(input())\n\ndef checker(pile_list,n):\n\n chef_score = 0\n roma_score = 0\n\n pile_list.sort()\n pile_list.reverse()\n\n for i in range(n):\n if i%2==0:\n chef_score += pile_list[i]\n else:\n roma_score += pile_list[i]\n \n print(chef_score)\n\nfor _ in range(basic_input):\n \n num_of_piles = int(input())\n pile_list = list(map(int, input().split()))\n\n checker(pile_list,num_of_piles)\n\n\n# logic \n# if the piles are sorted in a reverse order, since chef has the first turn, every alternate pile\n# he will try to take to maximise his score","repo_name":"burpcat/APT","sub_path":"CodeChef/practise/chef_and_easy.py","file_name":"chef_and_easy.py","file_ext":"py","file_size_in_byte":648,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"15"} +{"seq_id":"73973112330","text":"#!/usr/bin/env python3\r\n\r\n\r\n#------------------------------------------------------------\r\n# REQUIREMENTS:\r\n#\r\n# Python3\r\n# guizero\r\n# PIL (pillow)\r\n#------------------------------------------------------------\r\n\r\nfrom guizero import App, Text, Box, TextBox, PushButton, TitleBox, Picture, Drawing, CheckBox\r\nimport tkinter\r\nimport gui\r\nimport os\r\nimport Processing\r\nimport SD\r\nimport shutil\r\nimport Settings\r\nimport webbrowser\r\nimport progress_bar\r\nimport MeasureTime\r\n\r\n\r\nVERSION = \"1.0.0.1\"\r\n\r\ntimer = MeasureTime.Timer()\r\n\r\nsd = SD.SD()\r\nsd.Load()\r\n\r\nsettings = Settings.Settings()\r\nsettings.Load()\r\n\r\n#------------------------------------------------------------\r\n#default settings parameters for the gui\r\n#do not change it unless you have strong reasons for that!\r\n#------------------------------------------------------------\r\nguiWidth = 860\r\nguiHeight = 540\r\ninnerWidth = (guiWidth-92)\r\ninnerHeight = 400\r\n#------------------------------------------------------------\r\n\r\n#------------------------------------------------------------\r\n#global variables for storing details...\r\n#------------------------------------------------------------\r\n\r\nWorkingDirectory = os.getcwd()\r\n\r\nSteps = int(sd.GetSteps())\r\n\r\nDiffusion = Processing.Diffusion()\r\n#------------------------------------------------------------\r\n\r\n#------------------------------------------------------------\r\n# creating gui elements\r\n#------------------------------------------------------------\r\nmygui = gui.GUI()\r\nmygui.CreateWindow(\"OnnxStream GUI\", guiWidth, guiHeight)\r\nmain_window = mygui.GetMainWindow()\r\napp = main_window\r\nmain_window.bg = \"#F4F4F4\"\r\n\r\nmaster = mygui.DrawWindow()\r\ninnerbox = mygui.DrawMain(innerWidth, innerHeight)\r\n#------------------------------------------------------------\r\n\r\n\r\n#------------------------------------------------------------\r\n#header controls, like settings, help buttons, etc...\r\n#some kind of a top menu, but in a custom way, because I like this more\r\n#------------------------------------------------------------\r\nHeaderControls = Box(master, layout=\"grid\", grid=[0,0], width=guiWidth, height=35, align=\"top\", border=0)\r\n\r\n#spacer left\r\nBox(HeaderControls, layout=\"grid\", grid=[0,0], width=46, height=35, align=\"right\", border=0)\r\nHeaderText_box = Box(HeaderControls, layout=\"grid\", grid=[1,0], width=(innerWidth-120), height=35, align=\"left\", border=0)\r\nHeaderControls_inner = Box(HeaderControls, layout=\"grid\", grid=[2,0], width=120, height=35, align=\"right\", border=0)\r\n#spacer right\r\nBox(HeaderControls, layout=\"grid\", grid=[3,0], width=46, height=35, align=\"left\", border=0)\r\n#------------------------------------------------------------\r\n\r\n#------------------------------------------------------------\r\n#header text, info text, etc...\r\n#------------------------------------------------------------\r\nHeaderText_box_inner = Box(HeaderText_box, layout=\"grid\", grid=[0,0], width=(innerWidth-300)-46, height=35, align=\"left\", border=0)\r\nHeaderText = Text(HeaderText_box_inner, text=\"OnnxStream GUI\", grid=[0,0], align=\"left\")\r\nHeaderText.font = \"Arial Black\"\r\nHeaderText.text_color = \"#000000\"\r\nHeaderText.size = 16\r\n\r\n#spacer right\r\nBox(HeaderText_box_inner, layout=\"grid\", grid=[1,0], width=46, height=35, align=\"left\", border=0)\r\n\r\n#version number\r\nHeaderText = Text(HeaderText_box_inner, text=VERSION, grid=[2,0], align=\"right\")\r\nHeaderText.font = \"Arial\"\r\nHeaderText.text_color = \"#000000\"\r\nHeaderText.size = 9\r\n\r\n#------------------------------------------------------------\r\n\r\n#------------------------------------------------------------\r\n# Open settings window function\r\n#------------------------------------------------------------\r\ndef OpenSettings():\r\n settings.Show(main_window)\r\n#------------------------------------------------------------\r\n\r\n#------------------------------------------------------------\r\n# Open github page to the GUI in default webbrowser\r\n#------------------------------------------------------------\r\ndef OpenGithub():\r\n webbrowser.open(\"https://github.com/ThomAce/OnnxStreamGui\")\r\n#------------------------------------------------------------\r\n\r\n#------------------------------------------------------------\r\n# Open OnnxStream Github page.\r\n#------------------------------------------------------------\r\ndef OpenOnnxGithub():\r\n webbrowser.open(\"https://github.com/vitoplantamura/OnnxStream\")\r\n#------------------------------------------------------------\r\n \r\nPushButton(HeaderControls_inner, grid=[0,0],text=\"Settings\", padx=6, pady=2, align=\"right\", command=OpenSettings).font = \"Arial\"\r\nBox(HeaderControls_inner, layout=\"auto\", grid=[1,0], border=0, align=\"right\", width=10, height=20)\r\nPushButton(HeaderControls_inner, grid=[2,0],text=\"GUI on Github\", align=\"right\", padx=6, pady=2, command=OpenGithub).font = \"Arial\"\r\nBox(HeaderControls_inner, layout=\"auto\", grid=[3,0], border=0, align=\"right\", width=10, height=20)\r\nPushButton(HeaderControls_inner, grid=[4,0],text=\"OnnxStream on Github\", align=\"right\", padx=6, pady=2, command=OpenOnnxGithub).font = \"Arial\"\r\n#------------------------------------------------------------\r\n\r\n\r\n#------------------------------------------------------------\r\n#input box outer for holding the inner boxes\r\n#it is required to avoid graphical glitches and possible alignment issues on different screens\r\n#this also helping to keep the content aligned to top-left\r\n#------------------------------------------------------------\r\ninputbox_outer = Box(innerbox, layout=\"grid\", grid=[0,0], width=innerWidth-320, height=innerHeight, border=0, align=\"top\")\r\n#------------------------------------------------------------\r\n\r\n#------------------------------------------------------------\r\n# input box\r\n# this holds all the elements like project name input, push buttons, etc...\r\n#------------------------------------------------------------\r\ninputbox = Box(inputbox_outer, layout=\"grid\", grid=[0,0], width=innerWidth-330, height=innerHeight, border=0, align=\"left\")\r\n#------------------------------------------------------------\r\n\r\n#------------------------------------------------------------\r\n# + Box (ProjectActionBox)\r\n# + Text (Project Actions)\r\n# + Box [spacer]\r\n# + PushButton (Save Project)\r\n# + Box [spacer]\r\n# + PushButton (Load Project)\r\n# + Box [spacer]\r\n# + PushButton (New Project)\r\n#------------------------------------------------------------\r\n\r\n#project function\r\n#referencing to a later defined functions. Python trick...\r\n#------------------------------------------------------------\r\ndef save_project():\r\n save_project_data()\r\n#------------------------------------------------------------\r\n \r\n#------------------------------------------------------------\r\ndef export_project():\r\n save_project_data()\r\n\r\n if (sd.GetStatus()):\r\n selected_file = app.select_file(title=\"Save Project\", folder=\".\", filetypes=[[\"All files\", \"*.txt\"]], save=True, filename=\"\")\r\n\r\n if(selected_file != \"\"):\r\n sd.Save(selected_file)\r\n#------------------------------------------------------------\r\n \r\n#------------------------------------------------------------\r\ndef load_project():\r\n if (sd.GetStatus()):\r\n if (not app.yesno(\"WARNING!\", \"There is a loaded project. Do you wish to overwrite it?\")):\r\n return\r\n\r\n if (not sd.LoadProjectFile(app.select_file(title=\"Select Project\", folder=\".\", filetypes=[[\"All files\", \"*.txt\"]], save=False, filename=\"\"))):\r\n app.warn(\"WARNING!\", \"Project file is not loaded!\")\r\n else:\r\n load_project_data()\r\n#------------------------------------------------------------\r\n \r\n#------------------------------------------------------------\r\ndef new_project():\r\n if (not app.yesno(\"WARNING!\", \"Do you really wanted to reset all fields?\")): \r\n return\r\n\r\n reset_project_data()\r\n sd.Reset()\r\n#------------------------------------------------------------ \r\n\r\nProjectActionBox = Box(inputbox, layout=\"grid\", grid=[0,0], border=0, align=\"left\")\r\nText(ProjectActionBox, grid=[0,0], text=\"Project Actions\", align=\"left\", size=9, font=\"Arial Black\")\r\nBox(ProjectActionBox, layout=\"auto\", grid=[1,0], border=0, align=\"left\", width=20, height=20)\r\nSaveProject_PushButton = PushButton(ProjectActionBox, grid=[2,0],text=\"Save\", padx=6, pady=1, command=save_project)\r\nSaveProject_PushButton.font = \"Arial\"\r\nBox(ProjectActionBox, layout=\"auto\", grid=[3,0], border=0, align=\"left\", width=20, height=20)\r\nLoadProject_PushButton = PushButton(ProjectActionBox, grid=[4,0],text=\"Load\", padx=6, pady=1, command=load_project)\r\nLoadProject_PushButton.font = \"Arial\"\r\nBox(ProjectActionBox, layout=\"auto\", grid=[5,0], border=0, align=\"left\", width=20, height=20)\r\nLoadProject_PushButton = PushButton(ProjectActionBox, grid=[6,0],text=\"Export\", padx=6, pady=1, command=export_project)\r\nLoadProject_PushButton.font = \"Arial\"\r\nBox(ProjectActionBox, layout=\"auto\", grid=[7,0], border=0, align=\"left\", width=20, height=20)\r\nNewProject_PushButton = PushButton(ProjectActionBox, grid=[8,0],text=\"New\", padx=6, pady=1, command=new_project)\r\nNewProject_PushButton.font = \"Arial\"\r\n#------------------------------------------------------------\r\n\r\n\r\n\r\n#------------------------------------------------------------\r\n# project input box\r\n# Outer box for holding sub-boxes and objects / widgets\r\n#------------------------------------------------------------\r\nProjectInputBox = Box(inputbox, layout=\"grid\", grid=[0,1], border=0, align=\"left\")\r\n#------------------------------------------------------------\r\n\r\n#------------------------------------------------------------\r\n# Text (Project Name)\r\n# + TextBox (ProjectName)\r\n#------------------------------------------------------------\r\nText(ProjectInputBox, grid=[0,0], text=\"Project Name\", align=\"left\", size=9, font=\"Arial Black\")\r\nProjectName = TextBox(ProjectInputBox, grid=[0,1], text=sd.GetName(), align=\"left\", width=60, multiline=False)\r\nProjectName.font = \"Arial\"\r\n#------------------------------------------------------------\r\n\r\n#------------------------------------------------------------\r\n# Text (Positive Prompt)\r\n# + TextBox (PositivePrompt)\r\n#------------------------------------------------------------\r\nText(ProjectInputBox, grid=[0,2], text=\"Positive Prompt\", align=\"left\", size=9, font=\"Arial Black\")\r\nPositivePrompt = TextBox(ProjectInputBox, grid=[0,3], text=sd.GetPosPrompt(), align=\"left\", width=58, height=4, multiline=True, scrollbar=True)\r\nPositivePrompt.wrap = True\r\nPositivePrompt.font = \"Arial\"\r\n#------------------------------------------------------------\r\n\r\n#------------------------------------------------------------\r\n# Text (Negative Prompt)\r\n# + TextBox (NegativePrompt)\r\n#------------------------------------------------------------\r\nText(ProjectInputBox, grid=[0,4], text=\"Negative Prompt\", align=\"left\", size=9, font=\"Arial Black\")\r\nNegativePrompt = TextBox(ProjectInputBox, grid=[0,5], text=sd.GetNegPrompt(), align=\"left\", width=58, height=3, multiline=True, scrollbar=True)\r\nNegativePrompt.wrap = True\r\nNegativePrompt.font = \"Arial\"\r\n#------------------------------------------------------------\r\n\r\n#------------------------------------------------------------\r\n# Text (Image name)\r\n# + TextBox (TargetImage)\r\n#------------------------------------------------------------\r\nText(ProjectInputBox, grid=[0,6], text=\"Image name\", align=\"left\", size=9, font=\"Arial Black\")\r\nTargetImage_Box = Box(ProjectInputBox, grid=[0,7], layout=\"grid\", width=\"fill\", align=\"left\")\r\nTargetImage = TextBox(TargetImage_Box, grid=[0,0], text=sd.GetImage(), align=\"left\", width=54, multiline=False)\r\nTargetImage.font = \"Arial\"\r\n#spacer\r\nBox(TargetImage_Box, grid=[1,0],layout=\"grid\",align=\"left\", width=10, height=10, border=0)\r\n\r\n#------------------------------------------------------------\r\n# opening target image location... \"where to save\"\r\n#------------------------------------------------------------\r\ndef open_target_image():\r\n save_path = app.select_file(title=\"Save generated image file\", folder=\".\", filetypes=[[\"All files\", \"*.png\"]], save=True, filename=\"\")\r\n\r\n if (save_path[-4:].lower() != \".png\"):\r\n save_path += \".png\"\r\n \r\n if os.path.isfile(save_path):\r\n if (not app.yesno(\"WARNING!\", \"The file already exists!\\r\\nDo you wish to overwrite?\")):\r\n return \r\n\r\n TargetImage.value = save_path\r\n#------------------------------------------------------------\r\n\r\nOpenTargetImage_PushButton = PushButton(TargetImage_Box, command=open_target_image, grid=[2,0], width=18, height=18, align=\"right\", image=WorkingDirectory + \"/images/save_icon.png\")\r\n#------------------------------------------------------------\r\n\r\n\r\n#------------------------------------------------------------\r\n# Text (Steps)\r\n# + Box (SliderBox)\r\n# + Box (SpinBox)\r\n# + Box (SpinBox_text)\r\n# + TextBox (Steps_TextBox)\r\n# + Box (SpinBox_buttons)\r\n# + PushButton (up)\r\n# + PushButton (down)\r\n#\r\n# Additionals:\r\n# function (steps_text_changed)\r\n# function (increase_steps)\r\n# function (decrease_steps)\r\n# function (getTextBoxValue)\r\n# function (getTextBoxObj)\r\n# and others...\r\n#------------------------------------------------------------\r\nText(ProjectInputBox, grid=[0,8], text=\"Steps and Seed\", align=\"left\", size=9, font=\"Arial Black\")\r\n\r\n#------------------------------------------------------------\r\n# this function is called uppon text changed\r\n#------------------------------------------------------------\r\ndef steps_text_changed(textbox_value):\r\n global Steps\r\n \r\n if getTextBoxValue(getStepsBox()).isnumeric() == False:\r\n if (getTextBoxValue(getStepsBox())[:-1].isnumeric() == True):\r\n getStepsBox().value = getTextBoxValue(getStepsBox())[:-1]\r\n else:\r\n Steps = 3\r\n getStepsBox().value = \"3\"\r\n return\r\n\r\n if (int(getTextBoxValue(getStepsBox())) > 100):\r\n Steps = 100\r\n getStepsBox().value = \"100\"\r\n return\r\n\r\n if (int(getTextBoxValue(getStepsBox())) < 3):\r\n Steps = 3\r\n getStepsBox().value = \"3\"\r\n return\r\n\r\n Steps = int(getTextBoxValue(getStepsBox()))\r\n#------------------------------------------------------------\r\n \r\n#------------------------------------------------------------\r\n# increase steps\r\n#------------------------------------------------------------\r\ndef increase_steps():\r\n global Steps \r\n \r\n if Steps >= 100:\r\n return\r\n \r\n Steps += 1\r\n Steps_TextBox.value = str(Steps)\r\n#------------------------------------------------------------\r\n\r\n#------------------------------------------------------------\r\n# decrease steps\r\n#------------------------------------------------------------\r\ndef decrease_steps():\r\n global Steps \r\n \r\n if Steps <= 3:\r\n return\r\n \r\n Steps -= 1\r\n Steps_TextBox.value = str(Steps)\r\n#------------------------------------------------------------\r\n\r\n#------------------------------------------------------------\r\n# Spinbox for holding steps and other controls\r\n#------------------------------------------------------------\r\nSpinBox = Box(ProjectInputBox, grid=[0,9],layout=\"grid\",align=\"left\", width=\"fill\", height=\"fill\", border=0)\r\nText(SpinBox, grid=[0,0], text=\"Steps:\", align=\"left\", size=9, font=\"Arial Black\")\r\nBox(SpinBox, grid=[1,0],layout=\"grid\",align=\"left\", width=10, height=10, border=0) #spacer\r\nSpinBox_text = Box(SpinBox, grid=[2,0],align=\"left\", width=\"fill\", height=\"fill\")\r\nSteps_TextBox = TextBox(SpinBox_text, text=sd.GetSteps(), align=\"left\", width=\"4\",command=steps_text_changed)\r\nSteps_TextBox.font = \"Arial\"\r\n#------------------------------------------------------------\r\n\r\n#------------------------------------------------------------\r\n# getting textobx object for steps\r\n#------------------------------------------------------------\r\n#def getTextBoxObj():\r\n# return Steps_TextBox\r\n#------------------------------------------------------------\r\n\r\n#------------------------------------------------------------\r\n# Spinbox imitation with up and down buttons\r\n#------------------------------------------------------------\r\nSpinBox_buttons = Box(SpinBox, grid=[3,0], layout=\"grid\",align=\"left\", width=\"fill\", height=\"fill\")\r\nSpinBox_UP = PushButton(SpinBox_buttons, grid=[0,0],text=\"+\", padx=6, pady=0, image=WorkingDirectory + \"/images/button_up.png\", width=10, height=5, command=increase_steps)\r\nSpinBox_UP.font = \"Arial\"\r\nSpinBox_Down = PushButton(SpinBox_buttons, grid=[0,1],text=\"-\", padx=6, pady=0, image=WorkingDirectory + \"/images/button_down.png\", width=10, height=5, command=decrease_steps)\r\nSpinBox_Down.font = \"Arial\"\r\n#------------------------------------------------------------\r\n\r\n#------------------------------------------------------------\r\n# making a new random seed number\r\n#------------------------------------------------------------\r\ndef random_seed():\r\n sd.SetSeed(-1)\r\n set_seed()\r\n return\r\n#------------------------------------------------------------\r\n\r\n#------------------------------------------------------------\r\n# this function called uppon content of seed textbox changed\r\n#------------------------------------------------------------\r\ndef seed_changed(text):\r\n if getTextBoxValue(getSeedBox()).isnumeric() == False:\r\n sd.SetSeed(-1)\r\n getSeedBox().value = str(sd.GetSeed())\r\n return\r\n\r\n sd.SetSeed(int(getSeedBox().value))\r\n getSeedBox().value = sd.GetSeed()\r\n#------------------------------------------------------------\r\n\r\n#------------------------------------------------------------\r\n# Seed and the buttons for these controls\r\n#------------------------------------------------------------\r\nSeedBox = Box(SpinBox, grid=[4,0],align=\"left\", width=\"fill\", height=\"fill\",layout=\"grid\")\r\nBox(SeedBox, grid=[0,0],layout=\"grid\",align=\"left\", width=10, height=10, border=0) #spacer\r\nText(SeedBox, grid=[1,0], text=\"Seed:\", align=\"left\", size=9, font=\"Arial Black\")\r\nBox(SeedBox, grid=[2,0],layout=\"grid\",align=\"left\", width=10, height=10, border=0) #spacer\r\nSeedBox_TextBox = TextBox(SeedBox, grid=[3,0], text=sd.GetSeed(), align=\"left\", width=\"12\",command=seed_changed)\r\nSeedBox_TextBox.font = \"Arial\"\r\nBox(SeedBox, grid=[4,0],layout=\"grid\",align=\"left\", width=10, height=10, border=0) #spacer\r\nSeedBox_PushButton = PushButton(SeedBox, grid=[5,0],text=\" \", padx=6, pady=0, width=18, height=18, image=WorkingDirectory + \"/images/dice_icon.png\", command=random_seed)\r\n#------------------------------------------------------------\r\n\r\n#------------------------------------------------------------\r\n# return seedbox textbox widget object\r\n#------------------------------------------------------------\r\ndef getSeedBox():\r\n return SeedBox_TextBox\r\n#------------------------------------------------------------\r\n\r\n#------------------------------------------------------------\r\n# return steps textbox widget object\r\n#------------------------------------------------------------\r\ndef getStepsBox():\r\n return Steps_TextBox#SpinBox_text\r\n#------------------------------------------------------------\r\n\r\n#------------------------------------------------------------\r\n# return textbox value\r\n#------------------------------------------------------------\r\ndef getTextBoxValue(TextBoxObj):\r\n return TextBoxObj.value #Steps_TextBox.value\r\n#------------------------------------------------------------\r\n\r\n#------------------------------------------------------------\r\n# set seed value from project file\r\n#------------------------------------------------------------\r\ndef set_seed():\r\n SeedBox_TextBox.value = sd.GetSeed()\r\n#------------------------------------------------------------\r\n\r\n#------------------------------------------------------------\r\n# Checkbox for switching between SD and SDXL\r\n#------------------------------------------------------------\r\nUseXL_CheckBox = CheckBox(ProjectInputBox,grid=[0,10], align=\"left\", text=\"Use Stable Diffusion XL 1.0 instead of Stable Diffusion 1.5\")\r\nUseXL_CheckBox.font = \"Arial\"\r\n\r\nif (sd.GetXL() == True):\r\n UseXL_CheckBox.toggle()\r\n#------------------------------------------------------------\r\n\r\n#------------------------------------------------------------\r\n#horizontal line\r\n#------------------------------------------------------------\r\nBox(ProjectInputBox, grid=[0,11],layout=\"grid\",align=\"left\", width=innerWidth-320, height=2, border=0).bg = \"#EFEFEF\"\r\nBox(ProjectInputBox, grid=[0,12],layout=\"grid\",align=\"left\", width=320, height=15, border=0) #horizontal spacer\r\n#------------------------------------------------------------\r\n\r\n\r\n#------------------------------------------------------------\r\n# Start diffusing procedure...\r\n#------------------------------------------------------------\r\ndef start_diffusing(): \r\n if (not Diffusion.GetStatus()):\r\n save_project_data()\r\n\r\n if os.path.isfile(sd.GetImage()):\r\n if (not app.yesno(\"WARNING!\", \"The target image will be overwritten.\\r\\nAre you sure?\")):\r\n return\r\n\r\n timer.start()\r\n\r\n sd.ResetThumb()\r\n Diffusion.Diffuse()\r\n#------------------------------------------------------------\r\n\r\n#------------------------------------------------------------\r\n# Stop diffusion by user request.\r\n#------------------------------------------------------------\r\ndef stop_diffusing():\r\n Diffusion.Stop()\r\n#------------------------------------------------------------\r\n\r\n#------------------------------------------------------------\r\n# Start and stop buttons\r\n#------------------------------------------------------------\r\nStartBox = Box(ProjectInputBox, grid=[0,13],layout=\"grid\",align=\"left\", width=\"fill\", height=30, border=0)\r\nStart_Button = PushButton(StartBox, grid=[0,0],text=\"Start\", padx=6, pady=2, align=\"left\", width=30, command=start_diffusing)\r\nStart_Button.font = \"Arial\"\r\nBox(StartBox, grid=[1,0],layout=\"grid\",align=\"left\", width=50, height=20, border=0)\r\nStop_Button = PushButton(StartBox, grid=[2,0],text=\"Stop\", padx=6, pady=2, align=\"right\", width=5, command=stop_diffusing)\r\nStop_Button.font = \"Arial\"\r\n#------------------------------------------------------------\r\n\r\n\r\n#------------------------------------------------------------\r\n#horizontal spacer\r\n#------------------------------------------------------------\r\nBox(innerbox, layout=\"auto\", grid=[1,0], width=10, height=400, align=\"top\", border=0)\r\n#------------------------------------------------------------\r\n\r\n\r\n#------------------------------------------------------------\r\n#image and related controls holder box\r\n#------------------------------------------------------------\r\nimageBox = Box(innerbox, layout=\"grid\", grid=[2,0], width=320, height=400, align=\"top\", border=0)\r\n\r\n#image\r\npicture = Picture(imageBox, image=WorkingDirectory + \"/images/main.png\", grid=[0,0], width=320, height=320)\r\n\r\n#vertical spacer\r\npbbox = Box(imageBox, layout=\"auto\", grid=[0,1], width=320, height=10, align=\"top\", border=0)\r\npb = progress_bar.ProgressBar(pbbox)\r\npb.Width(320)\r\npb.Height(5)\r\npb.BarColor(\"#7CB5FF\")\r\npb.Show()\r\n\r\nStatusBox = Box(imageBox, layout=\"grid\", grid=[0,2], border=0, align=\"left\")\r\nText(StatusBox, grid=[0,0], text=\"Status:\", align=\"left\", size=9, font=\"Arial Black\")\r\nStatusMSG = Text(StatusBox, grid=[1,0], text=\"Completed...\", align=\"left\", size=10)\r\nStatusMSG.font = \"Arial\"\r\n\r\n#horizontal line\r\nBox(imageBox, grid=[0,3],layout=\"grid\",align=\"left\", width=320, height=2, border=0).bg = \"#EFEFEF\"\r\n#spacer\r\nBox(imageBox, grid=[0,4],layout=\"grid\",align=\"left\", width=60, height=10, border=0)\r\n\r\n#image controls\r\nImageActionBox = Box(imageBox, layout=\"grid\", grid=[0,5], border=0, align=\"left\")\r\n#------------------------------------------------------------\r\n\r\n#------------------------------------------------------------\r\n# Saving the image to user defined location.\r\n#------------------------------------------------------------\r\ndef save_image():\r\n selected_file = app.select_file(title=\"Save to file\", folder=\".\", filetypes=[[\"All files\", \"*.png\"]], save=True, filename=\"\")\r\n\r\n if (selected_file != \"\"):\r\n if (selected_file[-4:].lower() != \".png\"):\r\n selected_file += \".png\"\r\n \r\n shutil.move(sd.GetImage(), selected_file)\r\n EnableVisuals()\r\n app.info(\"Info\", \"Done!\")\r\n#------------------------------------------------------------\r\n\r\n#------------------------------------------------------------\r\n# Delete image function.\r\n#------------------------------------------------------------\r\ndef delete_image():\r\n if (not app.yesno(\"WARNING!\", \"The actual file will be deleted.\\r\\nAre you sure?\")):\r\n return\r\n\r\n try:\r\n os.remove(sd.GetImage())\r\n EnableVisuals()\r\n app.info(\"Info\", \"Done!\")\r\n except:\r\n app.error(\"Error\", \"File could not be deleted!\")\r\n pass\r\n#------------------------------------------------------------\r\n\r\n#------------------------------------------------------------\r\n# Action buttons for save, refine, delete image.\r\n#------------------------------------------------------------\r\nText(ImageActionBox, grid=[0,0], text=\"Actions:\", align=\"left\", size=9, font=\"Arial Black\")\r\nBox(ImageActionBox, layout=\"auto\", grid=[1,0], border=0, align=\"left\", width=20, height=20)\r\nSave_Image_PushButton = PushButton(ImageActionBox, grid=[2,0],text=\"Save Image\", padx=6, pady=2, command=save_image)\r\nSave_Image_PushButton.font = \"Arial\"\r\n\r\nBox(ImageActionBox, layout=\"auto\", grid=[3,0], border=0, align=\"left\", width=20, height=20)\r\nDelete_Image_PushButton = PushButton(ImageActionBox, grid=[6,0],text=\"Delete Image\", padx=6, pady=2, command=delete_image)\r\nDelete_Image_PushButton.font = \"Arial\"\r\n#------------------------------------------------------------\r\n\r\n#------------------------------------------------------------\r\n# saving project data\r\n#------------------------------------------------------------\r\ndef save_project_data():\r\n sd.SetName(ProjectName.value)\r\n sd.SetPosPrompt(PositivePrompt.value)\r\n sd.SetNegPrompt(NegativePrompt.value)\r\n sd.SetImage(TargetImage.value)\r\n sd.SetSteps(Steps_TextBox.value)\r\n sd.SetXL(UseXL_CheckBox.value)\r\n sd.SetSeed(SeedBox_TextBox.value)\r\n sd.Save()\r\n#------------------------------------------------------------\r\n\r\n#------------------------------------------------------------\r\n# loading the project data file\r\n#------------------------------------------------------------\r\ndef load_project_data():\r\n ProjectName.value = sd.GetName()\r\n PositivePrompt.value = sd.GetPosPrompt()\r\n NegativePrompt.value = sd.GetNegPrompt()\r\n TargetImage.value = sd.GetImage()\r\n Steps_TextBox.value = sd.GetSteps()\r\n SeedBox_TextBox.value = sd.GetSeed()\r\n UseXL_CheckBox.value = sd.GetXL()\r\n#------------------------------------------------------------\r\n\r\n#------------------------------------------------------------\r\n# reset all project data to \"empty\"\r\n#------------------------------------------------------------\r\ndef reset_project_data():\r\n ProjectName.value = \"\"\r\n PositivePrompt.value = \"\"\r\n NegativePrompt.value = \"\"\r\n TargetImage.value = \"\"\r\n Steps_TextBox.value = \"10\"\r\n SeedBox_TextBox.value = sd.GetSeed(-1)\r\n UseXL_CheckBox.value = False\r\n#------------------------------------------------------------\r\n\r\n#------------------------------------------------------------\r\n# disable most visual elements on main form to avoid unwanted user inputs during processing\r\n#------------------------------------------------------------\r\ndef DisableVisuals():\r\n ProjectName.enabled = False\r\n PositivePrompt.enabled = False\r\n NegativePrompt.enabled = False\r\n TargetImage.enabled = False\r\n Steps_TextBox.enabled = False\r\n UseXL_CheckBox.enabled = False\r\n SpinBox_UP.enabled = False\r\n SpinBox_Down.enabled = False\r\n Start_Button.enabled = False\r\n OpenTargetImage_PushButton.enabled = False\r\n ProjectActionBox.enabled = False\r\n SeedBox_TextBox.enabled = False\r\n SeedBox_PushButton.enabled = False\r\n \r\n picture.image = WorkingDirectory + \"/images/loading.png\"\r\n#------------------------------------------------------------\r\n\r\n#------------------------------------------------------------\r\n# disable image action buttions below the generated image\r\n#------------------------------------------------------------\r\ndef DisableImageActionButtons():\r\n Save_Image_PushButton.enabled = False\r\n Delete_Image_PushButton.enabled = False\r\n#------------------------------------------------------------\r\n\r\n#------------------------------------------------------------\r\n# enable image action buttions below the generated image\r\n#------------------------------------------------------------\r\ndef EnableImageActionButtons():\r\n Save_Image_PushButton.enabled = True\r\n Delete_Image_PushButton.enabled = True\r\n#------------------------------------------------------------\r\n\r\n#------------------------------------------------------------\r\n# Enabling visual elemenets\r\n#------------------------------------------------------------\r\ndef EnableVisuals():\r\n ProjectName.enabled = True\r\n PositivePrompt.enabled = True\r\n NegativePrompt.enabled = True\r\n TargetImage.enabled = True\r\n Steps_TextBox.enabled = True\r\n UseXL_CheckBox.enabled = True\r\n SpinBox_UP.enabled = True\r\n SpinBox_Down.enabled = True\r\n Start_Button.enabled = True\r\n OpenTargetImage_PushButton.enabled = True\r\n ProjectActionBox.enabled = True\r\n SeedBox_TextBox.enabled = True\r\n SeedBox_PushButton.enabled = True\r\n \r\n picture.image = WorkingDirectory + \"/images/main.png\"\r\n#------------------------------------------------------------\r\n\r\n#------------------------------------------------------------\r\n# this is responsible for a visual update during processing\r\n# nothing more just some visual stuffs for entertaining purposes\r\n#------------------------------------------------------------\r\nproc_steps = 0\r\n\r\ndef get_proc_msg():\r\n global proc_steps\r\n\r\n proc_steps += 1\r\n\r\n if proc_steps > 3:\r\n proc_steps = 0\r\n return \"Processing \" + timer.get()\r\n elif proc_steps == 3:\r\n return \"Processing... \" + timer.get()\r\n elif proc_steps == 2:\r\n return \"Processing.. \" + timer.get()\r\n elif proc_steps == 1:\r\n return \"Processing. \" + timer.get()\r\n\r\n return \"Processing\"\r\n#------------------------------------------------------------\r\n\r\n#------------------------------------------------------------\r\n# Get thread status every seconds\r\n# it will control the visual elements accordingly.\r\n#------------------------------------------------------------\r\ndef GetThreadStatus():\r\n global app\r\n \r\n if (Diffusion.GetStatus() == True):\r\n StatusMSG.value = get_proc_msg()\r\n\r\n app.title = \"OnnxStream GUI - Processing... \" + Diffusion.GetProgress()\r\n\r\n pb.Progress(int(Diffusion.GetProgress().replace(\"%\", \"\").strip()))\r\n \r\n DisableVisuals()\r\n DisableImageActionButtons()\r\n Stop_Button.enabled = True\r\n else:\r\n StatusMSG.value = \"Ready\"\r\n app.title = \"OnnxStream GUI\"\r\n DisableImageActionButtons()\r\n pb.Progress(0)\r\n\r\n if os.path.isfile(sd.GetImage()):\r\n picture.image = sd.GetImageThumb()\r\n EnableImageActionButtons()\r\n\r\n if (Diffusion.GetProcessingResult() == True):\r\n StatusMSG.value = \"Finished! \"\r\n app.title = \"OnnxStream GUI\"\r\n pb.Progress(100)\r\n\r\n timer.stop()\r\n StatusMSG.value += timer.get()\r\n EnableVisuals()\r\n Stop_Button.enabled = False\r\n\r\n if os.path.isfile(sd.GetImage()):\r\n picture.image = sd.GetImageThumb()\r\n EnableImageActionButtons()\r\n#------------------------------------------------------------\r\n\r\n \r\nDisableImageActionButtons()\r\n \r\nStop_Button.enabled = False\r\n\r\napp.repeat(1000, GetThreadStatus)\r\n\r\n\r\ndef bring_to_front():\r\n global app\r\n app.tk.attributes(\"-topmost\", True)\r\n app.tk.lift()\r\n app.tk.attributes(\"-topmost\", False)\r\n\r\nbring_to_front()\r\n\r\napp.after(1000, bring_to_front)\r\n\r\n#showing the gui\r\nmygui.Show()\r\n\r\n#------------------------------------------------------------\r\n# end of the script\r\n#------------------------------------------------------------\r\n","repo_name":"ThomAce/OnnxStreamGui","sub_path":"Desktop/__main__.py","file_name":"__main__.py","file_ext":"py","file_size_in_byte":32148,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"15"} +{"seq_id":"36590821852","text":"import uvicorn\n\nfrom fastapi import FastAPI\nfrom starlette.responses import RedirectResponse\n\nfrom make_us_rich.client import BinanceClient\nfrom make_us_rich.serving import ModelLoader\n\n\napp = FastAPI(\n title=\"Serving Crypto Models\",\n description=\"API to serve dynamically crypto models\",\n version=\"1.0\",\n openapi_url=\"/api/v1/openapi.json\",\n)\nclient = BinanceClient()\nmodels = ModelLoader()\n\n\n@app.get(\"/\", include_in_schema=False)\nasync def home():\n \"\"\"\n Home endpoint to redirect to docs.\n \"\"\"\n return RedirectResponse(\"/docs\")\n\n\n@app.put(\"/predict\", include_in_schema=True, tags=[\"serving\"])\nasync def predict(currency: str, compare: str, token: str = None):\n \"\"\"\n Predict endpoint.\n\n Parameters\n ----------\n currency: str\n Currency used in the model.\n compare: str\n Compare used in the model.\n token: str\n API token of the user.\n \n Returns\n -------\n \"\"\"\n if token is None:\n return {\n \"error\": \"You need to provide an API token. Check documentation for more information: https://chainyo.github.io/make-us-rich/\"\n }\n model_name = f\"{currency}_{compare}\"\n symbol = \"\".join(model_name.split(\"_\"))\n data = client.get_five_days_data(symbol)\n response = models.get_predictions(model_name, data)\n return {\"data\": data.to_dict(), \"prediction\": float(response)}\n\n\n@app.put(\"/update_models\", include_in_schema=True, tags=[\"serving\"])\nasync def update_model():\n \"\"\"\n Update models endpoint.\n \"\"\"\n models.update_model_files()\n return {\"message\": \"All models have been updated.\"}\n\n\n@app.put(\"/update_date\", include_in_schema=True, tags=[\"serving\"])\nasync def update_date():\n \"\"\"\n Update date endpoint.\n \"\"\"\n models.update_date()\n return {\"message\": \"Date has been updated.\"}\n\n\n@app.get(\"/check_models_number\", include_in_schema=True, tags=[\"monitoring\"])\nasync def check_models_number():\n \"\"\"\n Check models number endpoint.\n \"\"\"\n number_of_running_models = len(models.session_models)\n if number_of_running_models == 0:\n return {\"message\": \"Warning: No models are running.\"}\n else:\n response = {\n \"message\": f\"Number of running models: {number_of_running_models}\",\n \"models\": [],\n }\n for model in models.session_models:\n response[\"models\"].append(model)\n return response\n\n\n@app.get(\"/healthz\", status_code=200, include_in_schema=True, tags=[\"monitoring\"])\nasync def healthz():\n \"\"\"\n Healthz endpoint.\n \"\"\"\n return {\"status\": \"ok\"}\n\n\n@app.get(\"/readyz\", status_code=200, include_in_schema=True, tags=[\"monitoring\"])\nasync def readyz():\n \"\"\"\n Readyz endpoint.\n \"\"\"\n return {\"status\": \"ready\"}\n\n\nif __name__ == \"__main__\":\n uvicorn.run(\"api.main:app\", reload=True)\n","repo_name":"chainyo/make-us-rich","sub_path":"api/main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":2816,"program_lang":"python","lang":"en","doc_type":"code","stars":18,"dataset":"github-code","pt":"15"} +{"seq_id":"38228031265","text":"#!/usr/bin/env python\n# -*- coding: utf-8 -*-\n\n\n'''\n'''\n\nimport os\nfrom Bio import SeqIO\n\n\ndef read_fasta_aln (directory, liste_cluster):\n '''extract fasta sequences from dir, convert sequence in one string\n Return a dico with proteome_id as key and all corresponding sequence in files as value\n '''\n dico_all = {}\n for cluster in liste_cluster:\n if cluster.endswith('.aln'):\n path_cluster = os.path.join(directory, cluster)\n cluster = cluster.split('.')[0]\n with open(path_cluster) as f:\n for line in f:\n if line.startswith('>'):\n line = line.strip()\n name = line[1:]\n tmp = name.split('|')\n name_protein = tmp[1]\n full_proteome_name = tmp[0]\n else:\n sequence = line.strip()\n\n if full_proteome_name not in dico_all:\n dico_all[full_proteome_name] = sequence\n else:\n dico_all[full_proteome_name] +=sequence\n\n print(len(dico_all))\n print (len(dico_all[full_proteome_name]))\n return dico_all\n\ndef write_seq (dico_all, core_genome):\n '''write in a output file the fusionned sequence\n '''\n\n with open(core_genome, 'w') as outf:\n for proteome_id in dico_all:\n outf.write('>'+proteome_id+'\\n'+dico_all[proteome_id]+'\\n')\n\n\n\nrep = '/home/issa/Documents/stage/muscle/final_alignement/'\nliste_cl = os.listdir(rep)\ncore_genome = 'clusters_fusionned.fasta'\ndico = read_fasta_aln(rep, liste_cl)\nwrite_seq (dico, core_genome)\n","repo_name":"Issa900/AP_Intern","sub_path":"phylogenie/sequence_fusion.py","file_name":"sequence_fusion.py","file_ext":"py","file_size_in_byte":1701,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"15"} +{"seq_id":"28389049611","text":"n = int(input())\nparts_list = list(map(int, input().split()))\n\nm = int(input())\norder_list = list(map(int, input().split()))\n\nparts_list.sort()\n\ndef bisearch(key):\n start = 0\n end = len(parts_list) - 1\n\n while start <= end:\n mid = (start + end) // 2\n if parts_list[mid] == key:\n return True\n elif parts_list[mid] < key:\n start = mid + 1\n else:\n end = mid - 1\n\n return False\n\nfor order in order_list:\n if bisearch(order):\n print('yes', end=' ')\n else:\n print('no', end=' ')","repo_name":"ZeroMin-K/This_is_Coding_Test_with_Python","sub_path":"chapter07_review2/7-2-solve.py","file_name":"7-2-solve.py","file_ext":"py","file_size_in_byte":565,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"15"} +{"seq_id":"38239003868","text":"from django.urls import path\nfrom . import views \n\nurlpatterns = [\n\tpath('home/',views.home, name='home'),\n\tpath('aboutme/',views.aboutme, name='aboutme'),\t\n\tpath('contactme/',views.contactme, name='contactme'),\n\tpath('languages/',views.languages, name='languages'),\n\n]\n","repo_name":"pushpak-tiwari/success","sub_path":"pushpakdotcom/pushpak/urls.py","file_name":"urls.py","file_ext":"py","file_size_in_byte":270,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"15"} +{"seq_id":"40258314237","text":"import numpy\nimport pickle\n\n\nshows = {'Секретные материалы': {'Жанр': 'фантастика', 'Рейтинг': 0.9}, 'Ведьмак': {'Жанр': 'фэнтази', 'Рейтинг': 0.95},\n 'Клан Сопрано': {'Жанр': 'криминал', 'Рейтинг': '0.8'}, '24': {'Genre': 'драма', 'Rating': 0.75},\n 'Черное зеркало': {'Жанр': 'фантастика', 'Рейтинг': 0.98},\n 'Во все тяжкие': {'Жанр': 'криминал', 'Рейтинг': '0.85'},\n 'Игра престолов': {'Жанр': 'фэнтази', 'Рейтинг': 0.87}, 'Карточный домик': {'Genre': 'драма', 'Rating': 0.82},\n 'Рик и Морти': {'Жанр': 'фантастика', 'Рейтинг': 1}}\n\n\ndef fukciya(zhanr):\n ratings = []\n serials = []\n films = {}\n for k, v in shows.items():\n if v.get('Жанр') == zhanr:\n ratings.append(float(v.get('Рейтинг')))\n films.setdefault(k)\n elif v.get('Genre') == zhanr:\n ratings.append(float(v.get('Rating')))\n films.setdefault(k)\n\n for t, l in v.items():\n if l == zhanr:\n serials.append(t)\n serial = len(serials)\n rating = round(((sum(ratings)) / (len(ratings))), 2)\n print(f'Число сериалов {serial}, средний рейтинг {rating}')\n with open(f'{zhanr}.dat', mode='wb') as saplain:\n pickle.dump(f'{films}', saplain)\n\n\ndef zhanry():\n zhanr = []\n for k, v in shows.items():\n for t, l in v.items():\n if t == 'Жанр':\n zhanr.append(l)\n elif t == 'Genre':\n zhanr.append(l)\n return (set(zhanr))\n\n\nfor i in zhanry():\n fukciya(i)\n","repo_name":"Arkadiy28/Ozon_Skills","sub_path":"Task_6.2.py","file_name":"Task_6.2.py","file_ext":"py","file_size_in_byte":1811,"program_lang":"python","lang":"ru","doc_type":"code","stars":0,"dataset":"github-code","pt":"15"} +{"seq_id":"24375507831","text":"\"\"\"\nScript to download the data from the github repository and save it in the data/raw folder.\n.zip file is removed after unzipping.\n\"\"\"\n\nimport os\nimport zipfile\nimport wget\n\nprint(\"Downloading data from github repository...\")\n\n# download data\nurl = 'https://github.com/skoltech-nlp/detox/releases/download/emnlp2021/filtered_paranmt.zip'\nwget.download(url, out=\"./data/raw/\")\n\n# unzip data\nwith zipfile.ZipFile(\"./data/raw/filtered_paranmt.zip\", 'r') as zip_ref:\n zip_ref.extractall(\"./data/raw/\")\n\n# remove zip file\nos.remove(\"./data/raw/filtered_paranmt.zip\")\n\nprint(\"\\nDone!\")\n","repo_name":"ivancheroleg/Text-de-toxification-PMLDL-IU","sub_path":"src/data/download_data.py","file_name":"download_data.py","file_ext":"py","file_size_in_byte":585,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"15"} +{"seq_id":"5162610357","text":"\n#main and subprocesses have access to this\nimport cv2\n\nif __name__ != '__main__':\n #think of this as the subprocess environment\n from kivy.app import App\n from kivy.lang import Builder\n from kivy.uix.screenmanager import ScreenManager, Screen\n from kivy.graphics.texture import Texture\n from kivy.clock import Clock\n import mediapipe as mp\n # import skvideo.io\n # import skvideo.datasets\n\n mp_drawing = mp.solutions.drawing_utils # Drawing helpers\n mp_holistic = mp.solutions.holistic # Mediapipe Solutions\n import time\n\n class MainApp(App):\n def __init__(self, *args, **kwargs):\n super().__init__(*args, **kwargs)\n #remember that the KV string IS THE ACTUAL FILE AND MUST BE INDENTED PROPERLY TO THE LEFT!\n self.KV_string = '''\n:\n id: FCVA_screen_managerID\n StartScreen:\n id: start_screen_id\n name: 'start_screen_name'\n manager: 'FCVA_screen_managerID'\n\n:\n id: start_screen_id\n BoxLayout:\n orientation: 'vertical'\n Image:\n id: image_textureID\n Label:\n text: \"hello world!\"\n\nFCVA_screen_manager: #remember to return a root widget\n'''\n def build(self):\n self.title = \"Fast CV App v0.1.0 by Pengindoramu\"\n build_app_from_kv = Builder.load_string(self.KV_string)\n return build_app_from_kv\n \n def on_start(self):\n #start blitting, get the fps as an option [todo]\n Clock.schedule_interval(self.blit_from_shared_memory, 1/30)\n\n def run(self):\n '''Launches the app in standalone mode.\n reference: \n how to run kivy as a subprocess (so the main code can run neural networks like mediapipe without any delay)\n https://stackoverflow.com/questions/31458331/running-multiple-kivy-apps-at-same-time-that-communicate-with-each-other\n '''\n self._run_prepare()\n from kivy.base import runTouchApp\n runTouchApp()\n #here we set shared_metadata_dictVAR[\"run_state\"] to be false so main process knows to exit\n self.shared_metadata_dictVAR[\"run_state\"] = False\n # self.stop()\n \n def blit_from_shared_memory(self, *args):\n #problem is I don't think you can pickle the stream for multiprocessing (it's a tuple, idk if you can send tuples in a tuple), so send the frame instead\n # https://stackoverflow.com/questions/17872056/how-to-check-if-an-object-is-pickleable\n # import dill\n # # print(\"dill pickles!\", dill.pickles(self.stream)) #says false, so I can't send the stream, but I can still send the individual frame\n # dilling = dill.pickles(parallelize_cv_func)\n # # print(dilling)\n # if dilling:\n # self.what = FCVApool.apply_async(parallelize_cv_func, args=(cv_func_mp, ret, frame, shared_analysis_dict, self.frame_int)) \n # else:\n # print(f\"dill says function is unpickleable\")\n shared_analysis_dict = self.shared_analysis_dictVAR\n if len(shared_analysis_dict) > 0:\n max_key = max(shared_analysis_dict.keys())\n frame = shared_analysis_dict[max_key]\n buf = frame.tobytes()\n #texture documentation: https://github.com/kivy/kivy/blob/master/kivy/graphics/texture.pyx\n #blit to texture\n #blit buffer example: https://stackoverflow.com/questions/61122285/kivy-camera-application-with-opencv-in-android-shows-black-screen\n texture1 = Texture.create(size=(frame.shape[1], frame.shape[0]), colorfmt='bgr') \n texture1.blit_buffer(buf, colorfmt='bgr', bufferfmt='ubyte')\n App.get_running_app().root.get_screen('start_screen_name').ids[\"image_textureID\"].texture = texture1\n #after blitting delete some key/value pairs if dict has more than 10 frames:\n if len(shared_analysis_dict) > 5:\n min_key = min(shared_analysis_dict.keys())\n del shared_analysis_dict[min_key]\n\n class FCVA_screen_manager(ScreenManager):\n pass\n\n class StartScreen(Screen):\n pass\n\ndef open_kivy(*args):\n MainApp.shared_analysis_dictVAR = args[0]\n MainApp.shared_metadata_dictVAR = args[1]\n MainApp().run()\n\ndef open_read(*args):\n try:\n shared_analysis_dict = args[0]\n shared_metadata_dict = args[1]\n frame_rate = args[2]\n print(\"what is framerate?\", frame_rate)\n cap = cv2.VideoCapture(args[3])\n # trying scikit video as per this: https://stackoverflow.com/questions/42163058/how-to-turn-a-video-into-numpy-array\n # cap = skvideo.io.vreader(skvideo.datasets.bigbuckbunny())\n # cap = skvideo.io.vread(\"cottonbro studio.mp4\")\n\n prev = time.time()\n while True:\n if \"mp_ready\" in shared_metadata_dict.keys(): #if the key exists, assume value is true, else I have to add yet another if statement...\n\n time_elapsed = time.time() - prev\n\n if time_elapsed > 1./frame_rate:\n time_og = time.time()\n ret, frame = cap.read()\n time_2 = time.time()\n prev = time.time()\n\n # Do something with your image here.\n shared_metadata_dict[\"latest_cap_frame\"] = frame\n # print(\"keys????\", time_elapsed, 1./frame_rate, flush=True)\n # print(\"cv2 .read() takes long???\", time_2 - time_og, 1./frame_rate, flush= True)\n #reading DOES take long.. 0.052001953125 0.02\n except Exception as e:\n print(\"read function died!\", e, flush=True)\n\n# https://stackoverflow.com/questions/69722401/mediapipe-process-first-self-argument\n# alternatively you could do: results = mp.solutions.hands.Hands().process(imgRGB)\ndef open_mediapipe(*args):\n try:\n shared_analysis_dict = args[0]\n shared_metadata_dict = args[1]\n # cap = cv2.VideoCapture(0)\n # cap = cv2.VideoCapture(\"Good-Night Kiss (Dance Cover) - 전효성(JUNHYOSEONG) [UhkaBOcIB2A].webm\")\n\n \n # Initiate holistic model\n # https://peps.python.org/pep-0343/\n # In this PEP, context managers provide __enter__() and __exit__() methods that are invoked on entry to and exit from the body of the with statement.\n # https://stackoverflow.com/questions/1984325/explaining-pythons-enter-and-exit\n # https://stackoverflow.com/questions/51706836/manually-open-context-manager -> try this __exit__(None, None, None)\n\n with mp_holistic.Holistic(min_detection_confidence=0.5, min_tracking_confidence=0.5) as holistic:\n #THIS IS SLOW, SO RUNNING HOLISTIC WITHIN ANOTHER LOOP iS WHAT'S KILLING IT\n #checking here is 12 fps: shared_metadata_dict[\"run_state\"]\n # timea = time.time()\n # while shared_metadata_dict[\"run_state\"] and cap.isOpened():\n # print(\"keys?1??\", shared_metadata_dict.keys(), flush = True)\n\n shared_metadata_dict[\"mp_ready\"] = True\n\n while True:\n if \"run_state\" in shared_metadata_dict.keys() and \"latest_cap_frame\" in shared_metadata_dict.keys(): #assume true\n if shared_metadata_dict[\"run_state\"] == False:\n break\n # while cap.isOpened():\n # timeb = time.time()\n # print(\"morbin time\", timeb-timea) #reading from shared dit and cap is opened is not a problem: 0.0010020732879638672\n #nope lmao it's slow because I'm running bluestacks... (was ~10 fps)\n #nope, still ~10fps\n #old version went up to 19 fps regularly when I took down my hoodie..????\n #yeah it went to 20 when I took down hoodie and gave a side~ish profile of my face\n #yeah it's not bluestacks, it's just a bit harder head-on \n # while cap.isOpened():\n \n # timef1 = time.time()\n # ret, frame = cap.read()\n frame = shared_metadata_dict[\"latest_cap_frame\"]\n # timef2 = time.time()\n # print(\"how long to read frame?\", timef2 - timef1)# first frame takes a while and subsequent frames are fast: 0.9233419895172119 -> 0.006009101867675781\n \n # Recolor Feed\n image = cv2.cvtColor(frame, cv2.COLOR_BGR2RGB)\n image.flags.writeable = False \n \n time_1 = time.time()\n # Make Detections\n results = holistic.process(image)\n time_2 = time.time()\n\n # Recolor image back to BGR for rendering\n image.flags.writeable = True \n image = cv2.cvtColor(image, cv2.COLOR_RGB2BGR)\n \n # 2. Right hand\n mp_drawing.draw_landmarks(image, results.right_hand_landmarks, mp_holistic.HAND_CONNECTIONS, \n mp_drawing.DrawingSpec(color=(80,22,10), thickness=2, circle_radius=4),\n mp_drawing.DrawingSpec(color=(80,44,121), thickness=2, circle_radius=2)\n )\n\n # 3. Left Hand\n mp_drawing.draw_landmarks(image, results.left_hand_landmarks, mp_holistic.HAND_CONNECTIONS, \n mp_drawing.DrawingSpec(color=(121,22,76), thickness=2, circle_radius=4),\n mp_drawing.DrawingSpec(color=(121,44,250), thickness=2, circle_radius=2)\n )\n\n # 4. Pose Detections\n mp_drawing.draw_landmarks(image, results.pose_landmarks, mp_holistic.POSE_CONNECTIONS, \n mp_drawing.DrawingSpec(color=(245,117,66), thickness=2, circle_radius=4),\n mp_drawing.DrawingSpec(color=(245,66,230), thickness=2, circle_radius=2)\n )\n \n shared_analysis_dict[1] = cv2.flip(image,0)\n # print(\"why is this so fast? fps:\", 1/(time_2 - time_1), len(shared_analysis_dict), flush= True)\n # cv2.imshow('Raw Webcam Feed', image)\n\n # if cv2.waitKey(10) & 0xFF == ord('q'):\n # break\n\n # cap.release()\n # cv2.destroyAllWindows()\n # time.sleep(10000)\n except Exception as e:\n print(\"open_mediapipe died!\", e)\n\nclass FCVA():\n def __init__(self, *args, **kwargs):\n super().__init__(*args, **kwargs)\n self.frame_int = 0\n #put the imports here so that all users have to do is import FCVA and instantiate it in the top level\n \n def run(self):\n print(\"name in main (loaded main_file_read) \", __name__ == '__main__', __name__)\n if __name__ == '__main__' or __name__ == 'main_file_read':\n '''\n this will set up multiprocessing and the kivy app as a subprocess:\n '''\n import multiprocessing as FCVA_mp\n FCVA_mp.freeze_support() #this is so that only 1 window is run when packaging with pyinstaller\n shared_mem_manager = FCVA_mp.Manager()\n shared_analysis_dict = shared_mem_manager.dict()\n shared_metadata_dict = shared_mem_manager.dict()\n #set metadata run_state to true so main process will run\n shared_metadata_dict[\"run_state\"] = True\n \n #read just to get the fps\n # source = \"cottonbro studio.mp4\"\n source = 0\n # source = \"COSTA RICA IN 4K 60fps HDR (ULTRA HD).mkv\"\n video = cv2.VideoCapture(source)\n fps = video.get(cv2.CAP_PROP_FPS)\n \n # fake_frame = video.read()\n # shared_metadata_dict[\"latest_cap_frame\"] = fake_frame\n\n print(\"why is fps 0?\", fps)\n video.release()\n # read_subprocess = FCVA_mp.Process(target=open_read, args=(shared_analysis_dict,shared_metadata_dict, fps, source))\n read_subprocess = FCVA_mp.Process(target=open_read, args=(shared_analysis_dict,shared_metadata_dict, fps, source))\n read_subprocess.start()\n\n import time\n time.sleep(1)\n # mediapipe_subprocess = FCVA_mp.Process(target=open_mediapipe, args=(shared_analysis_dict,shared_metadata_dict)) \n mediapipe_subprocess = FCVA_mp.Process(target=open_mediapipe, args=(shared_analysis_dict,shared_metadata_dict)) \n mediapipe_subprocess.start()\n \n # kivy_subprocess = FCVA_mp.Process(target=open_kivy, args=(shared_analysis_dict,shared_metadata_dict))\n kivy_subprocess = FCVA_mp.Process(target=open_kivy, args=(shared_analysis_dict,shared_metadata_dict))\n kivy_subprocess.start()\n\n\n while shared_metadata_dict[\"run_state\"]:\n try:\n # ret, frame = self.source.read()\n # self.what = FCVApool.apply_async(parallelize_cv_func, args=(cv_func_mp, ret, frame, shared_analysis_dict, self.frame_int)) \n #try running mediapipe as a subprocess \n #yikes this is a while loop not if so I spawned a bunch of processess running mediapipe...\n # mediapipe_subprocess = FCVA_mp.Process(target=open_mediapipe, args=(shared_analysis_dict,shared_metadata_dict)) \n # mediapipe_subprocess.start()\n pass\n except Exception as e:\n print(\"Error in run, make sure stream is set. Example: app.source = cv2.VideoCapture(0)\", e)\n\napp = FCVA()\n# # app.source = cv2.VideoCapture(0)\napp.run() \n\n\n'''\nWhat I want people to do:\n\nfrom FCVA import FCVA\n\n@decorator\ntheir basic cv function\n#set the stream source:\napp = FCVA()\napp.source = cv2.VideoCapture(self.device_index)\n\napp.run() #FCVA().run()\n\napp.generate_exe() #FCVA.generate() <--- this will create a pyinstaller exe\n\n'''","repo_name":"ShootingStarDragon/Kivy-mediapipe-multiprocessing","sub_path":"FINALTEST_mediapipe_kivy_multiprocessing.py","file_name":"FINALTEST_mediapipe_kivy_multiprocessing.py","file_ext":"py","file_size_in_byte":14450,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"15"} +{"seq_id":"9085843635","text":"# -*- coding: utf-8 -*-\n\"\"\"varios_2.py\"\"\"\n\nfrom C_Simbolo import C_Simbolo\nfrom binance.client import Client, BinanceRequestException, BinanceAPIException\nfrom binance.exceptions import BinanceAPIException\n\n\ndef cantMonedas(client:Client, moneda: str) -> float:\n \"\"\"cantidad de monedas de una cierta moneda.\"\"\"\n\n for i in client.get_account()['balances']:\n if(i['asset'] != moneda):\n continue\n\n return float(i['free'])\n\n return -1\n\n\ndef cantMonedas_1(cuenta:dict, moneda: str) -> dict:\n \"\"\"cantidad de monedas de una cierta moneda en una cierta cuenta.\"\"\"\n \n client = Client(\n api_key = cuenta['api_key'], \n api_secret = cuenta['secret_key']\n )\n\n try:\n\n client = client.get_account()\n\n except BinanceAPIException as error:\n \n return {\n 'status': ['error', 'Binance, {}'.format(error)], \n 'out': -1\n }\n\n for i in client['balances']:\n if(i['asset'] != moneda):\n continue\n\n return {'status': ['ok', ''], 'out': float(i['free'])}\n\n return {\n 'status': ['error', 'Binance, No encontré la moneda {}'.format(moneda)], \n 'out': -1\n }\n \n\ndef cancelarOrdenesPendientes(cuenta:dict, simbolo:str) -> bool:\n \"\"\"\n Intenta cancelar todas las ordenes pendientes de un simbolo. Donde:\n * client es el cliente de binance (ver \n https://python-binance.readthedocs.io/en/latest/binance.html#module-binance.client ).\n * simbolo, es el simbolo de las pendientes que se desean cerrar.\n \"\"\"\n \n client = Client(\n api_key = cuenta['api_key'], \n api_secret = cuenta['secret_key']\n )\n\n orders = client.get_open_orders(symbol = simbolo)\n\n for i in orders:\n\n result = client.cancel_order(\n symbol = simbolo, \n orderId = i['orderId']\n )\n \n return True\n \n\ndef abrirInstantanea(\n cuenta:dict, \n simbolo: str, \n cantidadTotal:float,\n inversion:float, # viene de 0 a 100\n riesgoPorcentual:float\n ) -> dict:\n \"\"\"\n Intenta meter una orden instantanea a mercado.\n\n inversion:float, Nos dice cuanto porcentaje (de 0 a 100) van a ser usados de la cantidadTotal\n\n riesgoPorcentual: 1 / Abs(OpenPrice - stopLoss)\n\n \"\"\"\n \n client = Client(\n api_key = cuenta['api_key'], \n api_secret = cuenta['secret_key']\n )\n\n obj_simbolo = C_Simbolo(simbolo = simbolo)\n\n usd = cantidadTotal * inversion / 100.0\n\n cant_monedas = usd * riesgoPorcentual\n\n dict_cant = obj_simbolo.formatear_cant_monedas(cant_monedas)\n \n if(dict_cant['status'][0] == 'error'):\n\n return {\n 'status': [\n 'error',\n 'error, {}. {}, cant_monedas {}.'.format(\n dict_cant['status'][1],\n obj_simbolo.Name(),\n dict_cant['out']\n )\n ]\n }\n\n try:\n\n order = client.order_market_buy(\n symbol = simbolo,\n quantity = dict_cant['out']\n )\n \n except BinanceRequestException as error:\n return {'status': ['error',error]}\n except BinanceAPIException as error:\n return {'status': ['error',error]}\n\n return {\n 'status': [\n 'ok',\n 'Compra de {} {} satisfactoria.'.format(\n dict_cant['out'], \n simbolo\n )\n ]\n }\n\n\ndef cerrarPosicion(cuenta:dict, obj_simbolo:C_Simbolo) -> dict:\n \"\"\"Intenta cerrar posicion.\"\"\"\n\n dict_cant = cantMonedas_1(cuenta, obj_simbolo.get_monedaBase())\n\n if(dict_cant['status'][0] == 'error'):\n return dict_cant\n \n dict_cant = obj_simbolo.formatear_cant_monedas(dict_cant['out'])\n \n if((dict_cant['status'][0] == 'error')):\n\n return {\n 'status': [\n 'error',\n 'error, {}. {}, cant_monedas {}.'.format(\n dict_cant['status'][1],\n obj_simbolo.Name(),\n dict_cant['out']\n )\n ]\n }\n\n if(dict_cant['out'] == 0):\n \n return {\n 'status': [\n 'ok', \n 'No encontre posicion abierta para {}.'.format(\n obj_simbolo.Name()\n )\n ]\n }\n\n client = Client(\n api_key = cuenta['api_key'], \n api_secret = cuenta['secret_key']\n )\n\n try:\n order = client.order_market_sell(\n symbol = obj_simbolo.Name(),\n quantity = dict_cant['out']\n )\n \n except BinanceRequestException as error:\n return {\n 'status': [\n 'error', \n 'Error con cierre de {}. {}'.format(\n obj_simbolo.Name(), \n str(error)\n )\n ]\n }\n\n except BinanceAPIException as error:\n return {\n 'status': [\n 'error', \n 'Error con cierre de {}. {}'.format(\n obj_simbolo.Name(), \n str(error)\n )\n ]\n }\n \n return {\n 'status': ['ok', 'Posicion {} cerrada.'.format(obj_simbolo.Name())]\n }\n\n\ndef ponerOrdenPendiente(\n cuenta:dict, \n simbolo:str, \n precioApertura:float, \n cant_monedas:float\n ) -> dict:\n \"\"\"Intenta poner una orden pendiente.\"\"\"\n \n client = Client(\n api_key = cuenta['api_key'], \n api_secret = cuenta['secret_key']\n )\n\n obj_simbolo = C_Simbolo(simbolo = simbolo)\n\n dict_precio = obj_simbolo.formatear_precio(\n precioApertura\n )\n \n if(dict_precio['status'][0] == 'error'):\n\n return {\n 'status': [\n 'error', \n 'error, {}. {}, precio {}.'.format(\n dict_precio['status'][1],\n obj_simbolo.Name(),\n dict_precio['out']\n )\n ]\n }\n\n dict_precio['out'] = '{:.8f}'.format(dict_precio['out'])\n\n dict_cant = obj_simbolo.formatear_cant_monedas(cant_monedas)\n \n if(dict_cant['status'][0] == 'error'):\n\n return {\n 'status': [\n 'error',\n 'error, {}. {}, cant_monedas {}, precio {}.'.format(\n dict_cant['status'][1],\n obj_simbolo.Name(), \n dict_cant['out'], \n dict_precio['out']\n )\n ]\n }\n\n try:\n\n order = client.order_limit_buy(\n symbol = obj_simbolo.Name(),\n quantity = dict_cant['out'],\n price = str(dict_precio['out'])\n )\n \n except BinanceAPIException as error:\n\n return {\n 'status': [\n 'error',\n 'error, {}. {}, cant_monedas {}, precio {}.'.format(\n error,\n obj_simbolo.Name(), \n dict_cant['out'], \n dict_precio['out']\n )\n ]\n }\n\n return {\n 'status': [\n 'ok',\n \"Orden {} puesta por {} {} en {} {}, \".format( \n order['type'], \n order['origQty'],\n obj_simbolo.Simbol_info()['baseAsset'], \n order['price'],\n obj_simbolo.Simbol_info()['quoteAsset']\n )\n ]\n }\n","repo_name":"jfdelosrios/binance_func","sub_path":"binance_func.py","file_name":"binance_func.py","file_ext":"py","file_size_in_byte":8386,"program_lang":"python","lang":"es","doc_type":"code","stars":0,"dataset":"github-code","pt":"15"} +{"seq_id":"2170084888","text":"from PyQt5.QtWidgets import *\nfrom PyQt5 import uic\nclass MyGui(QMainWindow):\n def __init__(self):\n super(MyGui, self).__init__()\n\n uic.loadUi(\"SERVER UI.ui\", self)\n self.show()\n\n\n def main(self):\n app = QApplication([])\n window = MyGui()\n app.exec_()\n\n","repo_name":"vurudi/SERVER-CHAT-APP","sub_path":"clientgui.py","file_name":"clientgui.py","file_ext":"py","file_size_in_byte":301,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"15"} +{"seq_id":"32833190628","text":"#!/usr/bin/env python3\n# -*- coding: utf-8 -*-\n\"\"\"\nCreated on Mon May 2 20:07:22 2022\n\nCompare E-MPL with Gaussian noise and E-MPL with empirical noise\n\n@author: dliu\n\"\"\"\n\nimport numpy as np\nimport matplotlib.pyplot as plt\nimport sys \nsys.path.append(\"..\") \nimport torch\nimport numpy as np\nimport matplotlib.pyplot as plt\nfrom scipy.interpolate import interp1d\nfrom scipy.stats import norm\n\nfrom misc import parameters\nfrom utils import get_dataset, get_cond_noise, get_inter_grid\n\ndevice = torch.device(\"cuda:0\" if torch.cuda.is_available() else \"cpu\")\nparams = parameters(data_type='Saddle_high', n_trainset=20, kx=1, ks=10, x_lower_bound=-1, lr=5e-4)\n\ndata_train_pathes = params.data_pathes[:params.n_trainset]\ndata_test_pathes = params.data_pathes[params.n_trainset:params.n_trainset+80]\n\nbins_x = params.bins_x\nbins_s = params.bins_s\nbins_u = params.bins_u\n\nx_lower_bound = params.x_lower_bound\nkx = params.kx\nks = params.ks\n\n### load model for ODE(x and sigma)\nfrom model import model_f_saddle\nmodel_f = model_f_saddle().to(device)\nmodel_f.load_state_dict(torch.load(params.model_f_path))\n\n### load model for std and mean\nfrom model import model_std_mean_saddle\nmodel_H = model_std_mean_saddle().to(device)\nmodel_H.load_state_dict(torch.load(params.model_std_mean_path))\n\n### load model for distribution of noise in sigma\nfrom model import model_fs_dist_saddle\nmodel_K = model_fs_dist_saddle().to(device)\nmodel_K.load_state_dict(torch.load(params.model_dist_path))\n\n\ndef get_eps(data_pathes, model_f):\n ### load data ###\n x1, x2, s1, s2, diff_x, diff_s, dt_x, dt_s = \\\n get_dataset(data_pathes, x_lower_bound=x_lower_bound, kx=kx, ks=ks, resample=False)\n \n ### predict numerical derivative\n txs = torch.tensor(np.c_[np.ones_like(s1),x1,s1], dtype=torch.float32).to(device)\n numerical = model_f(txs).cpu().detach().numpy()\n \n ### s2 = s1+fs*dt+eps, then we can get the empirical distribution of eps under each condition\n eps = (s2 - (s1 + numerical[:,[-1]]*dt_s))/dt_s**.5\n return x1, s1, eps\n\n\ndef get_distribution(x,s,unif):\n x_obs = np.repeat(x, bins_u, axis=0)\n s_obs = np.repeat(s, bins_u, axis=0)\n unif_obs = np.repeat(unif[:,None], s.shape[0], axis=1).T.reshape(-1,1)\n \n obs = np.c_[x_obs, s_obs, unif_obs] \n obs_tensor = torch.tensor(obs, dtype=torch.float32).to(device)\n \n emp_estimated = model_K(obs_tensor).cpu().detach().numpy()\n \n return obs_tensor.cpu().numpy(), emp_estimated\n\ndef get_cons_std(data_train_pathes):\n x1_train, s1_train, eps_train = get_eps(data_train_pathes, model_f)\n x_inter_train, s_inter_train = get_inter_grid(x1_train[:,0], s1_train[:,0], bins_x, bins_s)\n _, _, cond_std, cond_mean, _, unif = get_cond_noise(eps_train, x1_train, s1_train, x_inter_train, s_inter_train, shape=[bins_x, bins_s, bins_u])\n return cond_std, cond_mean, x_inter_train, s_inter_train, unif\n\n\ndef get_samples_grid(eps, x1, s1, x_inter, s_inter, shape, n=30):\n bins_x, bins_s, bins_u = shape\n\n samp = []\n for i in range(bins_x):\n samp.append([])\n for j in range(bins_s):\n x_idx_ = x1[:,[0]]>=x_inter\n x_idx = x_idx_.sum(axis=1)-1\n \n s_idx_ = s1[:,[0]]>=s_inter\n s_idx = s_idx_.sum(axis=1)-1\n \n both_idx = np.logical_and(x_idx==i, s_idx==j)\n \n if both_idx.sum()>n: ## less than 100 data has no statistical meaning\n eps_sample = eps.flatten()[both_idx]\n samp[-1].append(eps_sample)\n else:\n samp[-1].append([])\n print('{}/{} has done!'.format(i,bins_x))\n \n return samp\n\nfrom scipy.interpolate import interp1d\nimport statsmodels.distributions.empirical_distribution as edf\n###https://stackoverflow.com/questions/44132543/python-inverse-empirical-cumulative-distribution-function-ecdf\ndef inverted_edf(unif, eps_sample):\n sample_edf = edf.ECDF(eps_sample)\n \n slope_changes = sorted(set(eps_sample))\n \n sample_edf_values_at_slope_changes = [sample_edf(item) for item in slope_changes]\n \n slope_changes.insert(0,2*slope_changes[0]-slope_changes[1])\n sample_edf_values_at_slope_changes.insert(0,0)\n \n return sample_edf_values_at_slope_changes, slope_changes\n\ndef get_inverted_cdf(x, y, unif):\n y_pred = interp1d(x, y)\n return y_pred(unif)\n\ndef Wasserstein_dist(f1, f2, unif, p=1):\n dx = unif[1]-unif[0]\n dist = ( np.sum(np.abs(f1-f2)**p, axis=1)*dx )**(1/p)\n return dist\n\n\nif __name__==\"__main__\":\n\n x1, x2, s1, s2, diff_x, diff_s, dt_x, dt_s = \\\n get_dataset(data_train_pathes, x_lower_bound=x_lower_bound, kx=kx, ks=ks, resample=False)\n x_inter_train, s_inter_train = get_inter_grid(x1[:,0], s1[:,0], bins_x, bins_s)\n x_inter = x_inter_train\n s_inter = s_inter_train\n \n middle_x = x_inter[:-1]+(x_inter[1]-x_inter[0])/2\n middle_s = s_inter[:-1]+(s_inter[1]-s_inter[0])/2\n \n x_, s_ = np.meshgrid(middle_x,middle_s,indexing='ij')\n unif = np.linspace(0,1,bins_u+2)[1:-1]\n obs, emp_estimated = get_distribution(x_.flatten(), s_.flatten(), unif)\n emp_train = emp_estimated.reshape([bins_x,bins_s,bins_u])\n \n x1_test, s1_test, eps_test = get_eps(data_test_pathes, model_f)\n samp = get_samples_grid(eps_test, x1_test, s1_test, x_inter, s_inter, shape=[bins_x, bins_s, bins_u], n=200)\n \n norm_train = np.zeros([bins_x, bins_s, bins_u])\n emp_test = np.zeros([bins_x, bins_s, bins_u])\n compare = []\n for i in range(len(samp)):\n for j in range(len(samp[1])):\n samples = samp[i][j]\n if len(samples)>0:\n compare.append([])\n \n point = torch.tensor(np.c_[1, middle_x[i], middle_s[j]],dtype=torch.float32).to(device)\n std, mean = model_H(point).cpu().detach().numpy().flatten()\n norm_train[i,j,:] = norm.ppf(unif, loc=mean, scale=std)\n \n unif_, samples_ = inverted_edf(unif, samples)\n emp_test[i,j,:] = get_inverted_cdf(unif_, samples_, unif)\n \n compare[-1].append(emp_train[i,j,:])\n compare[-1].append(norm_train[i,j,:])\n compare[-1].append(emp_test[i,j,:])\n \n compare = np.array(compare)\n \n idx = 5\n plt.figure(figsize=[10,8])\n fig = plt.plot(unif, compare[idx,:,:].T)\n plt.legend(fig, ['empirical i-cdf train','normal i-cdf train','empirical i-cdf test'])\n plt.title('inverse cdf comparison')\n\n p = 1\n W_dist_norm = Wasserstein_dist(compare[:,1,:], compare[:,2,:], unif, p)\n W_dist_pred = Wasserstein_dist(compare[:,0,:], compare[:,2,:], unif, p)\n print('W{} normal distance: {}'.format(p, np.mean(W_dist_norm)))\n print('W{} empirical distance: {}'.format(p, np.mean(W_dist_pred)))\n\n p = 2\n W_dist_norm = Wasserstein_dist(compare[:,1,:], compare[:,2,:], unif, p)\n W_dist_pred = Wasserstein_dist(compare[:,0,:], compare[:,2,:], unif, p)\n print('W{} normal distance: {}'.format(p, np.mean(W_dist_norm)))\n print('W{} empirical distance: {}'.format(p, np.mean(W_dist_pred)))\n \n # plt.figure()\n # plt.scatter(np.arange(W_dist_pred.shape[0]), W_dist_pred, s=1, label='W predict dist')\n # plt.scatter(np.arange(W_dist_norm.shape[0]), W_dist_norm, s=1, label='W normal dist')\n # plt.legend()","repo_name":"lindliu/Hybrid","sub_path":"Example_Saddle/compare_H_K_Saddle.py","file_name":"compare_H_K_Saddle.py","file_ext":"py","file_size_in_byte":7346,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"15"} +{"seq_id":"21525320829","text":"import cgitb as _cgitb\nimport json as _json\nimport logging as _log\nimport pathlib as _pl\nimport shutil as _sh\nimport time as _time\nimport typing as _tp\nimport unittest.mock as _mock\n\nfrom PyQt5 import QtWidgets as _widgets\n\nimport trnsysGUI.connection.singlePipeConnection as _spc\nimport trnsysGUI.hydraulicLoops.model as _hlm\nimport trnsysGUI.internalPiping as _ip\nimport trnsysGUI.massFlowSolver.networkModel as _mfn\nimport trnsysGUI.storageTank.widget as _st\n\n# Sometimes PyQT crashes only returning with quite a cryptic error code. Sometimes, again, we can get\n# a more helpful stack trace using the cgitb module.\n_cgitb.enable(format=\"text\")\n\n\nclass _StrictMock:\n def __init__(self, **kwargs):\n self.__dict__.update(kwargs)\n\n\nclass TestStorageTank:\n DATA_DIR_PATH = _pl.Path(__file__).parent / \"data\"\n ACTUAL_DIR_PATH = DATA_DIR_PATH / \"actual\"\n EXPECTED_DIR_PATH = DATA_DIR_PATH / \"expected\"\n LEGACY_JSON_PATH = DATA_DIR_PATH / \"storageTankOldestFormat.json\"\n\n def testDeserializeJsonFromLegacyFormatAndSerialize(\n self, tmp_path, qtbot # pylint: disable=invalid-name # /NOSONAR\n ):\n expectedPath = self.EXPECTED_DIR_PATH / \"storageTankNewestFormat.json\"\n expectedStorageTankJson = expectedPath.read_text()\n\n logger = _log.getLogger(\"root\")\n (\n editorMock,\n objectsNeededToBeKeptAliveWhileTanksAlive, # pylint: disable=unused-variable\n ) = self._createDiagramViewMocksAndOtherObjectsToKeepAlive(logger, tmp_path, qtbot)\n\n legacyJson = self.LEGACY_JSON_PATH.read_text()\n storageTank = self._deserializeStorageTank(legacyJson, editorMock)\n\n serializedStorageTank = storageTank.encode()[1]\n actualStorageTankJson = _json.dumps(serializedStorageTank, indent=4, sort_keys=True)\n\n assert actualStorageTankJson == expectedStorageTankJson\n\n self._deserializeStorageTank(actualStorageTankJson, editorMock)\n\n @staticmethod\n def _deserializeStorageTank(storageTankLegacyJson, editorMock):\n legacySerializedStorageTank = _json.loads(storageTankLegacyJson)\n storageTank = _st.StorageTank(\n trnsysType=\"StorageTank\",\n editor=editorMock,\n displayNamePrefix=legacySerializedStorageTank[\"BlockName\"],\n ) # pylint: disable=no-member\n\n blocks = []\n storageTank.decode(legacySerializedStorageTank, blocks)\n\n return storageTank\n\n def testExportDdck(self, qtbot): # pylint: disable=invalid-name\n self._deleteAndRecreateEmptyActualDir()\n\n logger = _log.getLogger(\"root\")\n (\n editorMock,\n objectsNeededToBeKeptAliveWhileTanksAlive, # pylint: disable=unused-variable\n ) = self._createDiagramViewMocksAndOtherObjectsToKeepAlive(logger, self.ACTUAL_DIR_PATH, qtbot)\n\n legacyJson = self.LEGACY_JSON_PATH.read_text()\n storageTank = self._deserializeStorageTank(legacyJson, editorMock)\n\n hydraulicLoops = _hlm.HydraulicLoops([])\n self._setupExternalConnectionMocks(storageTank, hydraulicLoops)\n\n storageTank.setHydraulicLoops(hydraulicLoops)\n\n storageTank.exportDck()\n\n actualDdckPath = self.ACTUAL_DIR_PATH / \"ddck\" / \"StorageTank7701\" / \"TesDhw.ddck\"\n actualDdckContent = actualDdckPath.read_text()\n print(actualDdckContent)\n\n expectedDdckContent = (self.EXPECTED_DIR_PATH / \"TesDhw.ddck\").read_text()\n\n assert actualDdckContent == expectedDdckContent\n\n def _deleteAndRecreateEmptyActualDir(self):\n if self.ACTUAL_DIR_PATH.exists():\n _sh.rmtree(self.ACTUAL_DIR_PATH)\n while self.ACTUAL_DIR_PATH.exists():\n _time.sleep(0.5)\n self.ACTUAL_DIR_PATH.mkdir()\n\n @classmethod\n def _setupExternalConnectionMocks(cls, storageTank: _st.StorageTank, hydraulicLoops: _hlm.HydraulicLoops) -> None:\n for i, heatExchanger in enumerate(storageTank.heatExchangers):\n externalFromPortConnection = cls._createConnectionMock(f\"hx{i}ExtFromPortConn\", toPort=heatExchanger.port1)\n heatExchanger.port1.connectionList.append(externalFromPortConnection)\n\n externalToPortConnection = cls._createConnectionMock(f\"hx{i}ExtToPortConn\", fromPort=heatExchanger.port2)\n heatExchanger.port2.connectionList.append(externalToPortConnection)\n\n cls._addLoop(externalFromPortConnection, externalToPortConnection, i, hydraulicLoops, namePrefix=\"hx\")\n\n for i, directPortPair in enumerate(storageTank.directPortPairs):\n externalFromPortConnection = cls._createConnectionMock(\n f\"dpp{i}ExtFromPortConn\", toPort=directPortPair.fromPort\n )\n directPortPair.fromPort.connectionList.append(externalFromPortConnection)\n\n externalToPortConnection = cls._createConnectionMock(f\"dpp{i}ExtToPortConn\", fromPort=directPortPair.toPort)\n directPortPair.toPort.connectionList.append(externalToPortConnection)\n\n cls._addLoop(externalFromPortConnection, externalToPortConnection, i, hydraulicLoops, namePrefix=\"dp\")\n\n @classmethod\n def _addLoop(cls, externalFromPortConnection, externalToPortConnection, i, hydraulicLoops, namePrefix):\n fluid = _hlm.Fluids.BRINE if i % 2 == 0 else _hlm.Fluids.WATER\n connections = [externalFromPortConnection, externalToPortConnection]\n name = _hlm.UserDefinedName(f\"{namePrefix}Loop{i}\")\n loop = _hlm.HydraulicLoop(name, fluid, useLoopWideDefaults=True, connections=connections)\n hydraulicLoops.addLoop(loop)\n\n @staticmethod\n def _createConnectionMock(\n displayName: str, fromPort=_StrictMock(), toPort=_StrictMock()\n ) -> _spc.SinglePipeConnection:\n modelPipe = _mfn.Pipe(\n _mfn.PortItem(\"In\", _mfn.PortItemDirection.INPUT), _mfn.PortItem(\"Out\", _mfn.PortItemDirection.OUTPUT)\n )\n\n def getInternalPiping() -> _ip.InternalPiping:\n return _ip.InternalPiping([modelPipe], {modelPipe.fromPort: fromPort, modelPipe.toPort: toPort})\n\n def getModelPipe(portItemType: _mfn.PortItemType) -> _mfn.Pipe:\n assert portItemType == _mfn.PortItemType.STANDARD\n\n return modelPipe\n\n mock = _StrictMock(\n displayName=displayName,\n getDisplayName=lambda: displayName,\n fromPort=fromPort,\n toPort=toPort,\n modelPipe=modelPipe,\n getModelPipe=getModelPipe,\n getInternalPiping=getInternalPiping,\n hasDdckPlaceHolders=lambda: False,\n shallRenameOutputTemperaturesInHydraulicFile=lambda: False,\n )\n\n return _tp.cast(_spc.SinglePipeConnection, mock)\n\n @staticmethod\n def _createDiagramViewMocksAndOtherObjectsToKeepAlive(logger, projectFolder, bot):\n mainWindow = _widgets.QMainWindow()\n\n bot.addWidget(mainWindow)\n\n editorMock = _widgets.QWidget(parent=mainWindow)\n editorMock.connectionList = []\n editorMock.logger = logger\n editorMock.trnsysObj = []\n editorMock.projectFolder = str(projectFolder)\n editorMock.splitter = _mock.Mock(name=\"splitter\")\n editorMock.idGen = _mock.Mock(\n name=\"idGen\",\n spec_set=[\n \"getID\",\n \"getTrnsysID\",\n \"getStoragenTes\",\n \"getStorageType\",\n \"getConnID\",\n ],\n )\n editorMock.moveDirectPorts = True\n editorMock.editorMode = 1\n editorMock.snapGrid = False\n editorMock.alignMode = False\n\n editorMock.idGen.getID = lambda: 7701\n editorMock.idGen.getTrnsysID = lambda: 7702\n editorMock.idGen.getStoragenTes = lambda: 7703\n editorMock.idGen.getStorageType = lambda: 7704\n editorMock.idGen.getConnID = lambda: 7705\n\n graphicsScene = _widgets.QGraphicsScene(parent=editorMock)\n editorMock.diagramScene = graphicsScene\n\n mainWindow.setCentralWidget(editorMock)\n mainWindow.showMinimized()\n\n return editorMock, [mainWindow, graphicsScene]\n","repo_name":"SPF-OST/pytrnsys_gui","sub_path":"tests/trnsysGUI/testStorageTank.py","file_name":"testStorageTank.py","file_ext":"py","file_size_in_byte":8073,"program_lang":"python","lang":"en","doc_type":"code","stars":3,"dataset":"github-code","pt":"15"} +{"seq_id":"15697468298","text":"import gym\nimport tensorflow as tf\nimport numpy as np\n\nfrom stable_baselines import logger\nfrom stable_baselines.ppo2 import PPO2\nfrom stable_baselines.ppo2.ppo2 import swap_and_flatten\n\nfrom stable_baselines.common.callbacks import BaseCallback\nfrom stable_baselines.gasil.adversary import TransitionClassifier\n# from stable_baselines.common.mpi_adam import MpiAdam\n\nfrom stable_baselines.gasil.buffer import RewardBuffer\n# from stable_baselines.common import dataset\nfrom stable_baselines.common.tf_util import total_episode_reward_logger\nfrom tensorboard.plugins.hparams import api as hp\n\n\n\n# from stable_baselines.common import explained_variance, ActorCriticRLModel, SetVerbosity, TensorboardWriter, dataset\n\n\nclass GASIL(PPO2):\n \"\"\"\n Generative Adversarial Self-Imitation Learning (GASIL)\n\n :param policy: (ActorCriticPolicy or str) The policy model to use (MlpPolicy, CnnPolicy, CnnLstmPolicy, ...)\n :param env: (Gym environment or str) The environment to learn from (if registered in Gym, can be str)\n :param gamma: (float) Discount factor\n :param n_steps: (int) The number of steps to run for each environment per update\n (i.e. batch size is n_steps * n_env where n_env is number of environment copies running in parallel)\n :param ent_coef: (float) Entropy coefficient for the loss calculation\n :param learning_rate: (float or callable) The learning rate, it can be a function\n :param vf_coef: (float) Value function coefficient for the loss calculation\n :param max_grad_norm: (float) The maximum value for the gradient clipping\n :param lam: (float) Factor for trade-off of bias vs variance for Generalized Advantage Estimator\n :param nminibatches: (int) Number of training minibatches per update. For recurrent policies,\n the number of environments run in parallel should be a multiple of nminibatches.\n :param noptepochs: (int) Number of epoch when optimizing the surrogate\n :param cliprange: (float or callable) Clipping parameter, it can be a function\n :param cliprange_vf: (float or callable) Clipping parameter for the value function, it can be a function.\n This is a parameter specific to the OpenAI implementation. If None is passed (default),\n then `cliprange` (that is used for the policy) will be used.\n IMPORTANT: this clipping depends on the reward scaling.\n To deactivate value function clipping (and recover the original PPO implementation),\n you have to pass a negative value (e.g. -1).\n :param verbose: (int) the verbosity level: 0 none, 1 training information, 2 tensorflow debug\n :param tensorboard_log: (str) the log location for tensorboard (if None, no logging)\n :param _init_setup_model: (bool) Whether or not to build the network at the creation of the instance\n :param policy_kwargs: (dict) additional arguments to be passed to the policy on creation\n :param full_tensorboard_log: (bool) enable additional logging when using tensorboard\n WARNING: this logging can take a lot of space quickly\n :param seed: (int) Seed for the pseudo-random generators (python, numpy, tensorflow).\n If None (default), use random seed. Note that if you want completely deterministic\n results, you must set `n_cpu_tf_sess` to 1.\n :param n_cpu_tf_sess: (int) The number of threads for TensorFlow operations\n If None, the number of cpu of the current machine will be used.\n\n :param use_gasil: (bool) Whether or not to use GASIL Reward for learning\n :param sil_samples: (int) Max Number of trajectories stored in SIL Buffer\n :param g_step: (int) number of steps to train policy in each epoch\n (Train Discriminator every after n policy updates)\n :param adversary_step: (int) number of steps to train discriminator in each epoch\n :param adversary_entcoeff: (float) the adversary entropy coefficient (1e-3)\n :param sil_alpha: (float) the weight of the Discriminator Reward.\n 1 => just D (pure GASIL), 0 => just real reward (pure PPO)\n :param adversary_stepsize: (float) the Adversarys stepsize on update\n :param adversary_hidden_size: (int) the hidden dimension for the Discriminator Network (100)\n \"\"\"\n # sil_update=1, sil_value=0.01, sil_alpha=0.6, sil_beta=0.1,\n\n def __init__(self, policy, env, gamma=0.99, n_steps=128, ent_coef=0.01, learning_rate=2.5e-4, vf_coef=0.5,\n max_grad_norm=0.5, lam=0.95, nminibatches=4, noptepochs=4, cliprange=0.2, cliprange_vf=None,\n verbose=0, tensorboard_log=None, _init_setup_model=True, policy_kwargs=None,\n full_tensorboard_log=False, seed=None, n_cpu_tf_sess=None,\n adversary_hidden_size=100, adversary_entcoeff=1e-3, sil_alpha=1.0,\n g_step=3, adversary_step=1, adversary_stepsize=3e-4, sil_samples=512,\n use_gasil=True, env_name=\"\", **kwargs):\n\n # super().__init__(policy, env, verbose=verbose, _init_setup_model=False, **kwargs)\n logger.log(\"Init\")\n super().__init__(policy, env, gamma=gamma, n_steps=n_steps,\n ent_coef=ent_coef, learning_rate=learning_rate,\n vf_coef=vf_coef, max_grad_norm=max_grad_norm,\n lam=lam, nminibatches=nminibatches,\n noptepochs=noptepochs, cliprange=cliprange,\n cliprange_vf=cliprange_vf, verbose=verbose,\n tensorboard_log=tensorboard_log,\n _init_setup_model=False, policy_kwargs=policy_kwargs,\n full_tensorboard_log=full_tensorboard_log,\n seed=seed, n_cpu_tf_sess=n_cpu_tf_sess, **kwargs)\n\n # GAIL Params\n self.use_gasil = use_gasil\n self.g_step = g_step # TODO: use this\n\n self.sil_alpha = sil_alpha\n self.sil_samples = sil_samples\n self.buffer = RewardBuffer(size=sil_samples)\n\n self.adversary = None\n self.adversary_step = adversary_step\n self.adversary_stepsize = adversary_stepsize\n self.adversary_entcoeff = adversary_entcoeff\n self.adversary_hidden_size = adversary_hidden_size\n\n # For HParam Logging\n self.env_name = env_name\n\n\n # Keep Track of Episode Reward (set, update, log from Callback)\n self.real_reward = [] # Env Reward Buffer for Adapted Rollouts\n self.d_reward = [] # Discriminator Reward Buffer for Adapted Rollouts\n self.accumulated_env_reward = np.zeros((self.n_envs,)) # []\n\n if _init_setup_model: # TODO: revert changes to PPO model setup\n self.setup_model()\n\n with self.graph.as_default():\n # self.set_random_seed(self.seed)\n # self.sess = tf_util.make_session(num_cpu=self.n_cpu_tf_sess, graph=self.graph)\n\n self.adversary = TransitionClassifier(self.observation_space, self.action_space,\n self.adversary_hidden_size, self.sess,\n self.train_model.obs_ph, self.action_ph,\n stepsize=self.adversary_stepsize,\n entcoeff=self.adversary_entcoeff)\n # tf_util.initialize(sess=self.sess)\n\n self.params.extend(self.adversary.get_trainable_variables())\n tf.global_variables_initializer().run(session=self.sess) # pylint: disable=E1101\n self.summary = tf.summary.merge_all() # TODO test if needed / usable\n\n self.adversary.setup_trainer()\n\n # with tf.variable_scope(\"DiscriminatorAdam\", reuse=False): # TODO: Move into Adversary\n # self.d_adam = MpiAdam(self.adversary.get_trainable_variables(), sess=self.sess)\n # self.d_adam.sync()\n\n def _train_step(self, learning_rate, cliprange, obs, returns, masks, actions, values, neglogpacs, update,\n writer, states=None, cliprange_vf=None):\n \"\"\"\n Training of PPO2 Algorithm\n\n :param learning_rate: (float) learning rate\n :param cliprange: (float) Clipping factor\n :param obs: (np.ndarray) The current observation of the environment\n :param returns: (np.ndarray) the rewards\n :param masks: (np.ndarray) The last masks for done episodes (used in recurent policies)\n :param actions: (np.ndarray) the actions\n :param values: (np.ndarray) the values\n :param neglogpacs: (np.ndarray) Negative Log-likelihood probability of Actions\n :param update: (int) the current step iteration\n :param writer: (TensorFlow Summary.writer) the writer for tensorboard\n :param states: (np.ndarray) For recurrent policies, the internal state of the recurrent model\n :return: policy gradient loss, value function loss, policy entropy,\n approximation of kl divergence, updated clipping range, training update operation\n :param cliprange_vf: (float) Clipping factor for the value function\n \"\"\"\n # logger.log(\"Train Step from GASIL\")\n advs = returns - values\n advs = (advs - advs.mean()) / (advs.std() + 1e-8)\n td_map = {self.train_model.obs_ph: obs, self.action_ph: actions,\n self.advs_ph: advs, self.rewards_ph: returns,\n self.learning_rate_ph: learning_rate, self.clip_range_ph: cliprange,\n self.old_neglog_pac_ph: neglogpacs, self.old_vpred_ph: values}\n if states is not None:\n td_map[self.train_model.states_ph] = states\n td_map[self.train_model.dones_ph] = masks\n\n expert_obs, expert_acs, _ = self.buffer.sample(len(obs))\n td_map[self.adversary.expert_obs_ph] = expert_obs\n td_map[self.adversary.expert_acs_ph] = expert_acs\n\n if cliprange_vf is not None and cliprange_vf >= 0:\n td_map[self.clip_range_vf_ph] = cliprange_vf\n\n if states is None:\n update_fac = max(self.n_batch // self.nminibatches // self.noptepochs, 1)\n else:\n update_fac = max(self.n_batch // self.nminibatches // self.noptepochs // self.n_steps, 1)\n\n if writer is not None:\n # run loss backprop with summary, but once every 10 runs save the metadata (memory, compute time, ...)\n if self.full_tensorboard_log and (1 + update) % 10 == 0:\n run_options = tf.RunOptions(trace_level=tf.RunOptions.FULL_TRACE)\n run_metadata = tf.RunMetadata()\n summary, policy_loss, value_loss, policy_entropy, approxkl, clipfrac, _ = self.sess.run(\n [self.summary, self.pg_loss, self.vf_loss, self.entropy, self.approxkl, self.clipfrac, self._train],\n td_map, options=run_options, run_metadata=run_metadata)\n writer.add_run_metadata(run_metadata, 'step%d' % (update * update_fac))\n else:\n summary, policy_loss, value_loss, policy_entropy, approxkl, clipfrac, _ = self.sess.run(\n [self.summary, self.pg_loss, self.vf_loss, self.entropy, self.approxkl, self.clipfrac, self._train],\n td_map)\n writer.add_summary(summary, (update * update_fac))\n else:\n policy_loss, value_loss, policy_entropy, approxkl, clipfrac, _ = self.sess.run(\n [self.pg_loss, self.vf_loss, self.entropy, self.approxkl, self.clipfrac, self._train], td_map)\n\n return policy_loss, value_loss, policy_entropy, approxkl, clipfrac\n\n def learn(self, total_timesteps, callback=None, log_interval=100, tb_log_name=\"GASIL\",\n reset_num_timesteps=True):\n callback = LeanAdversaryCallback(verbose=self.verbose)\n return super().learn(\n total_timesteps, callback=callback, log_interval=log_interval,\n tb_log_name='', reset_num_timesteps=reset_num_timesteps)\n\n def write_hparams(self, writer):\n \"\"\"Returns a summary proto buffer holding this experiment\"\"\"\n import hashlib\n from tensorboard.plugins.hparams import api_pb2\n from tensorboard.plugins.hparams import summary\n\n hparams = {\n 'alpha': self.sil_alpha,\n 'buffer': self.sil_samples\n }\n # \"GASIL Evaluation\"\n group_name = hashlib.md5(str(hparams).encode('utf-8')).hexdigest()\n group_name = \"{}:{}_{}\".format(self.env_name, self.sil_samples, self.sil_alpha)\n\n writer.add_summary(summary.experiment_pb(\n hparam_infos=[\n api_pb2.HParamInfo(\n name=\"alpha\", display_name=\"Reward Mixture\", type=api_pb2.DATA_TYPE_FLOAT64,\n domain_interval=api_pb2.Interval(min_value=0.0, max_value=1.0)),\n api_pb2.HParamInfo(\n name=\"buffer\", display_name=\"Imitation Buffer Size\", type=api_pb2.DATA_TYPE_FLOAT64,\n domain_interval=api_pb2.Interval(min_value=64.0, max_value=1024.0))\n ],\n metric_infos=[\n api_pb2.MetricInfo(\n name=api_pb2.MetricName(tag=\"rewards/true_acc_reward\"),\n display_name=\"Accumulated Env Reward\"),\n api_pb2.MetricInfo(\n name=api_pb2.MetricName(tag=\"adversary_loss/mean_reward_in_buffer\"),\n display_name=\"Mean Reward in Buffer\")\n ]\n ))\n writer.add_summary(summary.session_start_pb(hparams=hparams, group_name=group_name))\n writer.flush()\n\n def finish_hparams(self, writer):\n \"\"\"Returns a summary proto buffer holding this experiment\"\"\"\n from tensorboard.plugins.hparams import api_pb2\n from tensorboard.plugins.hparams import summary\n writer.add_summary(summary.session_end_pb(api_pb2.STATUS_SUCCESS))\n writer.flush()\n\n def save(self, save_path, cloudpickle=False):\n # verbose=0, tensorboard_log=None, _init_setup_model=True, full_tensorboard_log=False,\n data = {\n \"gamma\": self.gamma,\n \"n_steps\": self.n_steps,\n \"vf_coef\": self.vf_coef,\n \"ent_coef\": self.ent_coef,\n \"max_grad_norm\": self.max_grad_norm,\n \"learning_rate\": self.learning_rate,\n \"lam\": self.lam,\n \"nminibatches\": self.nminibatches,\n \"noptepochs\": self.noptepochs,\n \"cliprange\": self.cliprange,\n \"cliprange_vf\": self.cliprange_vf,\n \"verbose\": self.verbose,\n \"policy\": self.policy,\n \"observation_space\": self.observation_space,\n \"action_space\": self.action_space,\n \"n_envs\": self.n_envs,\n \"n_cpu_tf_sess\": self.n_cpu_tf_sess,\n \"seed\": self.seed,\n \"_vectorize_action\": self._vectorize_action,\n \"policy_kwargs\": self.policy_kwargs,\n \"adversary_hidden_size\": self.adversary_hidden_size,\n \"adversary_entcoeff\": self.adversary_entcoeff,\n \"g_step\": self.g_step,\n \"adversary_step\": self.adversary_step,\n \"adversary_stepsize\": self.adversary_stepsize,\n \"sil_samples\": self.sil_samples,\n \"use_gasil\": self.use_gasil\n }\n\n params_to_save = self.get_parameters()\n\n self._save_to_file(save_path, data=data, params=params_to_save, cloudpickle=cloudpickle)\n\n\nclass LeanAdversaryCallback(BaseCallback):\n \"\"\"\n A custom callback Updating the Generative Adversarial Self-Imitation Extension\n\n :param verbose: (int) Verbosity level 0: not output 1: info 2: debug\n \"\"\"\n def __init__(self, verbose=0):\n super(LeanAdversaryCallback, self).__init__(verbose)\n # Those variables will be accessible in the callback\n # (they are defined in the base class)\n # The RL model\n # self.model = None # type: BaseRLModel\n # An alias for self.model.get_env(), the environment used for training\n # self.training_env = None # type: Union[gym.Env, VecEnv, None]\n # Number of time the callback was called\n # self.n_calls = 0 # type: int\n # self.num_timesteps = 0 # type: int\n # local and global variables\n # self.locals = None # type: Dict[str, Any]\n # self.globals = None # type: Dict[str, Any]\n # The logger object, used to report things in the terminal\n # self.logger = None # type: logger.Logger\n # # Sometimes, for event callback, it is useful\n # # to have access to the parent object\n # self.parent = None # type: Optional[BaseCallback]\n\n def _on_training_start(self) -> None:\n \"\"\"\n This method is called before the first rollout starts.\n \"\"\"\n w = self.locals['writer']\n self.model.write_hparams(writer=w)\n\n # HP_ALPHA = hp.HParam('alpha', hp.RealInterval(0.0, 1.0))\n # HP_BUFFER = hp.HParam(\"buffer\", hp.IntInterval(64, 1024))\n # # HP_OPTIMIZER = hp.HParam('optimizer', hp.Discrete(['adam', 'sgd']))\n # HP_METRIC = hp.Metric('rewards/true_acc_reward', display_name='Reward')\n #\n # # self.model.sess.run(w.init())\n # self.model.sess.run(hp.hparams_config(\n # hparams=[HP_ALPHA, HP_BUFFER], metrics=[HP_METRIC])\n # )\n # self.model.sess.run(hp.hparams({\n # HP_ALPHA: self.model.sil_alpha,\n # HP_BUFFER: self.model.sil_samples\n # }))\n # self.model.sess.run(w.flush())\n\n def _on_rollout_start(self) -> None:\n \"\"\"\n A rollout is the collection of environment interaction\n using the current policy.\n This event is triggered before collecting new samples.\n \"\"\"\n # self.locals['d_rewards'] = []\n\n # Reset Env Reward Tracker\n # self.model.real_reward = []\n self.model.d_rewards = []\n\n def _on_step(self) -> bool:\n \"\"\"\n This method will be called by the model after each call to `env.step()`.\n\n For child callback (of an `EventCallback`), this will be called\n when the event is triggered.\n\n :return: (bool) If the callback returns False, training is aborted early.\n \"\"\"\n\n observation = self.locals['mb_obs'][-1].copy()\n action = self.locals['clipped_actions']\n reward = self.model.adversary.get_reward(observation, action[0])\n self.model.d_rewards.append(reward[0])\n env_reward = self.locals['rewards']\n\n # Write Detailed Reward Summary\n summary = tf.Summary(value=[\n tf.Summary.Value(tag='rewards/discriminator', simple_value=reward),\n tf.Summary.Value(tag='rewards/environment', simple_value=env_reward[0])\n ])\n self.locals['writer'].add_summary(summary, self.num_timesteps)\n\n # For discounting D rewards after Rollout\n\n if self.num_timesteps % self.model.n_steps == 0:\n\n # Reshabe Discriminator Reward\n d_rewards = np.asarray(self.model.d_rewards, dtype=np.float32)\n mb_rewards = self.locals['mb_rewards'][:]\n mb_rewards.append(self.locals['rewards'])\n mb_rewards = np.asarray(mb_rewards, dtype=np.float32)\n mb_values = np.asarray(self.locals['mb_values'], dtype=np.float32)\n mb_dones = np.asarray(self.locals['mb_dones'], dtype=np.bool)\n\n obs = self.locals['obs']\n states = self.locals['states']\n dones = self.locals['dones']\n last_values = self.model.value(obs, states, dones)\n\n # discount/bootstrap off value fn\n # last_values = self.model.model.value(self.model.obs, self.model.states, self.model.dones)\n d_adv = np.zeros_like(d_rewards)\n d_true_reward = np.copy(d_rewards)\n last_gae_lam = 0\n for step in reversed(range(self.model.n_steps)):\n if step == self.model.n_steps - 1:\n nextnonterminal = 1.0 - dones # self.model.dones\n nextvalues = last_values\n else:\n nextnonterminal = 1.0 - mb_dones[step + 1] # self.d_mb_dones[step + 1]\n nextvalues = mb_values[step + 1] # self.d_mb_values[step + 1]\n mixted_reward = self.model.sil_alpha * d_rewards[step] + (1-self.model.sil_alpha) * mb_rewards[step]\n delta = mixted_reward + self.model.gamma * nextvalues * nextnonterminal - mb_values[step] # self.d_mb_values[step]\n d_adv[step] = last_gae_lam = delta + self.model.gamma * self.model.lam * nextnonterminal * last_gae_lam\n d_returns = d_adv + mb_values\n\n # Write Value to reward summary\n self.locals['writer'].add_summary(tf.Summary(value=[tf.Summary.Value(\n tag='rewards/value', simple_value=np.mean(mb_values, axis=1)[0])\n ]), self.num_timesteps)\n\n d_returns, d_true_reward = map(swap_and_flatten, (d_returns, d_true_reward))\n self.d_returns = d_returns\n self.d_true_reward = d_true_reward\n\n def _on_rollout_end(self) -> None:\n \"\"\"\n This event is triggered before updating the policy.\n \"\"\"\n # logger.log(\"Rollout Ended. Updating Policy and Discriminator\")\n\n # Get Variables\n observations = self.locals['obs']\n actions = self.locals['actions']\n returns = self.locals['returns']\n\n true_rewards = self.locals['true_reward']\n masks = self.locals['masks']\n n_envs = self.model.n_envs # self.locals['n_envs']\n n_steps = self.model.n_steps # self.locals['n_steps']\n writer = self.locals['writer']\n steps = self.num_timesteps\n\n rewards = true_rewards.reshape((n_envs, n_steps))\n masks = masks.reshape((n_envs, n_steps))\n\n # Write Real Env Reward to Tensoboard\n self.model.accumulated_env_reward = total_episode_reward_logger(\n self.model.accumulated_env_reward,\n rewards, masks, writer, steps,\n tag=\"rewards/true_acc_reward\"\n )\n\n # Update Buffer\n self.model.buffer.extend(observations, actions, returns)\n buffer_rewards = [reward for _, _, reward in self.model.buffer.storage]\n\n assert len(observations) == self.model.n_steps\n batch_size = self.model.n_steps // self.model.adversary_step\n d_losses = self.model.adversary.learn(\n observations, actions, self.model.buffer, batch_size\n )\n logger.logkv(\"d_losses\", np.mean(d_losses, axis=1)[0])\n\n # Write Detailed Reward Summary\n writer.add_summary(tf.Summary(value=[tf.Summary.Value(\n tag='adversary_loss/discriminator_loss',\n simple_value=np.mean(d_losses, axis=1)[0])\n ]), self.num_timesteps)\n\n # Overwrite PPO Return & Reward\n if self.model.use_gasil:\n self.locals['true_reward'] = self.d_true_reward # d_rewards\n self.locals['returns'] = self.d_returns # d_rewards\n\n # Write Tensorboard Summary\n summary = tf.Summary(value=[\n tf.Summary.Value(tag='adversary_loss/samples_in_buffer',\n simple_value=len(self.model.buffer)),\n tf.Summary.Value(tag='adversary_loss/mean_reward_in_buffer',\n simple_value=np.mean(buffer_rewards))\n ])\n self.locals['writer'].add_summary(summary, self.num_timesteps)\n","repo_name":"philippaltmann/ASIL","sub_path":"stable_baselines/gasil/gasil.py","file_name":"gasil.py","file_ext":"py","file_size_in_byte":23369,"program_lang":"python","lang":"en","doc_type":"code","dataset":"github-code","pt":"15"} +{"seq_id":"1176936976","text":"# -*- coding: utf-8 -*-\nfrom __future__ import unicode_literals\n\nfrom django.db import models, migrations\n\n\nclass Migration(migrations.Migration):\n\n dependencies = [\n ('sms', '0006_auto_20150414_2257'),\n ]\n\n operations = [\n migrations.CreateModel(\n name='LeaderResponse',\n fields=[\n ('id', models.AutoField(verbose_name='ID', serialize=False, auto_created=True, primary_key=True)),\n ('name', models.CharField(default=b'null', max_length=100)),\n ('numMatches', models.IntegerField(default=0)),\n ('prefs', models.CharField(default=b'null', max_length=300)),\n ('which_login', models.ForeignKey(to='sms.LoginInfo')),\n ],\n ),\n migrations.AddField(\n model_name='memberresponse',\n name='conflicts',\n field=models.CharField(default=b'null', max_length=300),\n ),\n ]\n","repo_name":"asavaris/sms","sub_path":"mysite2/sms/migrations/0007_auto_20150414_2257.py","file_name":"0007_auto_20150414_2257.py","file_ext":"py","file_size_in_byte":945,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"15"} +{"seq_id":"12107122423","text":"import numpy as np\nimport pandas as pd\nimport datetime as dt\nfrom funciones_limpieza import *\nfrom lectura import *\n\n\n\ndef normalizar_emisiones(df):\n df.replace({'US':'UNITED STATES OF AMERICA (THE)',\n 'TRINIDAD & TOBAGO' :'TRINIDAD AND TOBAGO',\n 'VENEZUELA' :'VENEZUELA (BOLIVARIAN REPUBLIC OF)',\n 'CZECH REPUBLIC':'CZECHIA',\n 'NETHERLANDS' :'NETHERLANDS (THE)',\n 'NORTH MACEDONIA' :'REPUBLIC OF NORTH MACEDONIA',\n 'UNITED KINGDOM':'UNITED KINGDOM OF GREAT BRITAIN AND NORTHERN IRELAND (THE)',\n 'RUSSIAN FEDERATION':'RUSSIAN FEDERATION (THE)',\n 'IRAN':'IRAN (ISLAMIC REPUBLIC OF)',\n 'UNITED ARAB EMIRATES': 'UNITED ARAB EMIRATES (THE)',\n 'MIDDLE AFRICA':'CENTRAL AFRICAN REPUBLIC (THE)',\n 'CHINA HONG KONG SAR':'HONG KONG',\n 'PHILIPPINES':'PHILIPPINES (THE)',\n 'SOUTH KOREA':'KOREA (THE REPUBLIC OF)',\n 'TAIWAN':'TAIWAN (PROVINCE OF CHINA)',\n 'VIETNAM':'VIET NAM'\n },inplace=True)#de los 82 paises registados se eliminan 11 registros porque no estan asignados a un pais especifico o es una clasificacion no bien definida\n return df\n\ndef formato_emisiones(df):\n df.rename(columns={'Pais':'country_name'},inplace=True)\n \n df['country_name']=df['country_name'].str.upper()\n \n df.drop([0], axis=0, inplace=True)\n df.drop([\"2021.1\", \"2011-21\", \"2021.2\"], axis=1, inplace=True)\n df=normalizar_emisiones(df)\n #print(df['country_name'].unique())\n lista=comparar_nombre_pais(df)\n df.reset_index(inplace=True)\n falsos=no_paises_filas(lista)\n df.drop(['index'], axis=1,inplace=True)\n #print(f'falsos: {falsos}')\n df=elimimar_filas_incorrectas(falsos, df)\n \n return df\n\ndef limpieza_cap_instalada(df):\n df=trabajar_nulos_ceros_otros(df)\n df.rename(columns={'Pais':'country_name'},inplace=True)\n df.drop(columns=['2021.1','2011-2021','2021.2','1995','1996'],axis=1,inplace=True)\n df['country_name']=df['country_name'].str.upper()\n #df.rename(columns={'Country Name':'country_name','Country Code':'country_code'},inplace=True)\n #print(df)\n #print(df['country_name'].unique())\n df=normalizar_emisiones(df)\n lista=comparar_nombre_pais(df)\n df.reset_index(inplace=True)\n falsos=no_paises_filas(lista)\n df.drop(['index'], axis=1,inplace=True)\n #print(f'falsos: {falsos}')\n df=elimimar_filas_incorrectas(falsos, df)\n \n return df\n \n \n#funcion para agregar id tipo de energia\ndef agregar_column_t_energia(df,tipo_ener):\n tipo_ener.upper()\n if tipo_ener=='SOLAR':\n df.insert(2, 'id_energy', 1)\n elif tipo_ener=='VIENTO' :\n df.insert(2, 'id_energy', 2) \n elif tipo_ener=='CARBON':\n df.insert(2, 'id_energy', 3)\n elif tipo_ener=='PETROLEO':\n df.insert(2, 'id_energy', 4)\n elif tipo_ener=='NUCLEAR':\n df.insert(2, 'id_energy', 5)\n elif tipo_ener=='GAS NATURAL':\n df.insert(2, 'id_energy', 6)\n elif tipo_ener=='GEOTERMICA': \n df.insert(2, 'id_energy', 7)\n elif tipo_ener=='HIDROELECTRICA':\n df.insert(2, 'id_energy', 8)\n else:\n df\n return df\n\"\"\"\nfor i,p in enumerate(df_años['year']):\n cod= df_años.loc[i,'id_year']\n df.loc[df['year']==p,'id_year']=cod\n\n\"\"\"\ndef calculos_petroleo(df):\n #print('en funcion petrole')\n #df=df.astype({'annual_production':'int64'})\n #p=10**(-9)\n #eq_xj=6.11786319999928*p\n twh=588.4407483972509\n for i, ele in enumerate(df['annual_production']): \n totaltwh=df.loc[i,'annual_production']*twh\n df.loc[i,'annual_production']=totaltwh\n return(df)\n\ndef conversion_exaj_twh(df):\n #print('desde conversion')\n #print(df.dtypes)\n twh=227.77778 #equivalencia en twh de un joule\n #print(twh)\n for i, ele in enumerate(df['annual_production']):\n s=df.loc[i,'annual_production']\n #print(f's:{s}')\n prod_twh=df.loc[i,'annual_production']*twh\n #print(prod_twh)\n df.loc[i,'annual_production']=prod_twh\n \n\n return(df) \n\n # 8765 MBOE / 588.4407483972509","repo_name":"HX-GPosse/Proyecto_Grupal_Grupo05","sub_path":"Emisiones/funciones_limpieza2.py","file_name":"funciones_limpieza2.py","file_ext":"py","file_size_in_byte":4155,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"15"} +{"seq_id":"43606220986","text":"import sys; input = sys.stdin.readline\n\nN, M = map(int, input().split())\nary = [list(input().rstrip()) for _ in range(N)]\n\nresult = -1\nfor i in range(N):\n for j in range(M):\n for k in range(-N, N):\n for m in range(-M, M):\n if k == 0 and m == 0: continue\n temp = ''\n x, y = i, j\n while 0 <= x < N and 0 <= y < M:\n temp = temp + ary[x][y]\n if int(temp) == int(int(temp) ** 0.5) ** 2: result = max(result, int(temp))\n x += k\n y += m\nprint(result)","repo_name":"HyeongMokJeong/Coding-Test","sub_path":"BAEKJOON/1025.py","file_name":"1025.py","file_ext":"py","file_size_in_byte":600,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"15"} +{"seq_id":"72418763850","text":"secret_number = randint(0,100) #this is the secret number \nguess_count = 0 #number of guess count made\nguess_limit = 3 #maximum number of guess \nwhile guess_count < guess_limit : #while loop\n guess = int(input(\"enter the number : \")) #enter the number\n guess_count += 1 #increment every guess\n if guess ==secret_number: #if statement\n print(\" Voila ! You won!\") #print statement\n break #break statement\nelse: #else statement\n print(\"Sorry! You Lose!\") #print statement\n","repo_name":"grawish/GuessTheNumber","sub_path":"Guess the number!.py","file_name":"Guess the number!.py","file_ext":"py","file_size_in_byte":733,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"15"} +{"seq_id":"31191010007","text":"number_of_students = int(input())\nnumber_of_lectures = int(input())\nadditional_bonus = int(input())\n\ntotal_bonus = 0\nmax_bonus = 0\nmax_student = 0\n\nfor student in range(1, number_of_students + 1):\n student_attendance = int(input())\n total_bonus = student_attendance / number_of_lectures * (5 + additional_bonus)\n if max_bonus < total_bonus:\n max_bonus = total_bonus\n max_student = student_attendance\n\nprint(f\"\"\"Max Bonus: {round(max_bonus)}.\nThe student has attended {max_student} lectures.\"\"\")\n","repo_name":"IvanTodorovBG/SoftUni","sub_path":"Python Fundamentals/Exams/Mid Exam/Mid Exam 05/Task01.py","file_name":"Task01.py","file_ext":"py","file_size_in_byte":518,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"15"} +{"seq_id":"42378975549","text":"from django_filters import rest_framework as filters\nfrom rest_framework import viewsets\nfrom rest_framework.response import Response\n\nfrom api.serializers import CargoListSerializer, CargoSerializer\nfrom cargo.filters import CargoFilter\nfrom cargo.models import Cargo\nfrom core.utils import get_distance\nfrom trucks.models import Truck\n\n\nclass CargoViewSet(viewsets.ModelViewSet):\n queryset = Cargo.objects.all()\n filter_backends = (filters.DjangoFilterBackend,)\n filterset_class = CargoFilter\n\n def get_serializer_class(self):\n if self.action == \"list\":\n return CargoListSerializer\n return CargoSerializer\n\n # def create(self, request, *args, **kwargs):\n # return super().create(request, *args, **kwargs)\n\n def retrieve(self, request, *args, **kwargs):\n instance = self.get_object()\n serializer = self.get_serializer(instance)\n\n data = serializer.data\n\n data[\"trucks\"] = {}\n\n for truck in Truck.objects.all():\n distance_to_pick_up = get_distance(\n instance.delivery_location.coordinates, truck.current_location.coordinates\n )\n data[\"trucks\"][truck.unique_number] = distance_to_pick_up\n\n return Response(data)\n","repo_name":"isBlueTip/2023-05-25-welbex","sub_path":"cargo/views.py","file_name":"views.py","file_ext":"py","file_size_in_byte":1251,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"15"} +{"seq_id":"72923482250","text":"from django import forms\nfrom .widgets import CustomClearableFileInput\nfrom .models import Product, Category, ProductOption\n\n\nclass CustomMMCF(forms.ModelMultipleChoiceField):\n \"\"\"\n Custom form class that overrides the ‘label_from_instance’ method\n ref: http://tiny.cc/adg2vz\n \"\"\"\n def label_from_instance(self, product_select):\n return '%s' % product_select.product_options\n\n\nclass ProductForm(forms.ModelForm):\n \"\"\"\n Ability to add, update and delete products\n \"\"\"\n\n class Meta:\n # defines model and fields to include\n model = Product\n fields = '__all__'\n\n name = forms.CharField(label=\"\", widget=forms.TextInput(\n attrs={'placeholder': 'Name'}))\n\n description = forms.CharField(label=\"\", widget=forms.Textarea(\n attrs={'placeholder': 'A brief Description of the product'}))\n\n price = forms.DecimalField(label=\"\", widget=forms.NumberInput(\n attrs={'placeholder': 'Product price in Euro (€)'}))\n\n is_course = forms.BooleanField(\n label=\"This is a Course product\",\n required=False)\n\n is_apparel = forms.BooleanField(\n label=\"This is Apparel\",\n required=False)\n\n product_select = forms.ModelMultipleChoiceField(\n label=\"\",\n queryset=ProductOption.objects.all(),\n widget=forms.CheckboxSelectMultiple\n )\n\n course_info = forms.CharField(\n label=\"\",\n widget=forms.Textarea(\n attrs={'placeholder': 'Course information'}\n ),\n required=False)\n\n course_age = forms.CharField(\n label=\"\",\n widget=forms.TextInput(\n attrs={\n 'placeholder': 'Minimum age for course attendance'}\n ),\n required=False)\n\n image = forms.ImageField(\n label='Image',\n required=True,\n widget=CustomClearableFileInput\n )\n\n approved = forms.BooleanField(\n label=\"Approve Product\",\n required=False)\n\n def __init__(self, *args, **kwargs):\n \"\"\"\n Add placeholders and classes, remove auto-genetate\n labels and set autofocus on first field\n \"\"\"\n\n # override the init method\n # to make changes to fields\n super().__init__(*args, **kwargs)\n\n # get categories to show in their friendly name\n categories = Category.objects.all()\n # list comprehension for loop to get friendly names\n friendly_names = [(c.id, c.get_friendly_name()) for c in categories]\n # use category friendly name instead of id\n self.fields['category'].choices = friendly_names\n\n # cursor will start in name field\n self.fields['name'].widget.attrs['autofocus'] = True\n\n # iterate through fields with css for consistency\n for field_name, field in self.fields.items():\n field.widget.attrs['class'] = 'border-black rounded-0'\n","repo_name":"rebeccatraceyt/delphin_lifesavingclub","sub_path":"shop/forms.py","file_name":"forms.py","file_ext":"py","file_size_in_byte":2878,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"15"} +{"seq_id":"14137050409","text":"\"\"\"Implementation of T&E Harness for PAR Server.\"\"\"\n\nimport requests\nimport json\nimport io\nimport os\nimport traceback\nimport logging\n\nfrom sail_on_client.harness.test_and_evaluation_harness import TestAndEvaluationHarness\nfrom typing import Any, Dict, Union, List\nfrom requests import Response\nfrom sail_on_client.errors import ApiError, RoundError\nfrom tenacity import (\n retry,\n stop_after_attempt,\n wait_fixed,\n before_sleep_log,\n)\nfrom json import JSONDecodeError\n\nlog = logging.getLogger(__name__)\n\n\nclass ParHarness(TestAndEvaluationHarness):\n \"\"\"Harness for PAR server.\"\"\"\n\n def __init__(self, url: str, save_directory: str) -> None:\n \"\"\"\n Initialize a client connection object.\n\n Args:\n url: URL for the server\n save_directory: A directory to save files\n\n Returns:\n None\n \"\"\"\n TestAndEvaluationHarness.__init__(self)\n self.url = url\n self.save_directory = save_directory\n\n def get_config(self) -> Dict:\n \"\"\"JSON Compliant representation of the object.\"\"\"\n return {\"url\": self.url, \"save_directory\": self.save_directory}\n\n def _check_response(self, response: Response) -> None:\n \"\"\"\n Parse errors that present in the server response.\n\n Args:\n response: The response object obtained from the server\n\n Returns:\n None\n \"\"\"\n if response.status_code != 200:\n try:\n response_json = response.json()\n # Find the appropriate error class based on error code.\n for subclass in ApiError.error_classes():\n if subclass.error_code == response.status_code:\n raise subclass(\n response_json[\"reason\"],\n response_json[\"message\"],\n response_json[\"stack_trace\"],\n )\n except JSONDecodeError:\n log.exception(f\"Server Error: {traceback.format_exc()}\")\n exit(1)\n\n @retry(\n stop=stop_after_attempt(5),\n wait=wait_fixed(2),\n reraise=True,\n before_sleep=before_sleep_log(log, logging.INFO),\n )\n def test_ids_request(\n self,\n protocol: str,\n domain: str,\n detector_seed: str,\n test_assumptions: str = \"{}\",\n ) -> str:\n \"\"\"\n Request Test Identifiers as part of a series of individual tests.\n\n Args:\n protocol : string indicating which protocol is being evaluated\n domain : problem domain for the tests\n detector_seed : A seed provided by the novelty detector\n test_assumptions : Assumptions used by the detector\n\n Returns:\n Filename of file containing test ids\n \"\"\"\n payload = {\n \"protocol\": protocol,\n \"domain\": domain,\n \"detector_seed\": detector_seed,\n }\n\n with open(test_assumptions, \"r\") as f:\n contents = f.read()\n\n response = requests.get(\n f\"{self.url}/test/ids\",\n files={ # type: ignore\n \"test_requirements\": io.StringIO(json.dumps(payload)),\n \"test_assumptions\": io.StringIO(contents),\n },\n )\n\n self._check_response(response)\n\n filename = os.path.abspath(\n os.path.join(\n self.save_directory, f\"{protocol}.{domain}.{detector_seed}.csv\"\n )\n )\n with open(filename, \"w\") as f:\n f.write(response.content.decode(\"utf-8\"))\n\n return filename\n\n @retry(\n stop=stop_after_attempt(5),\n wait=wait_fixed(2),\n reraise=True,\n before_sleep=before_sleep_log(log, logging.INFO),\n )\n def session_request(\n self,\n test_ids: list,\n protocol: str,\n domain: str,\n novelty_detector_version: str,\n hints: list,\n detection_threshold: float,\n ) -> str:\n \"\"\"\n Create a new session to evaluate the detector using an empirical protocol.\n\n Args:\n test_ids: List of tests being evaluated in this session\n protocol: String indicating which protocol is being evaluated\n domain: String indicating which domain is being evaluated\n novelty_detector_version: The novelty detector being evaluated\n hints: Hints used for the session\n detection_threshold: Detection threshold for the session\n\n Returns:\n A session identifier provided by the server\n \"\"\"\n payload = {\n \"protocol\": protocol,\n \"novelty_detector_version\": novelty_detector_version,\n \"domain\": domain,\n \"hints\": hints,\n \"detection_threshold\": detection_threshold,\n }\n\n ids = \"\\n\".join(test_ids) + \"\\n\"\n\n response = requests.post(\n f\"{self.url}/session\",\n files={\"test_ids\": ids, \"configuration\": io.StringIO(json.dumps(payload))}, # type: ignore\n )\n\n self._check_response(response)\n return response.json()[\"session_id\"]\n\n @retry(\n stop=stop_after_attempt(5),\n wait=wait_fixed(2),\n reraise=True,\n before_sleep=before_sleep_log(log, logging.INFO),\n )\n def resume_session(self, session_id: str) -> List[str]:\n \"\"\"\n Get finished test from an existing session.\n\n Args:\n session id : Session id that was started but not terminated\n\n Returns:\n List of tests finished in the session\n \"\"\"\n params: Dict[str, str] = {\"session_id\": session_id}\n response = requests.get(f\"{self.url}/session/latest\", params=params)\n self._check_response(response)\n return response.json()[\"finished_tests\"]\n\n @retry(\n stop=stop_after_attempt(5),\n wait=wait_fixed(2),\n reraise=True,\n before_sleep=before_sleep_log(log, logging.INFO),\n )\n def dataset_request(self, test_id: str, round_id: int, session_id: str) -> str:\n \"\"\"\n Request data for evaluation.\n\n Args:\n test_id: The test being evaluated at this moment.\n round_id: The sequential number of the round being evaluated\n session_id: The identifier provided by the server for a single experiment\n\n Returns:\n Filename of a file containing a list of image files (including full path for each)\n \"\"\"\n params: Dict[str, Union[str, int]] = {\n \"session_id\": session_id,\n \"test_id\": test_id,\n \"round_id\": round_id,\n }\n response = requests.get(\n f\"{self.url}/session/dataset\",\n params=params,\n )\n if response.status_code == 204:\n raise RoundError(\"End of Dataset\", \"The entire dataset has been requested\")\n self._check_response(response)\n\n filename = os.path.abspath(\n os.path.join(self.save_directory, f\"{session_id}.{test_id}.{round_id}.csv\")\n )\n with open(filename, \"wb\") as f:\n f.write(response.content)\n return filename\n\n @retry(\n stop=stop_after_attempt(5),\n wait=wait_fixed(2),\n reraise=True,\n before_sleep=before_sleep_log(log, logging.INFO),\n )\n def get_feedback_request(\n self,\n feedback_ids: list,\n feedback_type: str,\n test_id: str,\n round_id: int,\n session_id: str,\n ) -> str:\n \"\"\"\n Get Labels from the server based provided one or more example ids.\n\n Args:\n feedback_ids: List of media ids for which feedback is required\n feedback_type: Protocols constants with the values: label, detection, characterization\n test_id: The id of the test currently being evaluated\n round_id: The sequential number of the round being evaluated\n session_id: The id provided by a server denoting a session\n\n Returns:\n Path to a file containing containing requested feedback\n \"\"\"\n params: Dict[str, Union[str, int]] = {\n \"feedback_ids\": \"|\".join(feedback_ids),\n \"session_id\": session_id,\n \"test_id\": test_id,\n \"feedback_type\": feedback_type,\n }\n response = requests.get(\n f\"{self.url}/session/feedback\",\n params=params,\n )\n self._check_response(response)\n filename = os.path.abspath(\n os.path.join(\n self.save_directory,\n f\"{session_id}.{test_id}.{round_id}_{feedback_type}.csv\",\n )\n )\n with open(filename, \"wb\") as f:\n f.write(response.content)\n\n return filename\n\n @retry(\n stop=stop_after_attempt(5),\n wait=wait_fixed(2),\n reraise=True,\n before_sleep=before_sleep_log(log, logging.INFO),\n )\n def post_results(\n self, result_files: Dict[str, str], test_id: str, round_id: int, session_id: str\n ) -> None:\n \"\"\"\n Post client detector predictions for the dataset.\n\n Args:\n result_files: A dictionary of results with protocol constant as key and file path as value\n test_id: The id of the test currently being evaluated\n round_id: The sequential number of the round being evaluated\n session_id: The id provided by a server denoting a session\n\n Returns:\n None\n \"\"\"\n payload = {\n \"session_id\": session_id,\n \"test_id\": test_id,\n \"round_id\": round_id,\n \"result_types\": \"|\".join(result_files.keys()),\n }\n\n files = {\"test_identification\": io.StringIO(json.dumps(payload))}\n\n if len(result_files.keys()) == 0:\n raise Exception(\"Must provide at least one result file\")\n\n for r_type in result_files:\n with open(result_files[r_type], \"r\") as f:\n contents = f.read()\n files[f\"{r_type}_file\"] = io.StringIO(contents)\n\n response = requests.post(f\"{self.url}/session/results\", files=files) # type: ignore\n\n self._check_response(response)\n\n @retry(\n stop=stop_after_attempt(5),\n wait=wait_fixed(2),\n reraise=True,\n before_sleep=before_sleep_log(log, logging.INFO),\n )\n def evaluate_round_wise(\n self,\n test_id: str,\n round_id: int,\n session_id: str,\n ) -> Dict[str, Any]:\n \"\"\"\n Get results for round(s).\n\n Args:\n test_id: The id of the test currently being evaluated\n round_id: The sequential number of the round being evaluated\n session_id: The id provided by a server denoting a session\n\n Returns:\n Path to a file with the results\n \"\"\"\n raise NotImplementedError(\"Round wise accuracy computation is not supported\")\n\n @retry(\n stop=stop_after_attempt(5),\n wait=wait_fixed(2),\n reraise=True,\n before_sleep=before_sleep_log(log, logging.INFO),\n )\n def evaluate(\n self,\n test_id: str,\n round_id: int,\n session_id: str,\n baseline_session_id: str = None,\n ) -> Dict:\n \"\"\"\n Get results for test(s).\n\n Args:\n test_id: The id of the test currently being evaluated\n round_id: The sequential number of the round being evaluated\n session_id: The id provided by a server denoting a session\n\n Returns:\n Path to a file with the results\n \"\"\"\n params: Dict[str, Union[str, int]] = {\n \"session_id\": session_id,\n \"test_id\": test_id,\n \"round_id\": round_id,\n }\n response = requests.get(\n f\"{self.url}/session/evaluations\",\n params=params,\n )\n\n self._check_response(response)\n return json.loads(response.text)\n\n @retry(\n stop=stop_after_attempt(5),\n wait=wait_fixed(2),\n reraise=True,\n before_sleep=before_sleep_log(log, logging.INFO),\n )\n def get_test_metadata(self, session_id: str, test_id: str) -> Dict[str, Any]:\n \"\"\"\n Retrieve the metadata json for the specified test.\n\n Args:\n session_id: The id of the session currently being evaluated\n test_id: The id of the test currently being evaluated\n\n Returns:\n A dictionary containing metadata\n \"\"\"\n response = requests.get(\n f\"{self.url}/test/metadata\",\n params={\"test_id\": test_id, \"session_id\": session_id},\n )\n\n self._check_response(response)\n return response.json()\n\n @retry(\n stop=stop_after_attempt(5),\n wait=wait_fixed(2),\n reraise=True,\n before_sleep=before_sleep_log(log, logging.INFO),\n )\n def complete_test(self, session_id: str, test_id: str) -> None:\n \"\"\"\n Mark test as completed.\n\n Args:\n session_id: The id of the session currently being evaluated\n test_id: The id of the test currently being evaluated\n\n Returns:\n None\n \"\"\"\n requests.delete(\n f\"{self.url}/test\",\n params={\"test_id\": test_id, \"session_id\": session_id},\n )\n\n @retry(\n stop=stop_after_attempt(5),\n wait=wait_fixed(2),\n reraise=True,\n before_sleep=before_sleep_log(log, logging.INFO),\n )\n def terminate_session(self, session_id: str) -> None:\n \"\"\"\n Terminate the session after the evaluation for the protocol is complete.\n\n Args:\n session_id: The id provided by a server denoting a session\n\n Returns: None\n \"\"\"\n response = requests.delete(\n f\"{self.url}/session\", params={\"session_id\": session_id}\n )\n\n self._check_response(response)\n","repo_name":"darpa-sail-on/sail-on-client","sub_path":"sail_on_client/harness/par_harness.py","file_name":"par_harness.py","file_ext":"py","file_size_in_byte":13961,"program_lang":"python","lang":"en","doc_type":"code","stars":2,"dataset":"github-code","pt":"15"} +{"seq_id":"29141162940","text":"\"\"\"\n这题分别遍历两个排序后数组,看之间的相对大小。如果相等,还有看看是否已经在ret数组中存在了,不然会导致重复元素。我在ret数组中先加了一个初始\n值,这样就不用在比较时没回都要判断数组是否为空。\n\"\"\"\nclass Solution:\n def intersection(self, nums1, nums2):\n \"\"\"\n :type nums1: List[int]\n :type nums2: List[int]\n :rtype: List[int]\n \"\"\"\n nums1.sort()\n nums2.sort()\n ret = ['ZERO']\n i, j = 0, 0\n while i < len(nums1) and j < len(nums2):\n if nums1[i] < nums2[j]:\n i += 1\n elif nums1[i] > nums2[j]:\n j += 1\n else:\n if nums1[i] != ret[-1]:\n ret.append(nums1[i])\n i += 1\n j += 1\n del ret[0]\n return ret\n\n\nsolve = Solution()\n# nums1 = [4,9,5]\n# nums2 = [9,4,9,8,4]\nnums1 = [1,2,2,1]\nnums2 = [2,2]\nprint(solve.intersection(nums1, nums2))","repo_name":"xukangjune/Leetcode","sub_path":"solved/349. 两个数组的交集.py","file_name":"349. 两个数组的交集.py","file_ext":"py","file_size_in_byte":1025,"program_lang":"python","lang":"zh","doc_type":"code","stars":2,"dataset":"github-code","pt":"15"} +{"seq_id":"38340876772","text":"#Song Information Reddit Bot\r\n\r\nimport praw\r\nimport lyricsgenius as genius\r\n\r\n#reddit api login\r\n#app developed under the projectpersonal reddit account\r\n\r\nreddit = praw.Reddit(client_id=\"******\", client_secret =\"******\", username=\"******\", password=\"******\", user_agent=\"******\")\r\n\t\t\t\t\t\r\n#subreddits that bot interacts with\r\nsubreddit = reddit.subreddit(\"drizzy\")\r\n\r\n#phrase to call songinfobot\r\nkeyphrase = \"!songinfobot\"\r\n\t\t\r\n\r\ndef getSongInfo(song_title):\r\n\tapi = genius.Genius(\"******\")\r\n\tartist_name = \"Drake\"\r\n\tsong_response = api.search_song(song_title, artist_name)\r\n\tif song_response:\r\n\t\tsong_information = song_response.title + \" by \" + song_response.artist + \".\\nAppears on the album: \" + song_response.album + \".\\nReleased on: \" + song_response.year + \". \\nFind out more at: \" + song_response._url\r\n\t\treturn song_information\r\n\telse:\r\n\t\tprint(\"Couldn't find \" + song_name + \"by \" + artist_name)\r\n\t\t\r\n\r\ndef postToReddit():\r\n\tfor comment in subreddit.stream.comments():\r\n\t\tif(keyphrase in comment.body):\r\n\t\t\t#Found a comment calling songinfobot so can proceed to look up song\r\n\t\t\tsong_title = comment.body.replace(keyphrase, \" \")\r\n\t\t\tsong_info = getSongInfo(song_title)\r\n\t\t\tcomment.reply(song_info)\r\n\t\t\tprint(\"Posted: \")\r\n\t\t\tprint(song_info + \" to r/Drizzy\")\r\n\t\t\t\t\r\n\t\t\t\t\r\n\t\t\t\t\t\r\npostToReddit()\r\nprint(\"Done posting to Reddit\")\r\n","repo_name":"BarathKoottala/songinfobot","sub_path":"songinfobot.py","file_name":"songinfobot.py","file_ext":"py","file_size_in_byte":1339,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"15"} +{"seq_id":"3334629111","text":"from httpx import AsyncClient\nimport pytest\nfrom sqlalchemy_utils import create_database, drop_database\n\nfrom app.database.base import Base\nfrom app.database.session import database, engine\nfrom app.main import app\n\n\n@pytest.fixture\nasync def client():\n async with AsyncClient(app=app, base_url=\"http://test\") as client:\n yield client\n\n\n@pytest.fixture(scope=\"session\", autouse=True)\ndef migrate():\n create_database(engine.url)\n Base.metadata.create_all(engine)\n yield\n Base.metadata.drop_all(engine)\n drop_database(engine.url)\n\n\n@pytest.fixture(scope=\"function\")\nasync def delete_tables_data():\n async def __removing_table():\n for table in Base.metadata.tables:\n query = f\"DELETE FROM {table}\"\n await database.execute(query)\n\n await __removing_table()\n yield\n await __removing_table()\n\n\n@pytest.fixture(autouse=True)\nasync def db():\n await database.connect()\n yield\n await database.disconnect()\n","repo_name":"PatrickGleeson/a_test2","sub_path":"templates/fastapi-app/app/tests/conftest.py","file_name":"conftest.py","file_ext":"py","file_size_in_byte":971,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"15"} +{"seq_id":"6750240280","text":"import telebot\nimport asyncio\nimport logging\nfrom aiogram import Bot, Dispatcher, types\nlogging.basicConfig(level=logging.INFO)\n# dp = Dispatcher(bot)\n\nbot = Bot(token = \"545___:AAGNo61KJ___6CQY\")\ndp = Dispatcher(bot)\n@dp.message_handler(commands =['start'])\nasync def cmd_start (message: types.Message):\n # bot.send_message(message.chat.id,\"Привет ✌️ \")\n await message.answer (\"Hello!\")\n\nasync def main():\n await dp.start_polling(bot)\n# bot.infinity_poling()\nif __name__ == \"__main__\":\n asyncio.run(main())\n","repo_name":"haimka71/pythonProject","sub_path":"BOT Project/Bot Task.py","file_name":"Bot Task.py","file_ext":"py","file_size_in_byte":522,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"15"} +{"seq_id":"14357915360","text":"# código referente à aula 05 - Desenvolvendo um verificador de IP Externo\nimport re\nimport json\nfrom urllib.request import urlopen\n\nurl = 'https://ipinfo.io/json'\n\nresposta = urlopen(url)\n\ndados = json.load(resposta)\n\nip = dados['ip']\norg = dados['org']\ncidade = dados['city']\npais = dados['country']\nregiao = dados['region']\n\nprint(f\"\"\"\n============================\n Detalhes do IP externo \nIP: {ip}\nOrganização: {org}\nCidade: {cidade}\nPais: {pais}\nRegião: {regiao}\n============================\n\n\"\"\")\n\n# Os dados mostrados nesse códigos são suas informações de IP reais, cuidado ao divulgar.","repo_name":"Lyarkh/Bootcamps_e_Intensivoes","sub_path":"Bootcamp_Cognizant_Cloud_Data/Seguranca_informacao_com_python/verificador_ip.py","file_name":"verificador_ip.py","file_ext":"py","file_size_in_byte":603,"program_lang":"python","lang":"pt","doc_type":"code","stars":1,"dataset":"github-code","pt":"15"} +{"seq_id":"30906838405","text":"from PIL import Image, ImageDraw\n\nUP = 40\nLEFT = 40\nSIZE = 21\nPIXEL = 10\n\nFRAME_SIZE = 7\nCELL_SIZE = 3\n\nBLANK = 0\n\nassert SIZE == FRAME_SIZE * CELL_SIZE\n\n# 対象となる QR コード\nimg = Image.open(\"hb1.png\")\nqr = [[0 for _ in range(SIZE)] for _ in range(SIZE)]\n\n# QR コードを符号化\nfor i in range(SIZE):\n for j in range(SIZE):\n color = img.getpixel((LEFT + j * PIXEL, UP + i * PIXEL))\n if color == 0:\n qr[i][j] = 0\n else:\n qr[i][j] = 1\n\n\nD_FRAME = 1\nD_HALF_DOT = 3\n\nD_DOT = 2 * D_HALF_DOT\nD_SIDE = 2\n\noutput = Image.new(\"RGB\", (D_DOT * 21 + 2 * D_SIDE * D_DOT, D_DOT * 21 + 2 * D_SIDE * D_DOT), (255, 255, 255))\ndraw = ImageDraw.Draw(output)\n\nfor i in range(SIZE):\n for j in range(SIZE):\n if qr[i][j] == 0:\n draw.rectangle(\n (D_DOT * D_SIDE + D_DOT * i + D_FRAME, D_DOT * D_SIDE + D_DOT * j + D_FRAME, D_DOT * D_SIDE + D_DOT * (i + 1) - D_FRAME, D_DOT * D_SIDE + D_DOT * (j + 1) - D_FRAME), fill=(0, 0, 0)\n )\n\noutput.save(\"output.png\")\n","repo_name":"firedial/til","sub_path":"polyomino/qr_hole/make_qr.py","file_name":"make_qr.py","file_ext":"py","file_size_in_byte":1041,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"15"} +{"seq_id":"71056918090","text":"my_dict = {\"Hello\": \"Xin chào\",\"name\":\"Tên\",\"age\":\"Tuổi\",\"egg\":\"trứng\",\"meat\":\"thịt\",\"one\":'số một',\"two\":'số hai',\"three\":\"số ba\"}\n\ndef show_header():\n print('''\n Nhập 1 để nhập từ tiếng anh.\n Nhập 2 để thoát chương trình.\n ''')\n\ndef search(my_dict):\n C = False\n vocabulary = input(\"Nhập từ tiếng anh cần tra sang tiếng việt: \")\n for eng, vn in my_dict.items():\n if vocabulary == eng:\n print(f'Từ {vocabulary} có nghĩa tiếng việt là {vn}')\n C= True\n break\n if C == False:\n print(f'Từ {vocabulary} không có trong từ điển.')\n\ndef get_choice():\n return input(\"Lựa chọn của bạn: \")\n\nwhile True:\n show_header()\n choice = get_choice()\n if choice == '1':\n search(my_dict)\n elif choice == '2':\n break\n\n","repo_name":"levinhdu/dictionary","sub_path":"English_Vietnamese_Dictionary.py","file_name":"English_Vietnamese_Dictionary.py","file_ext":"py","file_size_in_byte":877,"program_lang":"python","lang":"vi","doc_type":"code","stars":0,"dataset":"github-code","pt":"15"} +{"seq_id":"23628543252","text":"from calendar import monthrange\nfrom datetime import date, datetime\nfrom django.contrib.auth.models import User\nfrom readingtracker.models import Entry\nimport time\n\ndef get_entry_data(username):\n user = User.objects.get(username=username)\n entries = Entry.objects.filter(user=user)\n\n entry_data = []\n for entry in entries:\n entry_date = entry.date.strftime('%m/%d/%y')\n\n entry_dict = {\n 'date': entry_date,\n 'minutes': entry.minutes,\n 'pages': entry.pages\n }\n\n entry_data.append(entry_dict)\n\n return entry_data\n\ndef get_friend_entries(user, friend_type, year, month):\n # Get date range\n days = range(1, monthrange(year, month)[1] + 1)\n date_list = []\n columns = [{'title': 'Name'}]\n for day in days:\n date_list.append(date(year, month, day))\n columns.append({'title': day, 'width': '2%', 'orderable': False})\n\n friendships = user.friends_from.filter(friend_type=friend_type, active=True)\n data = []\n for friendship in friendships:\n friend_name = '%s, %s' % (friendship.user.last_name, friendship.user.first_name)\n if friend_name == ', ':\n friend_name = friendship.user.username\n\n friend_data = [friend_name]\n for entry_date in date_list:\n try:\n entry = Entry.objects.get(user=friendship.user, date=entry_date)\n friend_data.append(entry.minutes)\n except Entry.DoesNotExist:\n friend_data.append(0)\n data.append(friend_data)\n\n return {'columns': columns, 'data': data}\n","repo_name":"brycecaine/readitdown","sub_path":"wsgi/readitdown/readingtracker/service.py","file_name":"service.py","file_ext":"py","file_size_in_byte":1596,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"15"} +{"seq_id":"30897302352","text":"from islandora import ContentModel as CM\nfrom islandora_scraper import IslandoraScraper\nimport re\nfrom bs4 import BeautifulSoup\n\npaper_cm = CM(id='newspaperCModel', ds={'RELS-EXT': True, 'DC': True, 'MODS': True, 'TN': True})\nissue_cm = CM(id='newspaperIssueCModel', ds={'RELS-EXT': True, 'DC': True, 'MODS': True})\npage_cm = CM(id='newspaperPageCModel',\n ds={'RELS-EXT': False, 'DC': True, 'MODS': False, 'TN': False, 'RELS-INT': False, 'OBJ': False,\n 'JP2': False, 'JPG': False, 'OCR': False, 'HOCR': False})\n\npage_light_cm = CM(id='newspaperPageCModel',\n ds={'RELS-EXT': False, 'DC': True, 'MODS': False, 'TN': False, 'RELS-INT': False,\n 'JP2': False, 'JPG': False, 'OCR': False, 'HOCR': False})\n\nclass NewspaperScraper(IslandoraScraper):\n def __init__(self, root_url):\n super().__init__(root_url)\n\n def get_pages_in_issue(self, issue_id: str) -> [str]:\n resp = self.session.get(f'{self.root_url}/object/{issue_id}')\n soup = BeautifulSoup(resp.content, 'html.parser')\n dl_list = soup.find(id='block-roblib_download_block-roblib_download_block')\n if dl_list is None:\n return []\n pages = [self._extract_id(li.findAll('option')[1]['value']) for li in\n dl_list.find_all(class_='page-select form-select')]\n return pages\n\n def _extract_id(self, url: str) -> str:\n return url.replace(f'{self.root_url}/object/', '').split('/')[0].replace('%3A', ':')\n","repo_name":"Islandora-Image-Segmentation/dev-ops","sub_path":"src/newspapers.py","file_name":"newspapers.py","file_ext":"py","file_size_in_byte":1494,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"15"} +{"seq_id":"73927016010","text":"from .db import db, environment, SCHEMA, add_prefix_for_prod\n\nclass Reaction(db.Model):\n __tablename__ = \"reactions\"\n\n if environment == \"production\":\n __table_args__ = {\"schema\": SCHEMA}\n\n id = db.Column(db.Integer, primary_key=True)\n name = db.Column(db.String(20), nullable=False)\n emoji = db.Column(db.String(255), nullable=False)\n\n message_reactions = db.relationship(\"MessageReaction\", back_populates='reaction')\n","repo_name":"johnny-2123/Slack_Clone","sub_path":"app/models/reaction.py","file_name":"reaction.py","file_ext":"py","file_size_in_byte":444,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"15"} +{"seq_id":"8416412833","text":"import pygame\nfrom Globals import DECKDEFS,COLORS,UTILITIES\nclass TrickWinner():\n def __init__(self):\n self.pos=((0,-95),(90,0),(0,95),(-90,0))\n self.dirs=('d','l','u','r')\n self.surf=pygame.Surface((10,10),1).convert()\n self.rect=self.surf.get_rect()\n self.colorfg=COLORS['yellow']\n def getPos(self,screen,iseat):\n screenrect=screen.get_rect()\n pos=[screenrect.centerx,screenrect.centery]\n pos[0]+=(self.pos[iseat])[0]-self.rect.width/2\n pos[1]+=(self.pos[iseat])[1]-self.rect.height/2\n return pos\n def clear(self,screen):\n self.surf.fill(COLORS['table'])\n for iseat in range(DECKDEFS.nseats):\n screen.blit(self.surf,self.getPos(screen,iseat))\n def draw(self,screen,trickwinner):\n self.clear(screen)\n for iseat in range(DECKDEFS.nseats):\n if iseat==trickwinner:\n UTILITIES.drawArrowHead2(self.surf,self.colorfg,self.dirs[(iseat+2)%4])\n #self.drawArrow(self.dirs[iseat])\n screen.blit(self.surf,self.getPos(screen,iseat))\n break\n def drawArrow(self,direction):\n UTILITIES.drawArrow(self.surf,self.colorfg,direction,3)\n\n","repo_name":"baltzell/Bridget","sub_path":"src/TrickWinner.py","file_name":"TrickWinner.py","file_ext":"py","file_size_in_byte":1220,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"15"} +{"seq_id":"38002614741","text":"import ast\nimport sys\nfrom pathlib import Path\nfrom typing import List, Tuple, Union\n\nfrom pyleft.path_utils import cwd\nfrom pyleft.printing import verbose_print\nfrom pyleft.settings import Settings\n\ntry:\n pass\nexcept ImportError:\n pass # pyright: ignore\n\ntype_comments = sys.version_info >= (3, 8)\n\n\ndef does_arg_have_default(arg_position: int, arg_count: int, defaults: list) -> bool:\n \"\"\"\n For positional arguments, the defaults list provided by the ast, lists\n defaults for the last X arguments.\n\n So if there are 5 arguments, and 3 defaults, only the last 3 have defaults.\n \"\"\"\n return arg_count - (arg_position + 1) < len(defaults)\n\n\ndef does_kwarg_have_default(arg_position: int, defaults: list) -> bool:\n \"\"\"\n For keyword arguments, the defaults list provided by the ast, lists\n defaults for all arguments. If a value is None, then there is no default.\n \"\"\"\n return defaults[arg_position] is not None\n\n\ndef check_function(\n function: Union[ast.FunctionDef, ast.AsyncFunctionDef],\n inside_class: bool,\n) -> List[Tuple[str, int]]:\n \"\"\"\n Check a single function for type annotations and return a list of tuples of issues.\n The first item in the tuple is the issue, the second item is the line number.\n \"\"\"\n function_issues: List[Tuple[str, int]] = []\n\n has_classmethod = any(\n isinstance(decorator, ast.Name)\n and decorator.id == \"classmethod\"\n and isinstance(decorator.ctx, ast.Load)\n for decorator in function.decorator_list\n )\n\n has_property = any(\n isinstance(decorator, ast.Name)\n and decorator.id == \"property\"\n and isinstance(decorator.ctx, ast.Load)\n for decorator in function.decorator_list\n )\n\n for i, arg in enumerate(function.args.args):\n # if the function is inside a class, and is a class method\n if inside_class and i == 0 and arg.arg == \"cls\" and has_classmethod:\n continue\n\n # if the function is inside a class, and is a property\n if inside_class and i == 0 and arg.arg == \"cls\" and has_property:\n continue\n\n # if the function is the __new__ method\n if inside_class and i == 0 and arg.arg == \"cls\" and function.name == \"__new__\":\n continue\n\n # if the function is inside a class, and is a normal method\n if inside_class and i == 0 and arg.arg == \"self\":\n continue\n\n # static methods have no special treatment\n\n # check positional arguments for type annotations\n if arg.annotation is None:\n # see if argument has a default value, and if so, if the user is okay with this\n if Settings.ignore_if_has_default and does_arg_have_default(\n i, len(function.args.args), function.args.defaults\n ):\n continue\n\n function_issues.append(\n (\n f\"Argument '{arg.arg}' of function '{function.name}' has no type annotation\",\n function.lineno,\n )\n )\n\n # check keyword arguments for type annotations\n for j, kwarg in enumerate(function.args.kwonlyargs):\n if kwarg.annotation is None:\n # see if argument has a default value, and if so, if the user is okay with this\n if Settings.ignore_if_has_default and does_kwarg_have_default(\n j, function.args.kw_defaults\n ):\n continue\n\n function_issues.append(\n (\n f\"Argument '{kwarg.arg}' of function '{function.name}' has no type annotation\",\n function.lineno,\n )\n )\n\n # check that function has a return type annotation\n # __init__ and __new__ functions are allowed to have no return type annotation\n if function.returns is None and function.name not in [\"__init__\", \"__new__\"]:\n function_issues.append(\n (\n f\"Function '{function.name}' has no return type annotation\",\n function.lineno,\n )\n )\n\n return function_issues\n\n\ndef walk_ast(\n node: Union[ast.Module, ast.ClassDef, ast.FunctionDef, ast.AsyncFunctionDef],\n file_content: List[str],\n inside_class: bool = False,\n) -> List[Tuple[str, int]]:\n \"\"\"\n Walk an AST tree and check all functions inside recursively\n and return a list of strings of issues\n \"\"\"\n # list of messages and line number tuples\n ast_issues: List[Tuple[str, int]] = []\n\n for sub_node in node.body:\n if isinstance(sub_node, ast.ClassDef):\n # walk children of class\n ast_issues.extend(walk_ast(sub_node, file_content, inside_class=True))\n elif isinstance(sub_node, (ast.FunctionDef, ast.AsyncFunctionDef)):\n # skip the function if \"noqa\" in the same line as the function\n if all(\n c not in file_content[sub_node.lineno - 1]\n for c in [\"# noqa\", \"# noqa\"]\n ):\n # check the function's type annotations\n ast_issues.extend(check_function(sub_node, inside_class=inside_class))\n\n # still, walk the children of the function as you can put\n # functions inside functions\n ast_issues.extend(walk_ast(sub_node, file_content))\n\n return ast_issues\n\n\ndef check_file(file: Path) -> List[str]:\n \"\"\"\n Check a single file for type annotations and return a list of strings of issues\n \"\"\"\n # read the contents of the file\n file_content = file.read_text(encoding=\"utf-8\").splitlines()\n\n # not supported in Python 3.7 and below\n kwargs = {}\n if type_comments:\n kwargs[\"type_comments\"] = True\n\n # parse the file\n ast_tree = ast.parse(\"\\n\".join(file_content), filename=file.name, **kwargs)\n # walk the ast\n results = walk_ast(ast_tree, file_content=file_content)\n\n return [f'\"{file.absolute()}:{r[1]}\" {r[0]}' for r in results]\n\n\ndef main() -> List[str]:\n # record all the issues we find\n all_issues: List[str] = []\n\n # start looping\n for file in Settings.files:\n verbose_print(f\"Checking {file.relative_to(cwd)}\")\n all_issues.extend(check_file(file))\n\n return all_issues\n","repo_name":"NathanVaughn/pyleft","sub_path":"pyleft/api.py","file_name":"api.py","file_ext":"py","file_size_in_byte":6228,"program_lang":"python","lang":"en","doc_type":"code","stars":4,"dataset":"github-code","pt":"15"} +{"seq_id":"35930254692","text":"from picamera import PiCamera\nfrom time import sleep\n\ncamera = PiCamera()\ncamera.resolution = (2592, 1944)\ncamera.framerate = 15\n\ncamera.start_preview(alpha =200)\nfor i in range(5):\n sleep(5)\n camera.capture('/home/sumayyah/Desktop/len 2/img%s.jpg' % i)\ncamera.stop_preview()\n","repo_name":"imjacobestep/smart-study-lamp","sub_path":"test_code/past_camera_test/camera with maximum reslution.py","file_name":"camera with maximum reslution.py","file_ext":"py","file_size_in_byte":282,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"15"} +{"seq_id":"71777471373","text":"import tensorflow as tf\nimport numpy as np\nfrom time import time as timee\nimport time\nimport pickle\n\nfrom data.dataset import Dataset\nfrom data.sampler import SamplerFM\nfrom evaluate.evaluate import EvaluateFM\nfrom evaluate.logger import Logger\nfrom general_model.AbstractRecommender import AbstractRecommender\n\nclass NFM(AbstractRecommender):\n def __init__(self,\n sess,\n learning_rate=0.001,\n batch_size=512,\n embedding_size=64,\n episodes=50,\n data_name=\"frappe\",\n field_size=2,\n layers=[64,64,32],\n reg_mf=0.000001,\n num_neg=1,\n verbose=5,\n pre_train=False,\n dropout_rate=1,\n shuffle=True,\n user_layers=True,\n ):\n super(NFM,self).__init__()\n self.sess=sess\n self.lr=learning_rate\n self.batch_size=batch_size\n self.embedding_size=embedding_size\n self.episodes=episodes\n self.data_name=data_name\n self.field_size=field_size\n self.layers=layers\n self.reg_mf=reg_mf\n self.num_neg=num_neg\n self.verbose=verbose\n self.pre_train=pre_train\n self.dropout_rate=dropout_rate\n self.shuffle=shuffle\n self.use_layers=user_layers\n\n self.string=\"NFM\"\n self.dataset=Dataset(data_name=self.data_name)\n self.sampler=SamplerFM(batch_size=self.batch_size,data_name=self.data_name,shuffle=self.shuffle)\n\n self.build_tools()\n self.feature_size=self.sampler.get_feature_size()\n self.build_net()\n self.saver = tf.train.Saver()\n\n self.var=[v.name for v in tf.trainable_variables()]\n\n def build_net(self):\n #placeholder\n self.feat_features=tf.placeholder(tf.int32,[None,None],name=\"user\")\n self.label=tf.placeholder(tf.float32,[None,],name=\"label\")\n self.dropout_rates=tf.placeholder(tf.float32,[None,],name=\"droput_rates\")\n\n #variables\n init = tf.random_normal_initializer(0., 0.01)\n if self.pre_train:\n values = pickle.load(\n open(\"D:/PycharmProjects/recommend_DIY/dataset/model_values/NFM/%s.p\" % self.data_name, \"rb\"))\n self.feature_weight=tf.Variable(values[0],name=\"feature_weight\",dtype=tf.float32,trainable=True)\n self.feature_first=tf.Variable(values[1],name=\"feature_first\",dtype=tf.float32,trainable=True)\n else:\n self.feature_weight=tf.get_variable(name=\"feature_weight\",shape=[self.feature_size,self.embedding_size],dtype=tf.float32,initializer=init)\n self.feature_first=tf.get_variable(name=\"feature_first\",shape=[self.feature_size,1],dtype=tf.float32,initializer=init)\n\n #embedding\n \"\"\"\n [N,N_F]---embedding-->[N,N_F,E_S]--reduce_sum--->[N,E_S]--square--->[N,E_S]\n --square--->[N,N_F,N_S]--reduce_sum--->[N,E_S]\n subtract--->[N,E_S]\n \"\"\"\n self.feature_embedding_part=tf.nn.embedding_lookup(self.feature_weight,self.feat_features)\n\n self.first_order=tf.nn.embedding_lookup(self.feature_first,self.feat_features)\n self.first_order_part=tf.reduce_sum(self.first_order,axis=1)\n self.bias=tf.Variable(tf.constant(0.0), name='bias')\n self.bias=self.bias*tf.ones_like((self.label))[:,tf.newaxis]\n\n #order_2\n self.sum_features_embedding=tf.reduce_sum(self.feature_embedding_part,1)\n self.sum_features_embedding_square=tf.square(self.sum_features_embedding)\n self.square_feature_embedding=tf.square(self.feature_embedding_part)\n self.square_feature_embedding_sum=tf.reduce_sum(self.square_feature_embedding,1)\n self.FM_second_order=0.5*tf.subtract(self.sum_features_embedding_square,self.square_feature_embedding_sum)\n\n #l2_norm\n l2_norm=tf.add_n([\n tf.reduce_sum(tf.multiply(self.feature_embedding_part,self.feature_embedding_part)),\n tf.reduce_sum(tf.multiply(self.first_order,self.first_order))\n ])\n\n # #order_1\n # self.FM_first_order=tf.add_n([self.first_order_part,self.bias])\n\n #NN\n self.FM_second_order=tf.layers.batch_normalization(self.FM_second_order,axis=1)\n self.FM_second_order=tf.nn.dropout(self.FM_second_order,self.dropout_rates[-1])\n if self.use_layers:\n for i in range(len(self.layers)):\n self.FM_second_order=tf.layers.dense(self.FM_second_order,self.layers[i],activation=None,name=\"layer_%d\"%i,kernel_initializer=init)\n self.FM_second_order = tf.layers.batch_normalization(self.FM_second_order, axis=1)\n self.FM_second_order=tf.nn.relu(self.FM_second_order)\n self.FM_second_order=tf.nn.dropout(self.FM_second_order,self.dropout_rates[i])\n self.FM_second_order=tf.layers.dense(self.FM_second_order,1,kernel_initializer=init)\n #prediction\n self.FM=tf.reduce_sum(tf.add_n([self.first_order_part,self.bias,self.FM_second_order]),axis=1)\n\n #loss\n #square_loss for regression\n self.loss=tf.losses.mean_squared_error(labels=self.label,predictions=self.FM)+self.reg_mf*l2_norm\n self.square=tf.reduce_sum(tf.square(self.label-self.FM))\n #log_loss for classification\n # self.loss=tf.reduce_mean(tf.losses.sigmoid_cross_entropy(self.label,self.FM))+self.reg_mf*l2_norm\n\n #optimizer\n # self.train_op=tf.train.AdagradOptimizer(learning_rate=self.lr, initial_accumulator_value=1e-8).minimize(self.loss)\n self.train_op=tf.train.AdamOptimizer(self.lr).minimize(self.loss)\n\n def build_tools(self):\n localtime = time.strftime(\"%Y-%m-%d-%H-%M-%S\", time.localtime())\n self.logger = Logger(\"D:/PycharmProjects/recommend_DIY/log/NFM/%s\" % str(localtime))\n self.evaluate = EvaluateFM(sampler=self.sampler,logger=self.logger,model=self,data_name=self.data_name)\n self.evaluate.logging()\n self.logger.info(\"shuffle: %s\" % self.shuffle)\n self.logger.info(\"layers: %s\" % self.layers)\n self.logger.info(\"pre_train: %s\" % self.pre_train)\n self.logger.info(\"dropout_rate: %s\" % self.dropout_rate)\n self.logger.info(\"use_layers: %s\"%self.use_layers)\n\n def train(self):\n for episode in range(self.episodes):\n if (1+episode)%self.verbose==0:\n test_rmse,test_time=self.evaluate.RMSE(data_name=\"test\")\n validation_rmse,validation_time=self.evaluate.RMSE(data_name=\"validation\")\n train_rmse,train_time=self.evaluate.RMSE(data_name=\"train\")\n self.logger.info(\">>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>> train_rmse: %.3f validation: %.3f test:%.3f\"%(train_rmse,validation_rmse,test_rmse))\n data_iter = self.sampler.get_train_batch()\n train_batch_number, validation_batch_number, test_batch_number = self.sampler.get_batch_number()\n total_loss=0\n trainging_start_time=timee()\n for i in range(train_batch_number):\n data=next(data_iter)\n loss,_=self.sess.run([self.loss,self.train_op],feed_dict={\n self.feat_features:data[:,1:],\n self.label:data[:,0],\n self.dropout_rates:self.dropout_rate\n })\n total_loss+=loss\n self.logger.info(\"--Episode %d: train_loss: %.5f time: %.3f \" % (\n episode, total_loss / train_batch_number, timee() - trainging_start_time))\n self.logger.info(\"\")\n\n values=self.sess.run(self.var)\n pickle.dump((values),open(\"D:/PycharmProjects/recommend_DIY/dataset/model_values/NFM/%s.p\" % self.data_name, \"wb\"))\n self.saver.save(sess=self.sess,save_path=\"D:/PycharmProjects/recommend_DIY/dataset/model_store/NFM/%s\" % self.data_name)\n print(\"model has been saved!!!\")\n\n def predict(self,user_ids,item_ids=None):\n pass\n\nsess=tf.Session()\nNFM=NFM(sess=sess,learning_rate=0.005,batch_size=4096,verbose=1,shuffle=False,data_name=\"ml_tag\",dropout_rate=[0.8,0.7,0.5],pre_train=False,episodes=100,user_layers=True,reg_mf=0.00001,layers=[128],embedding_size=128)\nsess.run(tf.global_variables_initializer())\nNFM.train()","repo_name":"xingkongxiaxia/tensorflow_recommend_system","sub_path":"recommend_DIY/general_model/NFM.py","file_name":"NFM.py","file_ext":"py","file_size_in_byte":8363,"program_lang":"python","lang":"en","doc_type":"code","stars":2,"dataset":"github-code","pt":"15"} +{"seq_id":"27135953360","text":"from gooey import Gooey, GooeyParser\nimport yaml\n\n\ndef convert(data):\n print(\"Writing yaml...\")\n with open(data.FileSaver, \"w\") as outfile:\n yaml.dump(vars(data), outfile, default_flow_style=False)\n print(\"...\")\n print(\"Done!\")\n print(f\"Yaml available at {data.FileSaver}\")\n\n\n@Gooey(\n dump_build_config=True,\n program_name=\"Convert to YAML\",\n show_success_modal=False,\n show_restart_button=False,\n)\ndef main():\n desc = \"Enter fields and convert to yaml\"\n file_help_msg = \"Name of the file you want to output\"\n\n my_cool_parser = GooeyParser(description=desc)\n\n my_cool_parser.add_argument(\n \"FileSaver\",\n help=file_help_msg,\n widget=\"FileSaver\",\n gooey_options={\"full_width\": True},\n )\n\n my_cool_parser.add_argument(\n \"some_required_field\", metavar=\"Some Data\", help=\"Enter some text\"\n )\n\n data = my_cool_parser.parse_args()\n convert(data)\n\n\ndef here_is_more():\n pass\n\n\nif __name__ == \"__main__\":\n main()\n","repo_name":"jagath-jaikumar/testGooeyConverter","sub_path":"yamlConverter.py","file_name":"yamlConverter.py","file_ext":"py","file_size_in_byte":1006,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"15"} +{"seq_id":"34336728379","text":"\"\"\"\nPyTorch Implementation of IrregConv, by Robin Deuher\n\"\"\"\nimport torch\nimport torch.nn as nn\nimport torch.nn.functional as F\nimport numpy as np\n\ndef rand_mask(num_filters, num_channels, kernel_dims = (3, 3), weights_per_kernel = 4, center_weight = True):\n \"\"\"\n args:\n num_filters:\n num_channels:\n weights_per_kernel:\n return:\n mask: a randomly generated mask for irreg conv, shape num_filters, num_channels, 3, 3\n \"\"\"\n if isinstance(kernel_dims, int):\n kernel_dims = (kernel_dims, kernel_dims)\n\n total_weights = kernel_dims[0]*kernel_dims[1]\n\n if weights_per_kernel is None:\n weights_per_kernel = total_weights//2\n\n if kernel_dims[0] == kernel_dims[1] and kernel_dims[0]%2 == 1:\n center_weight = True \n center_i, center_j = kernel_dims[0]//2, kernel_dims[1]//2\n else:\n center_weight = False\n \n choices = []\n for i in range(kernel_dims[0]):\n for j in range(kernel_dims[1]):\n if center_weight:\n if i != center_i or j != center_j:\n choices.append((i, j))\n else: \n choices.append((i, j))\n\n mask = np.zeros((num_filters, num_channels, kernel_dims[0], kernel_dims[1]))\n for f in range(num_filters):\n for c in range(num_channels):\n if center_weight: \n mask[f, c, center_i, center_j] = total_weights/weights_per_kernel\n ks = np.random.permutation(len(choices))\n for k in ks[:weights_per_kernel-1]: \n i, j = choices[k]\n mask[f, c, i, j] = total_weights/weights_per_kernel\n return torch.Tensor(mask)\n\nclass IrregConv2D(nn.Conv2d):\n \"\"\"\"\"\"\n def __init__(self, in_channels, out_channels, kernel_size, mask_fn = rand_mask, weights_per_kernel = None, **kwargs):\n super(IrregConv2D, self).__init__(in_channels, out_channels, kernel_size, **kwargs)\n self.mask = mask_fn(out_channels, in_channels, kernel_dims = kernel_size, weights_per_kernel = weights_per_kernel)\n # get initalized weights from \n weights = self.weight\n self.weight = nn.Parameter(weights * self.mask)\n\n def forward(self, input: Tensor) -> Tensor:\n weight = torch.mul(self.weight, self.mask)\n return self._conv_forward(input, weight, self.bias)\n","repo_name":"electricdarb/IregularConv","sub_path":"src/IrregConv/torch_tools.py","file_name":"torch_tools.py","file_ext":"py","file_size_in_byte":2328,"program_lang":"python","lang":"en","doc_type":"code","stars":3,"dataset":"github-code","pt":"15"} +{"seq_id":"16788346602","text":"import logging\nfrom telegram import Update\nfrom telegram.ext import Updater, CommandHandler, ConversationHandler, MessageHandler, Filters, CallbackQueryHandler, PollAnswerHandler\nfrom Bot import RoutesettingBot\n\n\ndef init_logger():\n logger = logging.getLogger()\n logger.setLevel(logging.INFO)\n fle_handler = logging.FileHandler('../data/logs', mode='w', encoding='UTF-16')\n fle_format = logging.Formatter('%(asctime)s - %(name)s - %(levelname)s - %(message)s')\n fle_handler.setFormatter(fle_format)\n logger.addHandler(fle_handler)\n\n\ndef main() -> None:\n init_logger()\n routesetter_bot = RoutesettingBot()\n with open('../data/token.txt') as token_file:\n token = token_file.read().strip()\n if not token:\n logging.log(logging.ERROR, 'No app token')\n return\n updater = Updater(token=token, use_context=True)\n dispatcher = updater.dispatcher\n start_handler = CommandHandler('start', routesetter_bot.setting_process.start)\n dispatcher.add_handler(start_handler)\n dispatcher.add_handler(CallbackQueryHandler(routesetter_bot.setting_process.handle_days, pattern=\"^WJ.+$\"))\n dispatcher.add_handler(CallbackQueryHandler(routesetter_bot.setting_process.add_setter, pattern=\"^add_setter$\"))\n admin_menu_handler = ConversationHandler(\n entry_points=[CommandHandler('admin_menu', routesetter_bot.admin_menu)],\n states={\n routesetter_bot.ADMIN_START: [\n CallbackQueryHandler(routesetter_bot.setting_process.end_period, pattern='^' + 'end_period' + '$'),\n CallbackQueryHandler(routesetter_bot.setting_process.change, pattern='^' + 'change' + '$'),\n CallbackQueryHandler(routesetter_bot.setting_process.add_setter_button, pattern='^' + 'add_setter' + '$'),\n CallbackQueryHandler(routesetter_bot.setting_process.remove_setter_button, pattern='^' + 'remove_setter' + '$'),\n ]}, fallbacks=[CommandHandler(\"stop\", routesetter_bot.stop)], conversation_timeout=120)\n dispatcher.add_handler(admin_menu_handler)\n user_menu_handler = ConversationHandler(entry_points=[CommandHandler('menu', routesetter_bot.user_menu)],\n states={\n routesetter_bot.START: [\n CallbackQueryHandler(routesetter_bot.setting_process.show_user_res,\n pattern='^' + 'show_results' + '$'),\n CallbackQueryHandler(routesetter_bot.setting_process.handle_richest,\n pattern='^' + 'richest' + '$'),\n CallbackQueryHandler(routesetter_bot.setting_process.add_single_res_button,\n pattern='^' + '3' + '$')]},\n # routesetter_bot.menu.AWAIT_RESULT: [\n # MessageHandler(Filters.regex(r'^\\d{2}\\.\\d{2}\\.\\d{4}( \\d){5} ?$'),\n # routesetter_bot.menu.add_single_results)]\n fallbacks=[CommandHandler(\"stop\", routesetter_bot.stop)],\n conversation_timeout=120)\n dispatcher.add_handler(user_menu_handler)\n dispatcher.add_handler(PollAnswerHandler(routesetter_bot.setting_process.receive_after_setting_poll))\n updater.start_polling(allowed_updates=Update.ALL_TYPES)\n updater.idle()\n\n\nif __name__ == \"__main__\":\n main()\n","repo_name":"kraslav4ik/Telegram-Routesetting-bot-Python","sub_path":"source/main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":3356,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"15"} +{"seq_id":"33587646670","text":"import sys\nimport io, os\n\ninput = io.BytesIO(os.read(0, os.fstat(0).st_size)).readline\n\nNC = int(input().decode())\nfor _ in range(NC):\n n = int(input().decode())\n cs = [0] * 240\n\n for h in map(int, input().decode().split()):\n cs[h] += 1\n\n not_first = False\n for i in range(231):\n for j in range(cs[i]):\n if not_first:\n sys.stdout.write(\" \" + str(i))\n else:\n sys.stdout.write(str(n))\n not_first = True\n sys.stdout.write(\"\\n\")\n","repo_name":"LeonardoNNanci/coding_challenges","sub_path":"Problems/Sorting/1566 - Height/ans.py","file_name":"ans.py","file_ext":"py","file_size_in_byte":524,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"15"} +{"seq_id":"70347735373","text":"#consts.py\n\n#---------------------------- SOUNDS ----------------------------\n#join sound path\njoinSoundPath = \"audio/Join/\"\n\n#jajao\njajao = \"audio/Highlander/Play/last_surprise.mp3\"\n\n#youtube audio path\nyoutubePath = \"audio/Youtube/\"\n\n#yt_dl options\n#ytdl_opts = {\n# 'format' : 'bestaudio/best',\n# 'postprocessors' : [{\n# 'key' : 'FFmpegExtractAudio',\n# 'preferredcodec' : 'mp3',\n# 'preferredquality' : '192'\n# }]\n#}\n","repo_name":"henrique93/Ganda-Bot","sub_path":"consts.py","file_name":"consts.py","file_ext":"py","file_size_in_byte":448,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"15"} +{"seq_id":"31685754988","text":"#!/usr/bin/env python\n\n# Robert Toomey July 2017\n# \n# Utility library class for reading pair values from a\n# configuration file\n\n# System imports\nimport getpass,os,sys,readline,multiprocessing\nfrom datetime import timedelta # Time for expire function\nfrom datetime import datetime\n\n# Relative imports\nfrom . import filecompleter\nfrom . import buildtools as b\n\nred = \"\\033[1;31m\"\nblue = \"\\033[1;34m\"\ngreen = \"\\033[1;32m\"\ncoff = \"\\033[0m\"\nline = \"------------------------------------------------\"\n\nclass Configuration:\n \"\"\" Configuration options \"\"\"\n\n def __init__(self):\n self.map1 = {}\n self.map2 = {}\n self.history = {}\n self.firstJobCheck = True\n\n def cleanText(self, line):\n \"\"\" Clean text line from config file \"\"\"\n l2 = line.rstrip('\\n') # Remove new lines\n l2 = l2.rstrip(' ') # Remove end spaces\n l2 = l2.split(\"#\", 1)[0] # Remove stuff post '#'\n return l2\n\n def readSplitFile(self, configFile, delimiter):\n \"\"\" Read a configuration file with 'pairs' separated by delimiter, return map of values \"\"\"\n map1= {}\n try:\n print(\"Reading file \"+configFile)\n with open(configFile, \"r\") as f:\n for line in f:\n l2 = self.cleanText(line)\n\n # If anything left of line...\n if l2 != \"\":\n pair = l2.split(delimiter) # Get name=value pair if any\n if (len(pair) == 2):\n pair[0] = self.cleanText(pair[0])\n pair[1] = self.cleanText(pair[1])\n map1[pair[0]] = pair[1]\n except Exception as e: # python 2.7 up\n error = \"Couldn't read file \"+configFile+\"\\nReason:\"+str(e)\n print(error)\n sys.exit()\n return map1\n \n def readConfig(self, configFile):\n \"\"\" Read a configuration file, return map of values \"\"\"\n self.map1 = self.readSplitFile(configFile, \"=\")\n return \"\"\n\n def readConfig2(self, configFile):\n \"\"\" Read Lak's configuration file, return map of values \"\"\"\n self.map2 = self.readSplitFile(configFile, \" \")\n return \"\"\n\n def addHistory(self, key, prompt, value):\n \"\"\" Add a line to the history \"\"\"\n self.history[key] = [prompt, value]\n \n def printHistory(self):\n \"\"\" Print out history of options chosen \"\"\"\n print(line)\n print(\"Final settings:\")\n for l in self.history:\n data = self.history[l]\n prompt = data[0]\n value = data[1]\n if value == False:\n value = red+str(value)+coff\n else:\n value = green+str(value)+coff\n #print(l+\" \"+prompt +\" --> \"+value)\n print(l+\" --> \"+value)\n #print(l)\n print(line)\n\n def printFileHistory(self, f):\n \"\"\" Print out history of options chosen \"\"\"\n for l in self.history:\n data = self.history[l]\n prompt = data[0]\n value = data[1]\n if value == False:\n value = str(value)\n else:\n value = str(value)\n f.write(l+\" --> \"+value+\"\\n\")\n \n\n def printConfig(self):\n \"\"\" Print out configuration \"\"\"\n print (self.map1)\n\n def setAutoFileComplete(self, flag):\n \"\"\" Turn on/off tabbed auto folder completion in input \"\"\"\n if flag == True:\n comp = filecompleter.Completer()\n readline.set_completer_delims(' \\t\\n;')\n readline.parse_and_bind(\"tab: complete\")\n readline.set_completer(comp.complete)\n else:\n readline.set_completer_delims('')\n readline.parse_and_bind(\"\")\n readline.set_completer(None)\n\n def printPrompt(self, key, prompt):\n \"\"\" Print prompt for a given key variable \"\"\"\n print(\"'\"+key+\"' \"+prompt)\n \n def promptFileDir(self, key, prompt, default_value):\n \"\"\" Prompt for a file or directory with autocomplete \"\"\"\n # Make the default option the true/false given\n o = default_value\n\n # Loop until good option\n self.setAutoFileComplete(True)\n print(line)\n while True:\n\n # Print prompt\n self.printPrompt(key,prompt)\n\n # Get input\n newo = b.getInput(o)\n\n # Finish if valid input\n # FIXME: test existance of dir/file? \n validDirFile = True\n \n if validDirFile:\n self.setAutoFileComplete(False)\n return newo\n\n def getFileDir(self, key, prompt, default_value):\n \"\"\" Get a file or dirname from configuration \"\"\"\n # FIXME: duplicates a lot from getString (merge common code)\n v = \"\"\n s = self.map1.get(key, \"\")\n if s != \"\":\n v = s\n else:\n ### Not in configureation file, so prompt for it...\n if prompt == \"\":\n return default_value\n else:\n #v = self.promptString(prompt, default_value)\n v = self.promptFileDir(key, prompt, default_value)\n\n self.addHistory(key, prompt, v)\n return v\n\n def promptString(self, key, prompt, defOption):\n \"\"\" Prompt for a string \"\"\"\n # Make the default option the true/false given\n o = defOption\n\n # Loop until good option\n self.setAutoFileComplete(False)\n print(line)\n while True:\n\n # Print prompt\n self.printPrompt(key,prompt)\n\n # Get input\n newo = b.getInput(o)\n\n # Finish if valid input\n return newo\n\n def getString(self, key, prompt, default_value):\n \"\"\" Get a string from configuration \"\"\"\n v = \"\"\n s = self.map1.get(key, \"\")\n if s != \"\":\n v = s\n else:\n ### Not in configureation file, so prompt for it...\n if prompt == \"\":\n #return default_value\n v = default_value\n else:\n v = self.promptString(key, prompt, default_value)\n\n self.addHistory(key, prompt, v)\n return v\n\n def getPassword(self, key, prompt, user):\n \"\"\" Get a password string \"\"\"\n o = self.getString(key, \"\", \"\")\n if o == \"\":\n print(line)\n print(\"To checkout I might need your \"+green+\"NSSL\"+coff+\" password (I'll keep it secret)\")\n o = getpass.getpass(green+user+\" Password:\"+coff)\n self.addHistory(key, prompt, \"{User entered}\")\n else:\n self.addHistory(key, prompt, \"{From configuration}\")\n return o\n\n def promptBoolean(self, key, prompt, default_value):\n \"\"\" Prompt for a boolean value \"\"\"\n # Make the default option the true/false given\n o = default_value\n\n # Loop until good option\n self.setAutoFileComplete(False)\n print(line)\n while True:\n\n # Print prompt\n self.printPrompt(key,prompt)\n\n # Get input\n newo = b.getInput(o)\n\n # Finish if valid input\n newo = newo.lower()\n if newo in [\"yes\",\"y\",\"true\"]:\n return True\n elif newo in [\"no\",\"n\",\"false\"]:\n return False\n\n def getBoolean(self, key, prompt, default_option):\n \"\"\" Get a boolean value from configuration \"\"\"\n v = False\n s = self.map1.get(key, \"\")\n s = s.lower()\n if s == \"yes\":\n v = True\n elif s == \"no\":\n v = False\n elif s == \"true\":\n v = True\n elif s == \"false\":\n v = False\n elif s == \"y\":\n v = True\n elif s == \"n\":\n v = False\n else:\n ### Not in configuration file, so prompt for it...\n if prompt == \"\":\n return default_value\n else:\n v = self.promptBoolean(key, prompt, default_option)\n \n self.addHistory(key, prompt, v)\n return v\n\n def getBooleanAuto(self, key, prompt, default_option, checkRequirements):\n \"\"\" Get a boolean value from configuration with a auto check function \"\"\"\n s = self.map1.get(key, \"\")\n s = s.lower()\n if s == \"auto\":\n flag = checkRequirements()\n self.addHistory(key, prompt+\" (auto checking)\", flag)\n return flag\n else:\n return self.getBoolean(key, prompt, default_option)\n \n\n########################################################################\n# Non 'regular configuration' file stuff. Could be a subclass...\n\n def getJobs(self):\n \"\"\" Get job flag for all makes \"\"\"\n if (self.firstJobCheck):\n o = self.getString(\"JOBS\", \"\", \"CPU\")\n if ((o == \"CPU\") or (o == \"\")):\n o =str(multiprocessing.cpu_count())\n self.addHistory(\"JOBS\", \"Number of make jobs for build?\", o)\n self.jobs = o\n else:\n o = self.jobs\n return o\n\n def getOurDFlags(self, mrmsVersion):\n \"\"\" Get expire data from configuration file \"\"\"\n # Current expire is only allowed D flag?\n expireinfo = \"\"\n aMap = {}\n v = self.getString(\"EXPIRE\", \"\", \"\")\n dateformat = \"%Y-%m-%d\" # 2017-Aug-18\n good = False\n \n # SUNRISE or now...\n #nowtime = datetime.utcnow()\n # Strange to match date +%s has to be now time not utcnow\n # +%s is seconds from utc 1970...is python %s not correct?\n nowtime = datetime.now() \n #print(\"NOW is \"+str(nowtime))\n #thestart = \"-DWDSSII_SUNRISE=\"+nowtime.strftime(\"%s\")\n aMap[\"WDSSII_SUNRISE\"] = nowtime.strftime(\"%s\")\n expireinfo = \"Sunrise=\"+nowtime.strftime(\"%Y-%m-%d\")\n #final = thestart\n\n # Check for empty string, which means don't expire\n if good == False:\n if v == \"\":\n self.addHistory(\"EXPIRE\", \"Expiration information\", expireinfo)\n return aMap\n #return final # no expire time\n\n # Check for seconds as integer\n if good == False:\n try: # to get an integer\n seconds = int(v)\n thentime = nowtime+timedelta(seconds=seconds)\n #print(\"EXPIRING build in \"+str(seconds)+\" seconds...\")\n good = True \n except Exception as e: # python 2.7 up\n pass # Don't print first error\n\n # Check for full exact date given\n if good == False:\n try: # to get a date string\n thentime = datetime.strptime(v, dateformat) # 2017-Aug-18\n # Check if date in future by at least a week:\n if (thentime-nowtime < timedelta(seconds=604800)):\n print(\"EXPIRE set to a date less than a week in future...\")\n sys.exit()\n good = True\n except Exception as e: # python 2.7 up\n print(\"Couldn't convert EXPIRE to number or date, date format is \"+dateformat)\n print(\"exception was: \"+str(e))\n sys.exit() # Do we recover? This is probably error in config file\n\n if good == True:\n #final += \" -DWDSSII_SUNSET=\"+thentime.strftime(\"%s\")\n #final += \" -DWDSSII_SUNSET=\"+thentime.strftime(\"%s\")\n aMap[\"WDSSII_SUNSET\"] = thentime.strftime(\"%s\")\n expireinfo = \" Sunset=\"+thentime.strftime(\"%Y-%m-%d\")\n\n self.addHistory(\"EXPIRE\", \"Expiration information\", expireinfo)\n return aMap # Map of name to value\n #return final\n\n def getAuthFileDItems(self, default_path):\n \"\"\" Get auth key flags from Lak's space paired configuration file \"\"\"\n v = self.getString(\"KEYFILE\", \"\", \"\")\n if v == \"WDSS2\":\n v = default_path # WDSS2 internal suggested path\n elif v == \"NONE\": \n return {} # Don't want it\n elif v == \"\":\n v = self.getFileDir(\"KEYFILE\", \"What WDSS2 authentication file do you want to use?\", default_path)\n self.readConfig2(v)\n return self.map2 # Map of name to value\n\n def mergeConfigLists(self, map1, map2):\n \"\"\" Merge two dictionaries where second map overrides first map \"\"\"\n finalmap = {}\n for k in map1:\n finalmap[k] = map1[k]\n for k in map2:\n # Check if there already?\n try:\n v = finalmap[k]\n print(\"--->Overrode key '\"+k+\"' value of '\"+v+\"' to value of '\"+map2[k]+\"'\")\n except Exception as e: # python 2.7 up\n pass\n finalmap[k] = map2[k]\n return finalmap\n\n def listToDFlags(self, map1):\n \"\"\" Take a dictionary and create -D string \"\"\"\n # Now create a single cppflag string with all \"-D\" options\n cppflags = \"\"\n for k in map1:\n if map1[k] == \"\":\n cppflags = cppflags +\"-D\"+k+\" \"\n else:\n cppflags = cppflags +\"-D\"+k+\"=\"+map1[k]+\" \"\n return cppflags\n","repo_name":"retoomey/RAPIOBuilder","sub_path":"mrmsbuilder/config.py","file_name":"config.py","file_ext":"py","file_size_in_byte":11557,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"15"} +{"seq_id":"6507276981","text":"import sys\nimport re\nfrom functools import reduce\nfrom bs4 import BeautifulSoup\n\nsys.path.append('../common/')\nfrom canpos import Canpos\n\n\nENR2_1_PATH = \"./data/aip-enr-2.1.html\"\nFUKUOKA_FIR_VAR_NAME = \"atcapp.DATA_FUKUOKA_FIR\"\n\ndef print_fukuoka_fir(table):\n ems = table.find('tbody').find('tr').find('td').find_all('em')\n coord_strs = [em.get_text() for em in ems if em.get_text() ]\n coord_strs = reduce(lambda x,y: x + y, [str.split('-') for str in coord_strs])\n # => ['4545N14000E', '4545N14200E', ...]\n assert coord_strs\n canpos_list = [\n Canpos.canpos_by_aip_coord(s) for s in coord_strs\n ]\n json = {'p': [c.round(4).to_r() for c in canpos_list]}\n print(\"{} = {};\".format(FUKUOKA_FIR_VAR_NAME, str(json)))\n\ndef main():\n html_raw = open(ENR2_1_PATH, 'r').read()\n soup = BeautifulSoup(html_raw, \"html.parser\")\n main_div = soup.find('div', {'id': 'ENR-2.1'})\n assert main_div, \"no main id div.\"\n tables = main_div.find_all('table')\n\n print_fukuoka_fir(tables[0])\n \n\nif(__name__ == '__main__'):\n main()\n","repo_name":"atc48/atcapp","sub_path":"pytool/aip/fukuoka_fir.py","file_name":"fukuoka_fir.py","file_ext":"py","file_size_in_byte":1072,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"15"} +{"seq_id":"73926794890","text":"\"\"\"\nDefinition of Interval.\nclass Interval(object):\n def __init__(self, start, end):\n self.start = start\n self.end = end\n\"\"\"\n\nclass Solution:\n \"\"\"\n @param intervals: Sorted interval list.\n @param newInterval: new interval.\n @return: A new interval list.\n \"\"\"\n def insert(self, intervals, newInterval):\n intervals.insert(0, newInterval)\n\n i = 0\n while i < len(intervals) - 1:\n if intervals[i].end < intervals[i + 1].start:\n break\n\n if intervals[i].start > intervals[i + 1].end:\n self.swap(intervals, i, i + 1)\n i += 1\n continue\n\n intervals[i] = self.merge(intervals[i], intervals[i + 1])\n intervals.pop(i + 1)\n\n return intervals\n\n\n def merge(self, a, b):\n return Interval(min(a.start, b.start), max(a.end, b.end))\n\n def swap(self, arr, i, j):\n temp = arr[i]\n arr[i] = arr[j]\n arr[j] = temp","repo_name":"ctc316/algorithm-python","sub_path":"Lintcode/Ladder_23_L/1_Easy/30. Insert Interval.py","file_name":"30. Insert Interval.py","file_ext":"py","file_size_in_byte":989,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"15"} +{"seq_id":"19812336903","text":"import decimal\nfrom typing import Any, Dict\nfrom datetime import date, datetime, timedelta\nfrom dataclasses import dataclass\n\nfrom django.db.models.query import QuerySet\nfrom django.db.models import Q\nfrom django.shortcuts import get_object_or_404\nfrom django.urls import reverse_lazy\nfrom django.utils.formats import date_format\nfrom django.views.generic import ListView, TemplateView, DetailView, CreateView, UpdateView, DeleteView\nfrom django.contrib.auth.mixins import LoginRequiredMixin, PermissionRequiredMixin\nfrom .models import LedgerAccount, LedgerEntry\nfrom .forms import LedgerEntryForm, LedgerAccountForm\nfrom balukaa.nav_main_list import MENU\n\n\nclass AccountsBookListView(LoginRequiredMixin, ListView):\n model = LedgerAccount\n template_name = 'ledger/accounts_book.html'\n context_object_name = 'accounts'\n\n def get_context_data(self, **kwargs):\n \"\"\" Переменные шаблона\n\n title = title сайта; заголовок navbar content\n btn_href = ссылка для кнопки navbar content\n btn_text = текст для кнопки navbar content\n cart_text = текст info-cart, вызываемой в случае отсутствия записей\n menu_list = список элементов dropdown меню: {item-group, item-text, item-url}\n \"\"\"\n context = super().get_context_data(**kwargs)\n context['title'] = 'План счетов'\n context['btn_href'] = reverse_lazy('ledger:account_create')\n context['btn_text'] = 'Новый счет'\n context['cart_text'] = 'В плане счетов нет записей!'\n context['menu_list'] = MENU\n return context\n\n def get_queryset(self):\n return LedgerAccount.objects.all().order_by('number')\n\n\nclass AccountView(LoginRequiredMixin, DetailView):\n permission_required = 'account.view_choice'\n model = LedgerAccount\n template_name = 'ledger/account.html'\n context_object_name = 'account'\n\n def get_context_data(self, **kwargs):\n \"\"\" Переменные шаблона\n\n title = title сайта; заголовок navbar content\n btn_href = ссылка для кнопки navbar content\n btn_text = текст для кнопки navbar content\n menu_list = список элементов dropdown меню: {item-group, item-text, item-url}\n \"\"\"\n context = super().get_context_data(**kwargs)\n context['title'] = 'Бухгалтерский счет'\n context['btn_href'] = reverse_lazy('ledger:accounts_book')\n context['btn_text'] = 'План счетов'\n context['menu_list'] = MENU\n return context\n\n def get_object(self):\n \"\"\" Переопределяем стандартное получение объекта для DetailView по pk или slug на number\n\n Посмотрел здесь:\n https://stackru.com/questions/54206946/django-detailview-putanitsa-v-funktsii-getobject\n \"\"\"\n return get_object_or_404(LedgerAccount, number=self.kwargs.get('number'))\n\n\nclass AccountCreateView(PermissionRequiredMixin, CreateView):\n permission_required = 'account.add_choice'\n model = LedgerAccount\n template_name = 'ledger/account_edit.html' # account_create.html\n context_object_name = 'account'\n form_class = LedgerAccountForm\n\n def get_context_data(self, **kwargs):\n \"\"\" Переменные шаблона\n\n title = title сайта; заголовок navbar content\n btn_href = ссылка для кнопки navbar content\n btn_text = текст для кнопки navbar content\n menu_list = список элементов dropdown меню: {item-group, item-text, item-url}\n \"\"\"\n context = super().get_context_data(**kwargs)\n context['title'] = f\"Создать бухгалтерский счет\"\n context['btn_href'] = reverse_lazy('ledger:accounts_book')\n context['btn_text'] = 'План счетов'\n context['menu_list'] = MENU\n return context\n\n\nclass AccountUpdateView(PermissionRequiredMixin, UpdateView):\n permission_required = 'account.change_choice'\n model = LedgerAccount\n template_name = 'ledger/account_edit.html'\n context_object_name = 'account'\n form_class = LedgerAccountForm\n\n def get_context_data(self, **kwargs):\n \"\"\" Переменные шаблона\n\n title = title сайта; заголовок navbar content\n btn_href = ссылка для кнопки navbar content\n btn_text = текст для кнопки navbar content\n menu_list = список элементов dropdown меню: {item-group, item-text, item-url}\n \"\"\"\n context = super().get_context_data(**kwargs)\n context['title'] = f\"Изменить бухгалтерский счет { self.kwargs.get('number') }\"\n context['btn_href'] = reverse_lazy('ledger:accounts_book')\n context['btn_text'] = 'План счетов'\n context['menu_list'] = MENU\n return context\n\n def get_object(self):\n \"\"\" Переопределяем стандартное получение объекта для UpdateView по pk или slug на number\n\n Посмотрел здесь:\n https://stackru.com/questions/54206946/django-detailview-putanitsa-v-funktsii-getobject\n \"\"\"\n return get_object_or_404(LedgerAccount, number=self.kwargs.get('number'))\n\n\nclass AccountDeleteView(PermissionRequiredMixin, DeleteView):\n permission_required = 'account.delete_choice'\n model = LedgerAccount\n template_name = 'ledger/account_delete.html'\n # TODO: разобраться почему не работает reverse('ledger:accounts_book')\n success_url = reverse_lazy('ledger:accounts_book')\n context_object_name = 'account'\n\n def get_context_data(self, **kwargs):\n \"\"\" Переменные шаблона\n\n title = title сайта; заголовок navbar content\n btn_href = ссылка для кнопки navbar content\n btn_text = текст для кнопки navbar content\n cart_text = текст info-cart, вызываемой в случае отсутствия записей\n menu_list = список элементов dropdown меню: {item-group, item-text, item-url}\n \"\"\"\n context = super().get_context_data(**kwargs)\n context['title'] = f\"Удалить счет: {context['account'].number} {context['account'].name}\"\n context['btn_href'] = reverse_lazy('ledger:accounts_book')\n context['btn_text'] = 'План счетов'\n\n # TODO: Добавить проверку, т.к. если проводка сохранена с пустыми счетами, выдает ошибку\n context['cart_text'] = f\"Счет: {context['account'].number} {context['account'].name}, \" \\\n f\"до удаления связанных с ним {context['account'].get_refs()} движений \" \\\n f\"в журнале проводок, удалить нельзя!\"\n context['menu_list'] = MENU\n return context\n\n def get_object(self):\n \"\"\" Переопределяем стандартное получение объекта для DetailView по pk или slug на number\n\n Посмотрел здесь:\n https://stackru.com/questions/54206946/django-detailview-putanitsa-v-funktsii-getobject\n \"\"\"\n return get_object_or_404(LedgerAccount, number=self.kwargs.get('number'))\n\n\nclass EntriesJournalListView(LoginRequiredMixin, ListView):\n model = LedgerEntry\n template_name = 'ledger/entries_journal.html'\n context_object_name = 'entries'\n\n def get_context_data(self, **kwargs):\n \"\"\" Переменные шаблона\n\n title = title сайта; заголовок navbar content\n btn_href = ссылка для кнопки navbar content\n btn_text = текст для кнопки navbar content\n cart_text = текст info-cart, вызываемой в случае отсутствия записей\n menu_list = список элементов dropdown меню: {item-group, item-text, item-url}\n \"\"\"\n context = super().get_context_data(**kwargs)\n context['title'] = 'Журнал проводок'\n context['btn_href'] = reverse_lazy('ledger:entry_create')\n context['btn_text'] = 'Новая проводка'\n context['cart_text'] = 'В журнале проводок нет записей!'\n context['menu_list'] = MENU\n return context\n\n\nclass EntryView(LoginRequiredMixin, DetailView):\n permission_required = 'entry.view_choice'\n model = LedgerEntry\n template_name = 'ledger/entry.html'\n context_object_name = 'entry'\n\n def get_context_data(self, **kwargs):\n \"\"\" Переменные шаблона\n\n title = title сайта; заголовок navbar content\n btn_href = ссылка для кнопки navbar content\n btn_text = текст для кнопки navbar content\n menu_list = список элементов dropdown меню: {item-group, item-text, item-url}\n \"\"\"\n context = super().get_context_data(**kwargs)\n context['title'] = 'Проводка'\n context['btn_href'] = reverse_lazy('ledger:entries_journal')\n context['btn_text'] = 'Журнал проводок'\n context['menu_list'] = MENU\n return context\n\n\nclass EntryCreateView(PermissionRequiredMixin, CreateView):\n # TODO: сделать валидацию, в т.ч. проверку на ввод счета-1 и счета-2\n # TODO: изучить возможность добавить проверку корректности проводок (пример: +50 +60, а не +60 +50)\n permission_required = 'entry.add_choice'\n model = LedgerEntry\n template_name = 'ledger/entry_edit.html' # entry_create.html\n context_object_name = 'entry'\n form_class = LedgerEntryForm\n\n def get_context_data(self, **kwargs):\n \"\"\" Переменные шаблона\n\n title = title сайта; заголовок navbar content\n btn_href = ссылка для кнопки navbar content\n btn_text = текст для кнопки navbar content\n menu_list = список элементов dropdown меню: {item-group, item-text, item-url}\n \"\"\"\n context = super().get_context_data(**kwargs)\n context['title'] = 'Создать проводку'\n context['btn_href'] = reverse_lazy('ledger:entries_journal')\n context['btn_text'] = 'Журнал проводок'\n context['menu_list'] = MENU\n return context\n\n\nclass EntryUpdateView(PermissionRequiredMixin, UpdateView):\n permission_required = 'entry.change_choice'\n model = LedgerEntry\n template_name = 'ledger/entry_edit.html'\n context_object_name = 'entry'\n form_class = LedgerEntryForm\n\n def get_context_data(self, **kwargs):\n \"\"\" Переменные шаблона\n\n title = title сайта; заголовок navbar content\n btn_href = ссылка для кнопки navbar content\n btn_text = текст для кнопки navbar content\n menu_list = список элементов dropdown меню: {item-group, item-text, item-url}\n \"\"\"\n context = super().get_context_data(**kwargs)\n context['title'] = f\"Изменить проводку id={ self.kwargs.get('pk') }\"\n context['btn_href'] = reverse_lazy('ledger:entries_journal')\n context['btn_text'] = 'Журнал проводок'\n context['menu_list'] = MENU\n return context\n\n\nclass EntryDeleteView(PermissionRequiredMixin, DeleteView):\n permission_required = 'entry.delete_choice'\n model = LedgerEntry\n template_name = 'ledger/entry_delete.html'\n # TODO: разобраться почему не работает reverse('ledger:entries_journal')\n success_url = reverse_lazy('ledger:entries_journal')\n context_object_name = 'entry'\n # form_class = LedgerEntryForm\n\n def get_context_data(self, **kwargs):\n \"\"\" Переменные шаблона\n\n title = title сайта; заголовок navbar content\n btn_href = ссылка для кнопки navbar content\n btn_text = текст для кнопки navbar content\n menu_list = список элементов dropdown меню: {item-group, item-text, item-url}\n \"\"\"\n context = super().get_context_data(**kwargs)\n context['title'] = f\"Удалить проводку id={ self.kwargs.get('pk') }\"\n context['btn_href'] = reverse_lazy('ledger:entries_journal')\n context['btn_text'] = 'Журнал проводок'\n context['menu_list'] = MENU\n return context\n\n\nclass MovementsReportListView(LoginRequiredMixin, ListView):\n template_name = 'ledger/movements_report.html'\n context_object_name = 'entries'\n\n def get_context_data(self, **kwargs):\n \"\"\" Переменные шаблона\n\n title = title сайта; заголовок navbar content\n btn_href = ссылка для кнопки navbar content\n btn_text = текст для кнопки navbar content\n cart_text = текст info-cart, вызываемой в случае отсутствия записей\n menu_list = список элементов dropdown меню: {item-group, item-text, item-url}\n \"\"\"\n context = super().get_context_data(**kwargs)\n context['title'] = 'Движения по журналу проводок'\n context['btn_href'] = reverse_lazy('ledger:entries_journal')\n context['btn_text'] = 'Журнал проводок'\n context['cart_text'] = 'В журнале проводок нет движений!'\n context['menu_list'] = MENU\n return context\n\n def get_queryset(self) -> QuerySet:\n queryset = LedgerEntry.objects.filter(\n status=LedgerEntry.Statuses.ENABLE\n ).order_by(\"date\")\n return queryset\n\n\n@dataclass\nclass AccountCardReportRow:\n account_date: date\n correspondent_account_number: str = ''\n correspondent_account_name: str = ''\n arrival: decimal.Decimal = '0'\n expense: decimal.Decimal = '0'\n current_balance: decimal.Decimal = '0'\n\n\nclass AccountCardReportView(LoginRequiredMixin, TemplateView):\n template_name = 'ledger/account_card_report.html'\n\n def get_context_data(self, **kwargs: Any) -> Dict[str, Any]:\n \"\"\" Переменные шаблона\n\n account_cart_rows = строка карточки\n date_from = дата начала периода расчета карточки\n date_to = дата конца периода расчета карточки\n account = счет по которому расчитывается карточка\n initial_state = начальное сальдо\n turnover_for_the_period = обороты за период\n balance = конечное сальдо\n\n title = title сайта; заголовок navbar content\n btn_href = ссылка для кнопки navbar content\n btn_text = текст для кнопки navbar content\n cart_text = текст info-cart, вызываемой в случае отсутствия записей\n menu_list = список элементов dropdown меню: {item-group, item-text, item-url}\n \"\"\"\n context = super().get_context_data(**kwargs)\n\n account = LedgerAccount.objects.get(number=kwargs['number'])\n\n # Здесь нужно найти минимальную дату в базе\n date_earliest = LedgerEntry.objects.earliest('date').date\n date_from = None\n date_to = None\n\n try:\n date_from = datetime.strptime(self.request.GET.get('from'), '%Y%m%d').date()\n except Exception:\n date_from = date_earliest\n try:\n date_to = datetime.strptime(self.request.GET.get('to'), '%Y%m%d').date()\n except Exception:\n date_to = LedgerEntry.objects.latest('date').date\n \n initial_state = account.get_remains(date_earliest, date_from - timedelta(days=1))\n turnover_for_the_period = account.get_remains(date_from, date_to)\n\n entries = LedgerEntry.objects.filter(\n Q(account_two=account.id) | Q(account_one=account.id),\n status=LedgerEntry.Statuses.ENABLE,\n date__gte=date_from,\n date__lte=date_to\n ).order_by('date')\n\n current_balance = initial_state['balance']\n account_cart_rows = []\n for entry in entries:\n row = AccountCardReportRow(entry.date)\n if entry.account_one != account:\n row.correspondent_account_number = str(entry.account_one.number)\n row.correspondent_account_name = entry.account_one.name\n if entry.type == LedgerEntry.EntryTypes.MOVE.value:\n row.arrival = entry.amount\n elif entry.type == LedgerEntry.EntryTypes.RISE.value:\n row.arrival = entry.amount\n else:\n row.expense = entry.amount\n elif entry.account_two != account:\n row.correspondent_account_number = str(entry.account_two.number)\n row.correspondent_account_name = entry.account_two.name\n if entry.type == LedgerEntry.EntryTypes.MOVE.value:\n row.expense = entry.amount\n elif entry.type == LedgerEntry.EntryTypes.RISE.value:\n row.arrival = entry.amount\n else:\n row.expense = entry.amount\n current_balance += decimal.Decimal(row.arrival) - decimal.Decimal(row.expense)\n row.current_balance = current_balance\n account_cart_rows.append(row)\n \n context['account_cart_rows'] = account_cart_rows\n context['date_from'] = date_from\n context['date_to'] = date_to\n context['account'] = account\n context['initial_state'] = initial_state\n context['turnover_for_the_period'] = turnover_for_the_period\n context['balance'] = initial_state['balance'] + turnover_for_the_period['balance']\n\n context['title'] = f'Карточка по счету: {account.number} {account.name} / ' \\\n f\"Фильтр: от { date_format(date_from, 'SHORT_DATE_FORMAT') } \" \\\n f\"до { date_format(date_to, 'SHORT_DATE_FORMAT') }\"\n context['btn_href'] = reverse_lazy('ledger:accounts_book')\n context['btn_text'] = 'План счетов'\n context['cart_text'] = f'В указанном периоде по счету: {account.number}\\xa0{account.name}, - не было движений!'\n context['menu_list'] = MENU\n return context\n\n\n@dataclass\nclass AccountBalanceReportRow:\n account_number: str = ''\n account_name: str = ''\n balance: decimal.Decimal = '0'\n\n\nclass AccountBalanceReportView(LoginRequiredMixin, TemplateView):\n \"\"\" Балансовый отчет на дату. Требует доработки !!!\n\n Надо:\n 1) сделать выбор даты на которую делается баланс\n 2) доработать Акт/Пас (изменчивые) счета -\n 2.1) если сальдо '+', то отображать в Пассивах (это наш долг), иначе в Активах (это долг нам)\n 2.2) в дальнейшем ту часть, например, Поставщиков, у которых сальдо '+', отображать в Пассивах,\n остальных в Активах (долги нам - это активы, которыми необходимо управлять)\n \"\"\"\n template_name = 'ledger/account_balance_report.html'\n\n def get_context_data(self, **kwargs: Any) -> Dict[str, Any]:\n \"\"\" Переменные шаблона\n\n active_accounts = активные счета для раздела Актива Баланса\n source_accounts = пассивные и изменчивые счета для раздела Пассива Баланса\n actives_balance = сальдо Активов\n sources_balance = сальдо Пассивов\n balance = баланс Активов и Пассивов - должен быть 0\n\n title = title сайта; заголовок navbar content\n btn_href = ссылка для кнопки navbar content\n btn_text = текст для кнопки navbar content\n menu_list = список элементов dropdown меню: {item-group, item-text, item-url}\n \"\"\"\n context = super().get_context_data(**kwargs)\n\n date_report = datetime.now() # В будущем сделать выбор даты !!!\n\n active_accounts = LedgerAccount.objects.filter(type=LedgerAccount.AccountTypes.ACTIVE)\n source_accounts = LedgerAccount.objects.filter(Q(type=LedgerAccount.AccountTypes.SOURCE) |\n Q(type=LedgerAccount.AccountTypes.VARIABLE))\n\n actives_balance = decimal.Decimal()\n active_accounts_rows = []\n for account in active_accounts:\n row = AccountBalanceReportRow()\n row.account_number = account.number\n row.account_name = account.name\n row.balance = account.get_account_balance(date_report)\n active_accounts_rows.append(row)\n actives_balance += row.balance\n\n sources_balance = decimal.Decimal()\n source_accounts_rows = []\n for account in source_accounts:\n row = AccountBalanceReportRow()\n row.account_number = account.number\n row.account_name = account.name\n row.balance = account.get_account_balance(date_report)\n source_accounts_rows.append(row)\n sources_balance += row.balance\n\n context['active_accounts'] = active_accounts_rows\n context['source_accounts'] = source_accounts_rows\n context['actives_balance'] = actives_balance\n context['sources_balance'] = sources_balance\n context['balance'] = actives_balance - sources_balance\n\n context['title'] = f\"Баланс на дату: {date_format(date_report, 'SHORT_DATE_FORMAT')}\"\n context['btn_href'] = reverse_lazy('ledger:accounts_book')\n context['btn_text'] = 'План счетов'\n context['menu_list'] = MENU\n return context\n","repo_name":"shaj/balukaa","sub_path":"balukaa/ledger/views.py","file_name":"views.py","file_ext":"py","file_size_in_byte":23258,"program_lang":"python","lang":"ru","doc_type":"code","stars":0,"dataset":"github-code","pt":"15"} +{"seq_id":"43447158603","text":"#!/usr/bin/env python3\n\nimport os\nimport requests\nfrom lxml import html\n\nclass Scraping:\n \t\t\n def scrapingImages(self,url):\n print(\"\\nGetting images from url:\"+ url)\n \n try:\n response = requests.get(url) \n parsed_body = html.fromstring(response.text)\n\n # regular expresion for get images\n images = parsed_body.xpath('//img/@src')\n\n print('Found images %s' % len(images))\n \n #create directory for save images\n os.system(\"mkdir images\")\n \n for image in images:\n if image.startswith(\"http\") == False:\n download = url + \"/\"+ image\n else:\n download = image\n print(download)\n # download images in images directory\n r = requests.get(download)\n f = open('images/%s' % download.split('/')[-1], 'wb')\n f.write(r.content)\n f.close()\n \n except Exception as e:\n print(\"Connection error in \" + url)\n pass\n \n def scrapingLinks(self,url):\n print(\"\\nGetting links from url:\"+ url)\n \n try:\n response = requests.get(url) \n parsed_body = html.fromstring(response.text)\n \n # regular expresion for get links\n links = parsed_body.xpath('//a/@href')\n \n print('Found links %s' % len(links))\n \n for link in links:\n print(link)\n \n except Exception as e:\n print(\"Connection error in \" + url)\n pass\n\t\t\t\t\t\nif __name__ == \"__main__\":\n\ttarget = \"https://news.ycombinator.com\"\n\tscraping = Scraping()\n\tscraping.scrapingImages(target)\n\tscraping.scrapingLinks(target)","repo_name":"PacktPublishing/Learning-Python-Networking-Second-Edition","sub_path":"Chapter04/lxml/get_links_images.py","file_name":"get_links_images.py","file_ext":"py","file_size_in_byte":1893,"program_lang":"python","lang":"en","doc_type":"code","stars":64,"dataset":"github-code","pt":"15"} +{"seq_id":"20288157555","text":"#!/usr/bin/env python\n\n\nimport json\nimport time\nimport scraping\nfrom scraping import storage\nfrom urllib.parse import urlparse\n\n\nredis = scraping.get_redis_connection()\npg = scraping.get_pg_connection()\n\n\ndef is_scheme_supported(parsed):\n supported = (parsed.scheme in [\"http\", \"https\"])\n if not supported:\n print(\"Unsupported scheme\", parsed.scheme)\n return supported\n\n\ndef is_domain_blacklisted(fqdn):\n sql = (\n \"SELECT id FROM blacklisted_domains\"\n \" WHERE fqdn=%s\"\n )\n\n with pg.cursor() as cur:\n cur.execute(sql, (fqdn,))\n r = cur.fetchone()\n if r:\n print(\"Blacklisted\", fqdn)\n return r\n\n\nclass URLFilter(scraping.mq.TaskFilter):\n def process(self, ch, method, properties, body):\n body = json.loads(body)\n parsed = urlparse(body[\"url\"])\n fqdn = parsed.hostname\n filtered_out = False\n if (not is_scheme_supported(parsed) or\n is_domain_blacklisted(fqdn)):\n filtered_out = True\n\n if not filtered_out:\n with pg.cursor() as cur:\n print(\"OK:\", parsed.geturl())\n domain_id = storage.store_domain(cur, fqdn)\n body[\"domain_id\"] = domain_id\n url_id = storage.store_url(cur, domain_id, parsed.geturl())\n body[\"url_id\"] = url_id\n cur.connection.commit()\n\n body.update(\n domain_id=domain_id,\n filter_ts=int(time.time())\n )\n self.publisher.publish(body, persistent=True)\n ch.basic_ack(delivery_tag=method.delivery_tag)\n\n\nflt = URLFilter(\n [\n scraping.config.rabbit_url,\n scraping.mq.ScrapingExchange,\n scraping.mq.ScrapingExchange.queues.url_unfiltered,\n ],\n [\n scraping.config.rabbit_url,\n scraping.mq.ScrapingExchange,\n scraping.mq.ScrapingExchange.queues.url_filtered,\n ],\n)\n\nflt.start()\n","repo_name":"mcptr/mechanoia","sub_path":"mechanoia-scraping/workers/url_filter.py","file_name":"url_filter.py","file_ext":"py","file_size_in_byte":1952,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"15"} +{"seq_id":"13031780330","text":"\"\"\" spider for crawl pandora_air.\nshedule of each direction \"\"\"\nimport json\n\nimport scrapy\nfrom ..airports import read_airports\nfrom ..proxies import ProxyList\nfrom ..items import ScheduleItem\nfrom ..flights import get_list_month\n\n\nclass ScheduleSpiderOld(scrapy.Spider):\n \"\"\" shedule attemp to crawl\"\"\"\n\n name = \"schedule_old\"\n\n def start_requests(self):\n \"\"\" need for scrapy framework\"\"\"\n proxy_list = ProxyList()\n proxy_list.refresh_proxy()\n\n airports = read_airports()\n urls = []\n for airport in airports:\n if airport[\"iataCode\"] == \"STN\": # fot test or for parallel?\n origin = airport[\"iataCode\"]\n for route in airport[\"routes\"]:\n type_route = route.split(\":\")[0]\n iata_code = route.split(\":\")[1]\n if type_route == \"airport\":\n destination = iata_code\n ordered_months = get_list_month(origin, destination)\n if ordered_months:\n for dat_item in ordered_months:\n urls.append(\n # f\"http://jhgkjhgj.pythonanywhere.com/timtbl/3/schedules/\"\n f\"https://services-api.pandora_air.com/timtbl/3/schedules/\"\n f\"{origin}/\"\n f\"{destination}/years/\"\n f\"{dat_item}\"\n )\n # print(urls[:10])\n # urls = urls[:10]\n for url in urls:\n next_proxy = \"http://\" + proxy_list.get_next()\n yield scrapy.Request(\n url=url,\n callback=self.parse,\n headers={\"content-type\": \"application/json\"},\n meta={\"proxy\": next_proxy},\n )\n\n def parse(self, response):\n full_answer = response.body\n full_answer_string = full_answer.decode(\"UTF-8\")\n answer_json = json.loads(full_answer_string)\n error_exist = answer_json.get(\"code\", '')\n if error_exist:\n yield\n url_list = response.url.split(\"/\")\n origin = url_list[6]\n destination = url_list[7]\n year = url_list[9]\n month = answer_json[\"month\"]\n all_days = answer_json[\"days\"]\n list_all_days = [one_day[\"day\"] for one_day in all_days]\n\n schedule_item = ScheduleItem()\n # schedule_item[\"origin\"] = origin\n # schedule_item[\"destination\"] = destination\n schedule_item[\"year\"] = year\n schedule_item[\"month\"] = month\n schedule_item[\"key\"] = origin + destination\n schedule_item[\"days\"] = list_all_days\n\n yield schedule_item\n","repo_name":"Vlad-Yekat/af-scraper","sub_path":"pandora_air/pandora_air/spiders/schedule_spider_old.py","file_name":"schedule_spider_old.py","file_ext":"py","file_size_in_byte":2776,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"15"} +{"seq_id":"74576961611","text":"from tkinter import*\n\ndef get_color(event):\n lb[\"bg\"] = lb.get(lb.curselection())\n\ndef set_color(event):\n lb[\"fg\"] = lb.get(lb.curselection())\n\ndef sort_color(event):\n L.sort()\n colorlist.set(tuple(L))\n\nwindow = Tk()\nwindow.title(\"Listbox\")\nL = [\"red\", \"yellow\", \"light blue\", \"orange\"]\ncolorlist = StringVar()\nlb = Listbox(window,width = 10, height = 5,listvariable = colorlist)\nlb.grid(padx=100 , pady=15)\ncolorlist.set(tuple(L))\n#换背景\n#lb.bind(\"<>\",get_color)\nlb.bind(\"<>\", set_color)\n#排序\n#lb.bind(\"\", sort_color)\nwindow.mainloop()","repo_name":"clhiker/WPython","sub_path":"Python/Python基础知识/GUI编程的主要控件/Listbox.py","file_name":"Listbox.py","file_ext":"py","file_size_in_byte":595,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"15"} +{"seq_id":"18695685719","text":"import pytest\n\nfrom ..max_path_sum import Triangle\n\n\n@pytest.fixture\ndef sample_triangle():\n triangle_height = 4\n triangle_data = [\n (3,),\n (7, 4),\n (2, 4, 6),\n (8, 5, 9, 3),\n ]\n return Triangle(triangle_height, triangle_data)\n\n\ntriangles_test_data = [\n (Triangle(0, []), 0),\n (Triangle(1, [(10,)]), 10),\n (Triangle(2, [(1,), (2, 3)]), 4),\n (Triangle(3, [(5,), (5, 10), (5, 10, 10)]), 25),\n (Triangle(4, [(3,), (10, 15), (20, 1, 15), (14, 15, 20, 10)]), 53),\n]\n\n\nclass TestTriangle:\n def test_creation_of_triangle_sample_triangle_data(self, sample_triangle):\n triangle_data = sample_triangle.row_data\n triangle_height = sample_triangle.height\n triangle = Triangle(triangle_height, triangle_data)\n assert isinstance(triangle, Triangle)\n\n def test_creation_of_triangle_empty_row_data_list(self):\n zero_triangle = Triangle(height=0, row_data=[])\n assert isinstance(zero_triangle, Triangle)\n\n def test_max_total_sum_sample_triangle(self, sample_triangle):\n assert sample_triangle.max_total_sum() == 23\n\n @pytest.mark.parametrize(\"triangle_in_test, max_total_sum\", triangles_test_data)\n def test_max_total_sum_valid_triangles_data(self, triangle_in_test, max_total_sum):\n triangle = triangle_in_test\n expected_max_total_sum = max_total_sum\n actual_max_total_sum = triangle.max_total_sum()\n assert actual_max_total_sum == expected_max_total_sum\n","repo_name":"alv2017/ProjectEuler","sub_path":"MaxPathSum/tests/test_max_path_sum.py","file_name":"test_max_path_sum.py","file_ext":"py","file_size_in_byte":1486,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"15"} +{"seq_id":"19766768304","text":"import spacy\nfrom ngrams import bigram, trigram, unigram\ndef main():\n # load English model\n nlp = spacy.load('en_core_web_sm')\n\n # create a document\n doc = nlp(\"This is just a great movie! The story is fantastic and engaging. The cinematography is exceptional and really on par with what you would expect from Cameron. I saw the movie in 3D twice and very happy I did. I originally thought it would be good but it got a hold of me like Avatar did. I tell everyone about it but I have this feeling it is going to have a cult following. I was not familiar with Alita prior to watching this movie but I think if they make more, I will be a long time fan. I recommend it. There is something for everyone in this movie. CG, Action, Romance, Etc... Definitely sequel worthy.\")\n\n result = bigram(doc)\n result2 = trigram(doc)\n result3 = unigram(doc)\n\n for element in result2:\n for token in element:\n print(token, end=' ')\n print()\n\n for element in result:\n for token in element:\n print(token, end=' ')\n print() # new line\n\n for element in result3:\n for token in element:\n print(token, end=' ')\n print() # new line\n\nmain()\n","repo_name":"wilramdhani/Ngrams-Wildan","sub_path":"n_grams_main.py","file_name":"n_grams_main.py","file_ext":"py","file_size_in_byte":1223,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"15"} +{"seq_id":"70123220491","text":"\"\"\"\r\nThis module contain every independent function\r\n\"\"\"\r\nfrom datetime import datetime\r\nimport requests\r\nimport os\r\nimport shutil\r\n\r\nfrom bs4 import BeautifulSoup\r\n\r\n\r\ndef console_log(log: str) -> None:\r\n \"\"\"\r\n This function log in the console with the date a log\r\n :param log: a text to log\r\n :return: None\r\n \"\"\"\r\n print(f\"{datetime.now()}: {log}\")\r\n\r\n\r\ndef has_role(user_roles: list, roles: list) -> bool:\r\n \"\"\"\r\n This function return True is the user has any role in role\r\n :param user_roles: roles owned by the user\r\n :param roles: list of roles to have\r\n :return: True if the user has any roles in common with the role list else return false\r\n \"\"\"\r\n # for each role owned by the user\r\n for u_role in user_roles:\r\n # for each role in list of roles\r\n for g_role in roles:\r\n\r\n if u_role == g_role:\r\n return True\r\n\r\n return False\r\n\r\n\r\ndef check_link(link: str, list_link: [str]) -> bool:\r\n \"\"\"\r\n This function will check if the domaine in link is in list_link and return true if the link have the good domains\r\n :param link: the link to check\r\n :param list_link: a list of domain to check\r\n :return:\r\n \"\"\"\r\n # for each domain\r\n for domain in list_link:\r\n # check if the link is long enough\r\n if len(link) > len(domain):\r\n # check the domain\r\n if link[:len(domain)] == domain or link[1:len(domain) + 1] == domain:\r\n return True\r\n return False\r\n\r\n\r\ndef delete_music_folder() -> None:\r\n \"\"\"\r\n This function will delete the entire content of the music folder\r\n :return: None\r\n \"\"\"\r\n folder = '/music/'\r\n for filename in os.listdir(folder):\r\n file_path = os.path.join(folder, filename)\r\n try:\r\n if os.path.isfile(file_path) or os.path.islink(file_path):\r\n os.unlink(file_path)\r\n elif os.path.isdir(file_path):\r\n shutil.rmtree(file_path)\r\n except Exception as e:\r\n print('Failed to delete %s. Reason: %s' % (file_path, e))","repo_name":"Adhoc-yt/DiscordMusicBot","sub_path":"utils.py","file_name":"utils.py","file_ext":"py","file_size_in_byte":2083,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"15"} +{"seq_id":"27967819907","text":"#!/usr/bin/env python3\n\nimport http.server\nimport socketserver\nimport ssl\nimport http.client\nimport urllib.parse\nimport socket\nfrom shutil import copyfileobj\nfrom lxml import etree\nfrom io import StringIO, BytesIO\nimport bredogen\nimport random\nimport argparse\nimport sys\n\n# Try to use gevent for light threading (improve performance)\nimport gevent\nfrom gevent import monkey\nmonkey.patch_all()\n\nclass MyHTTPRequestHandler(http.server.BaseHTTPRequestHandler):\n #protocol_version = 'HTTP/1.1' # allow HTTP/1.1 features\n\n def handle_one_request(self):\n try:\n self.raw_requestline = self.rfile.readline(65537)\n if len(self.raw_requestline) > 65536:\n self.requestline = ''\n self.request_version = ''\n self.command = ''\n self.send_error(HTTPStatus.REQUEST_URI_TOO_LONG)\n return\n if not self.raw_requestline:\n self.close_connection = True\n return\n if not self.parse_request():\n # An error code has been sent, just exit\n return\n\n self.custom_handle_request()\n\n self.wfile.flush() #actually send the response if not already done.\n except socket.timeout as e:\n #a read or a write timed out. Discard this connection\n self.log_error(\"Request timed out: %r\", e)\n self.close_connection = True\n return\n\n # Handle all http methods in one function\n def custom_handle_request(self):\n # Get site hostname\n self.sitehost = self.server.sitehost\n\n # Send request to upstream\n upstream_conn = http.client.HTTPSConnection(self.sitehost)\n upstream_conn.putrequest(self.command, self.path, skip_host=False, skip_accept_encoding=False)\n upstream_connection_close = False\n request_hostname = self.sitehost\n for k,v in list(self.headers.items()):\n if k.lower() == \"host\":\n request_hostname = v\n continue # skip the Host header\n elif k.lower() == \"server\":\n self.server_version = v\n continue # skip the Server header too\n elif k.lower() == \"connection\" and v.lower() == \"close\":\n upstream_connection_close = True\n upstream_conn.putheader(k, v)\n if not upstream_connection_close:\n # force connection-close for upstream\n upstream_conn.putheader(\"Connection\", \"close\")\n upstream_conn.endheaders()\n\n # Receive response headers from upstream\n upstream_resp = upstream_conn.getresponse()\n response_content_length = -1\n response_chunked = False\n response_content_type = \"\"\n response_content_encoding = None\n upstream_headers = []\n for k,v in upstream_resp.getheaders():\n if k.lower().strip() == 'connection' and v.lower().strip() == 'close':\n self.close_connection = True\n elif k.lower().strip() == 'content-length':\n response_content_length = int(v)\n continue # filter this\n elif k.lower().strip() == \"transfer-encoding\" and \"chunked\" in v.lower():\n response_chunked = True\n continue # filter this too\n elif k.lower().strip() == 'content-encoding':\n response_content_encoding = v\n continue # filter this too\n elif k.lower().strip() == 'content-type':\n response_content_type = v\n upstream_headers.append((k,v))\n\n body = None\n if upstream_resp.status == 200 and \"html\" in response_content_type.lower():\n if response_chunked:\n body = self.process_html(upstream_resp.read(), request_hostname) # python already implements dechunking internally\n response_content_length = len(body)\n response_content_encoding = None\n elif response_content_length >= 0:\n body = self.process_html(upstream_resp.read(response_content_length), request_hostname)\n response_content_length = len(body)\n response_content_encoding = None\n\n # Send response headers to the client\n self.send_response(upstream_resp.status, upstream_resp.reason)\n\n for k,v in upstream_headers:\n self.send_header(k, v)\n # send (possibly updated) content-length to upstream\n if response_content_length >= 0:\n self.send_header(\"Content-Length\", str(response_content_length))\n if response_content_encoding != None:\n self.send_header(\"Content-Encoding\", response_content_encoding)\n self.end_headers()\n\n if body != None:\n # Send modified body response\n self.wfile.write(body)\n else:\n # Path-through unmodified response body\n copyfileobj(upstream_resp, self.wfile)\n\n def process_html(self, body, request_hostname):\n parser = etree.HTMLParser()\n tree = etree.parse(BytesIO(body), parser)\n\n # URL rewriting\n for a in tree.getroot().xpath(\".//a\"):\n url = a.get('href')\n if url and self.sitehost in url:\n url = url.replace(self.sitehost, request_hostname)\n a.set('href', url)\n\n for t in tree.getroot().xpath(\".//text()\"):\n if t.getparent().tag in (\"span\", \"div\", \"strong\", \"a\", \"h1\", \"h2\", \"h3\", \"h4\", \"p\"):\n if t.getparent().text and len(t.getparent().text.strip()) > 0:\n src = t.getparent().text\n # Skip all-digit strings\n if src.lower().strip().replace(':','').replace('.','').replace(';','').isdigit():\n continue\n t.getparent().text = bredogen.process(src)\n\n return etree.tostring(tree.getroot(), pretty_print=True, method=\"html\")\n\n# TODO: use this after logic works with normal http server\nclass MyHTTPServer(socketserver.ThreadingMixIn, http.server.HTTPServer):\n daemon_threads = True\n\ndef main():\n parser = argparse.ArgumentParser(description='Bredogen HTTP(S) proxy (courtesy Borisich)')\n parser.add_argument('-l', '--listen', type=str, default='443', help='listen in the form [ip:]port (default 443)')\n parser.add_argument('-c', '--certfile', type=str, help='')\n parser.add_argument('hostname', type=str, help='site hostname')\n args = parser.parse_args()\n\n if args.certfile == None:\n sys.stderr.write(\"error: You must specify --certfile!\\n\")\n parser.print_usage(sys.stderr)\n sys.exit()\n\n if ':' in args.listen:\n addr, port = args.listen.split(':', 1)\n else:\n addr, port = '', args.listen\n port = int(port)\n\n print(\"Starting HTTPS Server listening on {addr}:{port} certfile='{certfile}' upstream '{hostname}' ...\".format(\n addr=addr, port=port, certfile=args.certfile, hostname=args.hostname)\n )\n\n httpd = MyHTTPServer((addr, port), MyHTTPRequestHandler)\n httpd.socket = ssl.wrap_socket(httpd.socket, certfile = args.certfile, server_side = True, cert_reqs=ssl.CERT_OPTIONAL)\n # Store site hostname on the \"server\" object, so it is available for request handlers\n httpd.sitehost = args.hostname\n httpd.serve_forever()\n\nif __name__ == '__main__':\n main()\n\n","repo_name":"borisshvonder/bredogen","sub_path":"brproxy.py","file_name":"brproxy.py","file_ext":"py","file_size_in_byte":7375,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"15"} +{"seq_id":"25985650181","text":"import os\nimport numpy as np\nimport torchvision\nfrom PIL import Image\nimport matplotlib.pyplot as plt\nfrom skimage.metrics import structural_similarity, peak_signal_noise_ratio\n\n\ndef plot_image(images):\n \"\"\"\n Plots the image provided\n :param images: Image as Torch Tensor\n :return: None\n \"\"\"\n\n grid = torchvision.utils.make_grid(images.clamp(min=-1, max=1), scale_each=True, normalize=True)\n grid_image = grid.permute(1, 2, 0).cpu().numpy()\n plt.imshow(grid_image)\n plt.show()\n\n\ndef save_image(images, save_path, mode, iteration=None):\n \"\"\"\n Save the image provided\n :param images: Image as a Torch tensor\n :param save_path: Path to which image is to be saved\n :param mode: Folder to which image has to be saved\n :param iteration: Optional iteration count\n :return: None\n \"\"\"\n\n PATH = f\"{save_path}/{mode}\"\n os.makedirs(PATH, exist_ok=True)\n\n grid = torchvision.utils.make_grid(images.clamp(min=-1, max=1), scale_each=True, normalize=True)\n grid_image = grid.permute(1, 2, 0).cpu().numpy()\n plt.imshow(grid_image)\n\n if iteration:\n plt.imsave(f\"{PATH}/image_{iteration}.png\", grid_image)\n else:\n plt.imsave(f\"{PATH}/original_image.png\", grid_image)\n\n\ndef RGBA2RGB(image):\n \"\"\"\n Converts an 4 channel RGBA image to 3 channel RGB image\n :param image: Image to be converted to RGB\n :return: RGB image\n \"\"\"\n\n if image.shape[-1] == 3:\n return image\n\n rgba_image = Image.fromarray(image)\n rgba_image.load()\n rgb_image = Image.new(\"RGB\", rgba_image.size, (255, 255, 255))\n rgb_image.paste(rgba_image, mask=rgba_image.split()[3])\n\n return np.array(rgb_image)\n\n\ndef metrics(firstImage, secondImage):\n \"\"\"\n Calculates and returns SSIM and PSNR for a pair of images\n :param firstImage: First Image\n :param secondImage: Second Image\n :return: Metrics Dictionary\n \"\"\"\n\n firstImage = firstImage\n secondImage = secondImage\n\n firstImage = RGBA2RGB(firstImage)\n secondImage = RGBA2RGB(secondImage)\n\n ssim = structural_similarity(\n firstImage, secondImage, data_range=firstImage.max() - firstImage.min(), multichannel=True\n )\n psnr = peak_signal_noise_ratio(firstImage, secondImage, data_range=firstImage.max() - firstImage.min())\n\n image_metrics = {\"SSIM\": ssim, \"PSNR\": psnr}\n\n return image_metrics\n","repo_name":"vineeths96/Generative-Image-Compression","sub_path":"src/utils.py","file_name":"utils.py","file_ext":"py","file_size_in_byte":2360,"program_lang":"python","lang":"en","doc_type":"code","stars":7,"dataset":"github-code","pt":"15"} +{"seq_id":"38681968670","text":"import json\nimport cv2\nimport numpy as np\n\n\ndef facialRecognition():\n\n detector = cv2.CascadeClassifier(\n 'haarcascade/haarcascade_frontalface_default.xml')\n cam = cv2.VideoCapture(0)\n recognizer = cv2.face.LBPHFaceRecognizer_create()\n recognizer.read('trainner/trainner.yml')\n font = cv2.FONT_HERSHEY_COMPLEX\n\n # importing the module json and read the data from the file\n with open('idCorresp/memoryFile') as f:\n data = f.read()\n # reconstructing the data as a dictionary\n nameCorrespondance = json.loads(data)\n\n continuer = True\n while(continuer):\n ret, img = cam.read()\n gray = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)\n faces = detector.detectMultiScale(gray, 1.3, 5)\n\n for (x, y, w, h) in faces:\n cv2.rectangle(img, (x, y), (x+w, y+h), (255, 0, 0), 2)\n idPerson, conf = recognizer.predict(gray[y:y+h, x:x+w])\n try:\n idName = nameCorrespondance[str(idPerson)]\n except KeyError:\n idName = \"unknown\"\n\n cv2.putText(img, str(idName), (x, y+h), font, 1.5, (15, 0, 255))\n\n cv2.imshow('frame', img)\n\n if cv2.waitKey(1) and 0xFF == ord('q'):\n break\n\n if cv2.getWindowProperty('frame', cv2.WND_PROP_VISIBLE) < 1:\n break\n\n cam.release()\n cv2.destroyAllWindows()\n\n\nif __name__ == \"__main__\":\n facialRecognition()\n","repo_name":"Nausicaa68/Facial-recognition","sub_path":"detector.py","file_name":"detector.py","file_ext":"py","file_size_in_byte":1414,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"15"} +{"seq_id":"16873253848","text":"import logging\nimport time\nfrom calendar import timegm\nfrom datetime import datetime\nfrom typing import Dict, Tuple\n\nLOG: logging.Logger = logging.getLogger(__name__)\n\n_BASE_URL: str = \"https://api.netatmo.com/\"\n\nERRORS: Dict[int, str] = {\n 400: \"Bad request\",\n 401: \"Unauthorized\",\n 403: \"Forbidden\",\n 404: \"Not found\",\n 406: \"Not Acceptable\",\n 500: \"Internal Server Error\",\n 502: \"Bad Gateway\",\n 503: \"Service Unavailable\",\n}\n\n\ndef to_time_string(value: str) -> str:\n return datetime.utcfromtimestamp(int(value)).isoformat(sep=\"_\")\n\n\ndef to_epoch(value: str) -> int:\n return timegm(time.strptime(value + \"GMT\", \"%Y-%m-%d_%H:%M:%S%Z\"))\n\n\ndef today_stamps() -> Tuple[int, int]:\n today: int = timegm(time.strptime(time.strftime(\"%Y-%m-%d\") + \"GMT\", \"%Y-%m-%d%Z\"))\n return today, today + 3600 * 24\n\n\ndef fix_id(raw_data: Dict) -> Dict:\n if raw_data:\n for station in raw_data:\n station[\"_id\"] = station[\"_id\"].replace(\" \", \"\")\n for module in station.get(\"modules\", {}):\n module[\"_id\"] = module[\"_id\"].replace(\" \", \"\")\n return raw_data\n","repo_name":"vlebourl/home-assistant-config","sub_path":"custom_components/netatmo/pyatmo/helpers.py","file_name":"helpers.py","file_ext":"py","file_size_in_byte":1118,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"15"} +{"seq_id":"37653154147","text":"import numpy as np\nimport yaml\nimport cv2\n\nclass StereoCamera():\n def __init__(self, cal_file_path, rectify = True, downscale_factor = 2, scale_baseline=1e-3):\n # Load cal file and get all the parameters\n # scale_baseline scales the baseline (i.e. converts units from mm to m!)\n f = open(cal_file_path)\n cal_data = yaml.load(f, Loader=yaml.FullLoader)\n \n self.K1 = np.array(cal_data['K1']['data']).reshape(3,3)\n self.K2 = np.array(cal_data['K2']['data']).reshape(3,3)\n self.D1 = np.array(cal_data['D1']['data'])\n self.D2 = np.array(cal_data['D2']['data'])\n \n self.rotation = np.array(cal_data['R']['data']).reshape(3,3)\n self.translation = np.array(cal_data['T'])*scale_baseline\n self.T = np.eye(4)\n \n # Downscale stuff\n self.downscale_factor = downscale_factor\n self.img_size = np.array(cal_data['ImageSize'])/self.downscale_factor\n self.img_size = ( int(self.img_size[1]), int(self.img_size[0]) )\n self.K1 = self.K1/self.downscale_factor\n self.K2 = self.K2/self.downscale_factor\n \n self.K1[-1, -1] = 1\n self.K2[-1, -1] = 1\n \n # Prepare undistort and rectification (if desired) here\n if rectify:\n R1, R2, P1, P2, Q, roi1, roi2 = cv2.stereoRectify(self.K1, self.D1, self.K2, self.D2, \n self.img_size, self.rotation, self.translation)\n self.left_map1, self.left_map2 = cv2.initUndistortRectifyMap(self.K1, self.D1, R1, P1[:,:-1], \n self.img_size, cv2.CV_32FC1)\n self.right_map1, self.right_map2 = cv2.initUndistortRectifyMap(self.K2, self.D2, R2, P2[:,:-1], \n self.img_size, cv2.CV_32FC1)\n self.K1 = P1[:,:-1]\n self.K2 = P2[:,:-1]\n \n self.rotation = np.eye(3)\n self.translation = np.linalg.norm(self.translation)*P2[:, -1]/np.linalg.norm(P2[:, -1])\n\n else:\n self.left_map1, self.left_map2 = cv2.initUndistortRectifyMap(self.K1, self.D1, np.eye(3), self.K1, \n self.img_size, cv2.CV_32FC1)\n self.right_map1, self.right_map2 = cv2.initUndistortRectifyMap(self.K2, self.D2, np.eye(3), self.K2, \n self.img_size, cv2.CV_32FC1)\n self.T[:3, :3] = self.rotation\n self.T[:3, -1] = self.translation\n \n def processImage(self, left_image, right_image):\n left_image = cv2.resize(left_image, self.img_size)\n right_image = cv2.resize(right_image, self.img_size)\n left_image = cv2.remap(left_image, self.left_map1, self.left_map2, interpolation=cv2.INTER_LINEAR)\n right_image = cv2.remap(right_image, self.right_map1, self.right_map2, interpolation=cv2.INTER_LINEAR)\n \n return left_image, right_image\n\n def projectPoints(self, points):\n # points is Nx3 np array\n points = np.transpose(points)\n projected_point_l = np.transpose(np.dot(self.K1, points/points[-1,:]))[:,:-1]\n \n points_homogeneous = np.concatenate( (points, np.ones((1, points.shape[1]))) )\n points_r = np.dot(self.T, points_homogeneous)[:-1, :]\n \n projected_point_r = np.transpose(np.dot(self.K2, points_r/points_r[-1,:]))[:,:-1]\n \n return projected_point_l, projected_point_r\n","repo_name":"ucsdarclab/surgical_tool_tracking","sub_path":"core/StereoCamera.py","file_name":"StereoCamera.py","file_ext":"py","file_size_in_byte":3638,"program_lang":"python","lang":"en","doc_type":"code","stars":2,"dataset":"github-code","pt":"15"} +{"seq_id":"23846911978","text":"# Escreva um algoritmo para ler o número total de eleitores de um município, o número de votos\r\n# brancos, nulos e válidos. Calcular e escrever o percentual que cada um representa em relação ao total\r\n# de eleitores.\r\n\r\n# Criação das variáveis\r\nnumeroTotalEleitores=int(input(\"Digite o número total de eleitores:\"))\r\nnumeroTotalVotosBrancos=int(input(\"Digite o número total de votos brancos:\"))\r\nnumeroTotalVotosNulos=int(input(\"Digite o número total de votos nulos:\"))\r\nnumeroTotalVotosValidos=int(input(\"Digite o número total de votos válidos:\"))\r\n# Processamento\r\nporcetagemVotosBrancos=numeroTotalVotosBrancos/numeroTotalEleitores*100\r\nporcetagemVotosNulos=numeroTotalVotosNulos/numeroTotalEleitores*100\r\nporcetagemVotosValidos=numeroTotalVotosValidos/numeroTotalEleitores*100\r\n# Saída\r\nprint(\"A porcentagem de votos brancos corresponde a : {} %\".format(porcetagemVotosBrancos))\r\nprint(\"A porcentagem de votos nulos corresponde a : {} %\".format(porcetagemVotosNulos))\r\nprint(\"A porcentagem de votos válidos corresponde a : {} %\".format(porcetagemVotosValidos))\r\n","repo_name":"professorobama/Linguagem-de-Programacao-Python","sub_path":"Exercicio08.py","file_name":"Exercicio08.py","file_ext":"py","file_size_in_byte":1082,"program_lang":"python","lang":"pt","doc_type":"code","stars":15,"dataset":"github-code","pt":"15"} +{"seq_id":"37639615197","text":"#BOJ1977_완전제곱수_B\n#https://www.acmicpc.net/problem/1977\n\nm = int(input())\nn = int(input())\n\nhap = 0\ncheck = 0\n\nfor i in range(1, 101):\n if m <= i*i and n >= i*i:\n if hap == 0:\n check = i*i\n hap += i*i\n\nif hap == 0:\n print(-1)\n\nelse:\n print(hap)\n print(check)","repo_name":"Namdarun/Algorithm-BOJ","sub_path":"Bronze/BOJ1977완전제곱수.py","file_name":"BOJ1977완전제곱수.py","file_ext":"py","file_size_in_byte":304,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"15"} +{"seq_id":"40895906018","text":"import os\nimport subprocess\n\nfrom validators import url as check_url\nfrom git import Repo, GitCommandError\n\nfrom src.archivist.errors.errors import UNSUPPORTED_URL\n\n\nclass Crawler:\n \"\"\"\n Crawler class responsible for cloning Git repositories.\n \"\"\"\n\n def __init__(self, repo_url: str, output_path: str):\n \"\"\"\n Initialize the Crawler object.\n\n Args:\n repo_url (str): The URL of the Git repository to clone.\n output_path (str): The directory where the repository will be cloned.\n\n Raises:\n ValueError: If `repo_url` is invalid.\n ValueError: If `output_path` is invalid.\n \"\"\"\n # TODO: Switch to a common url validator.\n self.repo_url = repo_url\n self.output_path = output_path\n\n def validate_repo_url(self) -> bool:\n \"\"\"\n Validates the given Git repository URL.\n\n Returns:\n bool: True if the URL is valid, False otherwise.\n\n Raises:\n ConnectionError: If unable to connect to the repository.\n ValueError: If the URL is empty.\n \"\"\"\n # Check for an empty URL\n if not self.repo_url:\n raise ValueError(\"Repository URL cannot be empty.\")\n\n # Validate the URL\n if not check_url(self.repo_url):\n raise ConnectionError(\"Invalid or unreachable repository URL.\")\n\n return True\n\n\n def prepare_output_path(self) -> bool:\n \"\"\"\n Prepares the output directory path. Creates it if it doesn't exist.\n\n Returns:\n bool: True if the path is valid or successfully created, False otherwise.\n\n Raises:\n PermissionError: If the program lacks write permission to create the directory.\n \"\"\"\n if os.path.exists(self.output_path):\n return True\n\n try:\n os.makedirs(self.output_path)\n except PermissionError:\n raise PermissionError(f\"Permission denied: Cannot create directory at {self.output_path}.\")\n\n return True\n\n def clone_repo(self) -> str:\n \"\"\"\n Clones the Git repository to the specified output path.\n\n Returns:\n str: The path to the root of the cloned repository.\n\n Raises:\n GitCommandError: If the git clone operation fails.\n \"\"\"\n try:\n Repo.clone_from(self.repo_url, self.output_path)\n except GitCommandError as e:\n raise GitCommandError(f\"Git clone operation failed: {str(e)}\")\n\n return self.output_path\n\n def execute(self) -> str:\n \"\"\"\n Orchestrates the whole cloning operation.\n\n Returns:\n str: The path to the root of the cloned repository.\n\n Raises:\n Exception: If any step in the operation fails.\n \"\"\"\n try:\n self.validate_repo_url()\n self.prepare_output_path()\n return self.clone_repo()\n except Exception as e:\n raise Exception(f\"Cloning operation failed: {str(e)}\")\n","repo_name":"Brad-Edwards/archivist","sub_path":"src/archivist/crawler/crawler.py","file_name":"crawler.py","file_ext":"py","file_size_in_byte":3032,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"15"} +{"seq_id":"19433049592","text":"import discord\nfrom discord.ext import commands\n\n\nasync def getchannellist(bot, sortchars):\n bot.paginator.clear()\n f = open(\"channels.txt\", \"r\", encoding='utf16')\n lines = f.readlines()\n lines.sort(key=str.lower)\n for x in lines:\n if sortchars == '':\n bot.paginator.add_line(x)\n elif x[0].lower() in sortchars:\n bot.paginator.add_line(x)\n if len(bot.paginator.pages) == 0:\n bot.paginator.add_line(\"No channels found.\")\n\n\nasync def getsearchresponse(bot, query):\n bot.paginator.clear()\n f = open(\"channels.txt\", \"r\", encoding='utf16')\n lines = f.readlines()\n lines.sort(key=str.lower)\n for x in lines:\n if query.lower() in x.rsplit(\" - \", 1)[0].lower():\n bot.paginator.add_line(x)\n if len(bot.paginator.pages) == 0:\n bot.paginator.add_line(\"No channels found.\")\n\n\nclass ChannelList(commands.Cog):\n\n def __init__(self, bot):\n self.bot = bot\n\n @commands.command(name=\"channelsfile\", aliases=[\"chanout\", \"gibfile\"])\n async def channelsfile(self, ctx):\n await ctx.send(file=discord.File('channels.txt'))\n\n async def updatemsg(self, msg):\n reactions = [u\"\\u25C0\", u\"\\u25B6\"]\n page = self.bot.page\n pages = self.bot.paginator.pages\n await msg.clear_reactions()\n await msg.edit(content=f'{pages[page]}\\n\\t\\tYou are viewing page {page + 1} of {len(pages)}')\n if page == 0:\n await msg.add_reaction(reactions[1])\n elif page == len(pages) - 1:\n await msg.add_reaction(reactions[0])\n else:\n for reaction in reactions:\n await msg.add_reaction(reaction)\n\n @commands.command(name=\"listchannels\", aliases=[\"listchan\", \"lchan\"])\n async def listchannels(self, ctx, sortchars=''):\n await getchannellist(ctx.bot, sortchars)\n ctx.bot.page = page = 0\n pages = ctx.bot.paginator.pages\n if len(pages) == 1:\n await ctx.send(content=f'{pages[page]}')\n return\n else:\n msg = await ctx.send(content=f'{pages[page]}\\n\\t\\tYou are viewing page {page + 1} of {len(pages)}')\n await msg.add_reaction(u\"\\u25B6\")\n\n @commands.command(name=\"search\")\n async def search(self, ctx, *, query):\n if len(query) < 3:\n await ctx.send(\"Search request must be at least 3 characters in length.\")\n return\n await getsearchresponse(ctx.bot, query)\n page = ctx.bot.page\n pages = ctx.bot.paginator.pages\n if len(pages) == 1:\n await ctx.send(content=f'{pages[page]}')\n return\n else:\n msg = await ctx.send(content=f'{pages[page]}\\n\\t\\tYou are viewing page {page + 1} of {len(pages)}')\n await msg.add_reaction(u\"\\u25B6\")\n\n @commands.command(name=\"ahelp\")\n async def ahelp(self, ctx):\n await ctx.send(\"use channel link\")\n\n @commands.command(name=\"giverole\")\n @commands.cooldown(1, 60, commands.BucketType.user)\n async def giverole(self, ctx):\n role = discord.utils.get(ctx.message.author.guild.roles, name=\"YT Archive\")\n user = ctx.message.author\n if role not in ctx.message.author.roles:\n await user.add_roles(role)\n await ctx.send(\"Role given, enjoy.\")\n else:\n await user.remove_roles(role)\n await ctx.send(\"Role removed, enjoy.\")\n\n @commands.Cog.listener()\n async def on_reaction_add(self, reaction, user):\n if user.bot:\n return\n if not reaction.message.author.bot:\n return\n if \"You are viewing page\" not in reaction.message.content:\n return\n if reaction.emoji == \"◀\":\n if self.bot.page == 0:\n return\n else:\n self.bot.page -= 1\n elif reaction.emoji == \"▶\":\n self.bot.page += 1\n await self.updatemsg(reaction.message)\n\n\ndef setup(bot):\n bot.add_cog(ChannelList(bot))\n","repo_name":"Ditiae/ConversionBot","sub_path":"src/channellist.py","file_name":"channellist.py","file_ext":"py","file_size_in_byte":3980,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"15"} +{"seq_id":"39199610757","text":"import flask\nimport functools\nimport hashlib\nimport math\nimport os\nimport pathlib\nimport random\nimport string\nimport pymysql\nimport pymysql.cursors\nfrom pymysql.cursors import Cursor\nfrom flask import send_from_directory\nfrom uuid import uuid4\n\n\nstatic_folder = pathlib.Path(__file__).resolve().parent.parent / \"public\"\nicons_folder = \"/shared-web-app/icons\"\napp = flask.Flask(__name__, static_folder=str(static_folder), static_url_path=\"\")\napp.secret_key = \"tonymoris\"\navatar_max_size = 1 * 1024 * 1024\n\nif not os.path.exists(str(icons_folder)):\n os.makedirs(str(icons_folder))\n\nconfig = {\n \"db_host\": os.environ.get(\"ISUBATA_DB_HOST\", \"localhost\"),\n \"db_port\": int(os.environ.get(\"ISUBATA_DB_PORT\", \"3306\")),\n \"db_user\": os.environ.get(\"ISUBATA_DB_USER\", \"root\"),\n \"db_password\": os.environ.get(\"ISUBATA_DB_PASSWORD\", \"\"),\n}\n\n\ndef dbh():\n if hasattr(flask.g, \"db\"):\n return flask.g.db\n\n flask.g.db = pymysql.connect(\n host=config[\"db_host\"],\n port=config[\"db_port\"],\n user=config[\"db_user\"],\n passwd=config[\"db_password\"],\n db=\"isubata\",\n charset=\"utf8mb4\",\n cursorclass=pymysql.cursors.DictCursor,\n autocommit=True,\n )\n cur = flask.g.db.cursor()\n cur.execute(\n \"SET SESSION sql_mode='TRADITIONAL,NO_AUTO_VALUE_ON_ZERO,ONLY_FULL_GROUP_BY'\"\n )\n return flask.g.db\n\n\n@app.teardown_appcontext\ndef teardown(error):\n if hasattr(flask.g, \"db\"):\n flask.g.db.close()\n\n\n@app.route(\"/initialize\")\ndef get_initialize():\n cur = dbh().cursor()\n cur.execute(\"delete from user where id > 1000\")\n cur.execute(\"delete from channel where id > 10\")\n cur.execute(\"delete from message where id > 10000\")\n cur.execute(\"delete from channel_message_num\")\n cur.execute(\"delete from channel_message_read_num\")\n cur.execute(\n \"\"\"\n insert into channel_message_num\n select channel_id, count(*) from message m group by m.channel_id\n \"\"\"\n )\n cur.close()\n return (\"\", 204)\n\n\ndef db_get_user(cur, user_id):\n cur.execute(\"SELECT * FROM user WHERE id = %s\", (user_id,))\n return cur.fetchone()\n\n\nclass DBUtil:\n @staticmethod\n def is_exist_user(cur: Cursor, user_id):\n cur.execute(\"select count(1) as num from user where id = %s\", (user_id,))\n res = cur.fetchone()\n return res[\"num\"] > 0\n\n @staticmethod\n def add_message(cur: Cursor, channel_id, user_id, content):\n cur.execute(\n \"insert into message (channel_id, user_id, content, created_at) values (%s, %s, %s, now())\",\n (channel_id, user_id, content),\n )\n DBUtil.update_channel_message_num(cur, channel_id)\n\n @staticmethod\n def add_channel(cur: Cursor, name, description):\n cur.execute(\n \"insert into channel (name, description, updated_at, created_at) values (%s, %s, now(), now())\",\n (name, description),\n )\n channel_id = cur.lastrowid\n sql = \"\"\"\n insert channel_message_num(channel_id, num)\n values (%s, 0)\n \"\"\"\n cur.execute(sql, (channel_id,))\n return channel_id\n\n @staticmethod\n def update_channel_message_num(cur: Cursor, channel_id: str):\n sql = \"\"\"\n update channel_message_num\n set num = num + 1\n where channel_id = %s\n \"\"\"\n cur.execute(sql, (channel_id,))\n\n @staticmethod\n def get_channel_message_num(cur: Cursor):\n sql = \"select channel_id, num from channel_message_num\"\n cur.execute(sql)\n rows = cur.fetchall()\n return rows\n\n @staticmethod\n def upsert_channel_message_read_num(\n cur: Cursor, user_id: str, channel_id: str, message_id: str\n ):\n sql = \"\"\"\n insert into channel_message_read_num\n (user_id, channel_id, num)\n values (%s, %s, (\n select count(1) from message m\n where m.channel_id = %s and m.id <= %s\n ))\n on duplicate key update\n num = (\n select count(1) from message m\n where m.channel_id = %s and m.id <= %s\n )\n \"\"\"\n cur.execute(\n sql, (user_id, channel_id, channel_id, message_id, channel_id, message_id)\n )\n\n @staticmethod\n def get_channel_message_read_num(cur: Cursor, user_id: str):\n sql = \"select channel_id, num from channel_message_read_num where user_id = %s\"\n cur.execute(sql, (user_id,))\n rows = cur.fetchall()\n return rows\n\n\ndef login_required(func):\n @functools.wraps(func)\n def wrapper(*args, **kwargs):\n if not \"user_id\" in flask.session:\n return flask.redirect(\"/login\", 303)\n flask.request.user_id = user_id = flask.session[\"user_id\"]\n user = db_get_user(dbh().cursor(), user_id)\n if not user:\n flask.session.pop(\"user_id\", None)\n return flask.redirect(\"/login\", 303)\n flask.request.user = user\n return func(*args, **kwargs)\n\n return wrapper\n\n\ndef random_string(n):\n return \"\".join(\n [random.choice(string.ascii_letters + string.digits) for i in range(n)]\n )\n\n\ndef register(cur, user, password):\n salt = random_string(20)\n pass_digest = hashlib.sha1((salt + password).encode(\"utf-8\")).hexdigest()\n try:\n cur.execute(\n \"INSERT INTO user (name, salt, password, display_name, avatar_icon, created_at)\"\n \" VALUES (%s, %s, %s, %s, %s, NOW())\",\n (user, salt, pass_digest, user, \"default.png\"),\n )\n cur.execute(\"SELECT LAST_INSERT_ID() AS last_insert_id\")\n return cur.fetchone()[\"last_insert_id\"]\n except pymysql.IntegrityError:\n flask.abort(409)\n\n\n@app.route(\"/\")\ndef get_index():\n if \"user_id\" in flask.session:\n return flask.redirect(\"/channel/1\", 303)\n return flask.render_template(\"index.html\")\n\n\ndef get_channel_list_info(focus_channel_id=None):\n cur = dbh().cursor()\n cur.execute(\"SELECT * FROM channel ORDER BY id\")\n channels = cur.fetchall()\n description = \"\"\n\n for c in channels:\n if c[\"id\"] == focus_channel_id:\n description = c[\"description\"]\n break\n\n return channels, description\n\n\n@app.route(\"/channel/\")\n@login_required\ndef get_channel(channel_id):\n channels, description = get_channel_list_info(channel_id)\n return flask.render_template(\n \"channel.html\",\n channels=channels,\n channel_id=channel_id,\n description=description,\n )\n\n\n@app.route(\"/register\")\ndef get_register():\n return flask.render_template(\"register.html\")\n\n\n@app.route(\"/register\", methods=[\"POST\"])\ndef post_register():\n name = flask.request.form[\"name\"]\n pw = flask.request.form[\"password\"]\n if not name or not pw:\n flask.abort(400)\n user_id = register(dbh().cursor(), name, pw)\n flask.session[\"user_id\"] = user_id\n return flask.redirect(\"/\", 303)\n\n\n@app.route(\"/login\")\ndef get_login():\n return flask.render_template(\"login.html\")\n\n\n@app.route(\"/login\", methods=[\"POST\"])\ndef post_login():\n name = flask.request.form[\"name\"]\n cur = dbh().cursor()\n cur.execute(\"SELECT * FROM user WHERE name = %s\", (name,))\n row = cur.fetchone()\n if (\n not row\n or row[\"password\"]\n != hashlib.sha1(\n (row[\"salt\"] + flask.request.form[\"password\"]).encode(\"utf-8\")\n ).hexdigest()\n ):\n flask.abort(403)\n flask.session[\"user_id\"] = row[\"id\"]\n return flask.redirect(\"/\", 303)\n\n\n@app.route(\"/logout\")\ndef get_logout():\n flask.session.pop(\"user_id\", None)\n return flask.redirect(\"/\", 303)\n\n\n@app.route(\"/message\", methods=[\"POST\"])\ndef post_message():\n user_id = flask.session[\"user_id\"]\n cur = dbh().cursor()\n is_exist_user = DBUtil.is_exist_user(cur, user_id)\n message = flask.request.form[\"message\"]\n channel_id = int(flask.request.form[\"channel_id\"])\n if not is_exist_user or not message or not channel_id:\n flask.abort(403)\n DBUtil.add_message(cur, channel_id, user_id, message)\n return (\"\", 204)\n\n\n@app.route(\"/message\")\ndef get_message():\n user_id = flask.session.get(\"user_id\")\n if not user_id:\n flask.abort(403)\n\n channel_id = int(flask.request.args.get(\"channel_id\"))\n last_message_id = int(flask.request.args.get(\"last_message_id\"))\n cur = dbh().cursor()\n cur.execute(\n \"\"\"\n select m.id, m.created_at, m.content, u.name, u.display_name, u.avatar_icon from message as m\n left join user as u on u.id = m.user_id\n where m.id > %s and channel_id = %s order by id desc limit 100\n \"\"\",\n (last_message_id, channel_id),\n )\n rows = cur.fetchall()\n response = []\n for row in rows:\n r = {}\n r[\"id\"] = row[\"id\"]\n r[\"user\"] = {\n \"name\": row[\"name\"],\n \"display_name\": row[\"display_name\"],\n \"avatar_icon\": row[\"avatar_icon\"],\n }\n r[\"date\"] = row[\"created_at\"].strftime(\"%Y/%m/%d %H:%M:%S\")\n r[\"content\"] = row[\"content\"]\n response.append(r)\n response.reverse()\n\n max_message_id = max(r[\"id\"] for r in rows) if rows else 0\n DBUtil.upsert_channel_message_read_num(cur, user_id, channel_id, max_message_id)\n\n return flask.jsonify(response)\n\n\n@app.route(\"/fetch\")\ndef fetch_unread():\n user_id = flask.session.get(\"user_id\")\n if not user_id:\n flask.abort(403)\n\n cur = dbh().cursor()\n\n res = []\n channel_message_nums = DBUtil.get_channel_message_num(cur)\n channel_message_read_nums = DBUtil.get_channel_message_read_num(cur, user_id)\n channel_message_read_nums = {\n v[\"channel_id\"]: v[\"num\"] for v in channel_message_read_nums\n }\n for v in channel_message_nums:\n unread = v[\"num\"] - channel_message_read_nums.get(v[\"channel_id\"], 0)\n r = {\"channel_id\": v[\"channel_id\"], \"unread\": unread}\n res.append(r)\n return flask.jsonify(res)\n\n\n@app.route(\"/history/\")\n@login_required\ndef get_history(channel_id):\n page = flask.request.args.get(\"page\")\n if not page:\n page = \"1\"\n if not page.isnumeric():\n flask.abort(400)\n page = int(page)\n\n N = 20\n cur = dbh().cursor()\n cur.execute(\n \"select num from channel_message_num where channel_id = %s\", (channel_id,)\n )\n cnt = int(cur.fetchone()[\"num\"])\n max_page = math.ceil(cnt / N)\n if not max_page:\n max_page = 1\n\n if not 1 <= page <= max_page:\n flask.abort(400)\n\n cur.execute(\n \"\"\"\n SELECT m.id, m.created_at, m.content, u.name, u.display_name, u.avatar_icon FROM message as m\n LEFT JOIN user as u on u.id = m.user_id\n WHERE m.channel_id = %s ORDER BY m.id DESC LIMIT %s OFFSET %s\n \"\"\",\n (channel_id, N, (page - 1) * N),\n )\n rows = cur.fetchall()\n messages = []\n for row in rows:\n r = {}\n r[\"id\"] = row[\"id\"]\n r[\"user\"] = {\n \"name\": row[\"name\"],\n \"display_name\": row[\"display_name\"],\n \"avatar_icon\": row[\"avatar_icon\"],\n }\n r[\"date\"] = row[\"created_at\"].strftime(\"%Y/%m/%d %H:%M:%S\")\n r[\"content\"] = row[\"content\"]\n messages.append(r)\n messages.reverse()\n\n channels, description = get_channel_list_info(channel_id)\n return flask.render_template(\n \"history.html\",\n channels=channels,\n channel_id=channel_id,\n messages=messages,\n max_page=max_page,\n page=page,\n )\n\n\n@app.route(\"/profile/\")\n@login_required\ndef get_profile(user_name):\n channels, _ = get_channel_list_info()\n\n cur = dbh().cursor()\n cur.execute(\n \"select id, name, display_name, avatar_icon from user where name = %s\",\n (user_name,),\n )\n user = cur.fetchone()\n\n if not user:\n flask.abort(404)\n\n self_profile = flask.request.user[\"id\"] == user[\"id\"]\n return flask.render_template(\n \"profile.html\", channels=channels, user=user, self_profile=self_profile\n )\n\n\n@app.route(\"/add_channel\")\n@login_required\ndef get_add_channel():\n channels, _ = get_channel_list_info()\n return flask.render_template(\"add_channel.html\", channels=channels)\n\n\n@app.route(\"/add_channel\", methods=[\"POST\"])\n@login_required\ndef post_add_channel():\n name = flask.request.form[\"name\"]\n description = flask.request.form[\"description\"]\n if not name or not description:\n flask.abort(400)\n cur = dbh().cursor()\n channel_id = DBUtil.add_channel(cur, name, description)\n return flask.redirect(\"/channel/\" + str(channel_id), 303)\n\n\n@app.route(\"/profile\", methods=[\"POST\"])\n@login_required\ndef post_profile():\n user_id = flask.session.get(\"user_id\")\n if not user_id:\n flask.abort(403)\n\n cur = dbh().cursor()\n user = db_get_user(cur, user_id)\n if not user:\n flask.abort(403)\n\n display_name = flask.request.form.get(\"display_name\")\n avatar_name = None\n\n if \"avatar_icon\" in flask.request.files:\n file = flask.request.files[\"avatar_icon\"]\n if file.filename:\n ext = os.path.splitext(file.filename)[1] if \".\" in file.filename else \"\"\n if ext not in (\".jpg\", \".jpeg\", \".png\", \".gif\"):\n flask.abort(400)\n avatar_name = str(uuid4()) + ext\n with open(os.path.join(icons_folder, avatar_name), \"wb\") as f:\n file.save(f)\n if avatar_max_size < f.tell():\n flask.abort(400)\n\n if avatar_name:\n cur.execute(\n \"UPDATE user SET avatar_icon = %s WHERE id = %s\", (avatar_name, user_id)\n )\n\n if display_name:\n cur.execute(\n \"UPDATE user SET display_name = %s WHERE id = %s\", (display_name, user_id)\n )\n\n return flask.redirect(\"/\", 303)\n\n\nif __name__ == \"__main__\":\n app.run(port=8080, debug=True, threaded=True)\n","repo_name":"sidearrow/playground","sub_path":"isucon/isucon7-qualify/app/main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":13847,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"15"} +{"seq_id":"29953346568","text":"import torch\nimport torch.nn as nn\nimport torch.nn.functional as F\nimport torch.utils.model_zoo as model_zoo\nfrom torch.autograd import Variable\n\npretrained_settings = {\n 'nasnetalarge': {\n 'imagenet': {\n 'url': 'http://data.lip6.fr/cadene/pretrainedmodels/nasnetalarge-a1897284.pth',\n 'input_space': 'RGB',\n 'input_size': [3, 331, 331], # resize 354\n 'input_range': [0, 1],\n 'mean': [0.5, 0.5, 0.5],\n 'std': [0.5, 0.5, 0.5],\n 'num_classes': 1000\n },\n 'imagenet+background': {\n 'url': 'http://data.lip6.fr/cadene/pretrainedmodels/nasnetalarge-a1897284.pth',\n 'input_space': 'RGB',\n 'input_size': [3, 331, 331], # resize 354\n 'input_range': [0, 1],\n 'mean': [0.5, 0.5, 0.5],\n 'std': [0.5, 0.5, 0.5],\n 'num_classes': 1001\n }\n }\n}\n\nclass MaxPool(nn.Module):\n\n def __init__(self, pad=False):\n super(MaxPool, self).__init__()\n self.pad = pad\n self.pad = nn.ZeroPad2d((1, 0, 1, 0)) if pad else None\n self.pool = nn.MaxPool2d(3, stride=2, padding=1)\n\n def forward(self, x):\n if self.pad:\n x = self.pad(x)\n x = self.pool(x)\n if self.pad:\n x = x[:, :, 1:, 1:]\n return x\n\n\nclass AvgPool(nn.Module):\n\n def __init__(self, pad=False, stride=2, padding=1):\n super(AvgPool, self).__init__()\n self.pad = pad\n self.pad = nn.ZeroPad2d((1, 0, 1, 0)) if pad else None\n self.pool = nn.AvgPool2d(3, stride=stride, padding=padding)\n\n def forward(self, x):\n if self.pad:\n x = self.pad(x)\n x = self.pool(x)\n if self.pad:\n x = x[:, :, 1:, 1:]\n return x\n\n\nclass SeparableConv2d(nn.Module):\n\n def __init__(self, in_channels, out_channels, dw_kernel, dw_stride, dw_padding, bias=False):\n super(SeparableConv2d, self).__init__()\n self.depthwise_conv2d = nn.Conv2d(in_channels, in_channels, dw_kernel,\n stride=dw_stride,\n padding=dw_padding,\n bias=bias,\n groups=in_channels)\n self.pointwise_conv2d = nn.Conv2d(in_channels, out_channels, 1, stride=1, bias=bias)\n\n def forward(self, x):\n x = self.depthwise_conv2d(x)\n x = self.pointwise_conv2d(x)\n return x\n\n\nclass BranchSeparables(nn.Module):\n\n def __init__(self, in_channels, out_channels, kernel_size, stride, padding,\n bias=False, reduction=False, z_padding=1, stem=False):\n super(BranchSeparables, self).__init__()\n self.relu = nn.ReLU()\n self.separable_1 = SeparableConv2d(in_channels,\n out_channels if stem else in_channels,\n kernel_size, stride, padding, bias=bias)\n self.bn_sep_1 = nn.BatchNorm2d(\n out_channels if stem else in_channels,\n eps=0.001, momentum=0.1, affine=True)\n self.relu1 = nn.ReLU()\n self.separable_2 = SeparableConv2d(\n out_channels if stem else in_channels,\n out_channels, kernel_size, 1, padding, bias=bias)\n self.bn_sep_2 = nn.BatchNorm2d(out_channels, eps=0.001, momentum=0.1,\n affine=True)\n if reduction:\n self.padding = nn.ZeroPad2d((z_padding, 0, z_padding, 0))\n\n def forward(self, x):\n x = self.relu(x)\n x = self.padding(x) if hasattr(self, 'padding') else x\n x = self.separable_1(x)\n x = x[:, :, 1:, 1:].contiguous() if hasattr(self, 'padding') else x\n x = self.bn_sep_1(x)\n x = self.relu1(x)\n x = self.separable_2(x)\n x = self.bn_sep_2(x)\n return x\n\n\nclass AuxHead(nn.Module):\n def __init__(self, in_planes, num_classes=10):\n super(AuxHead, self).__init__()\n # aux output to improve convergence (classification shortcut)\n self.pool = nn.AvgPool2d(5, stride=3)\n # local shape inference\n self.pointwise = nn.Conv2d(in_planes, 128, 1)\n self.pointwise_bn = nn.BatchNorm2d(128)\n # NASNet's way of implementing a fc layer is wild\n self.conv2d_fc = nn.Conv2d(128, 728, 1)\n self.conv2d_fc_bn = nn.BatchNorm2d(728)\n self.linear = nn.Linear(728, num_classes)\n\n def forward(self, x):\n out = self.pool(x)\n out = self.pointwise(out)\n out = self.pointwise_bn(out)\n out = F.relu(out)\n out = self.conv2d_fc(out)\n out = self.conv2d_fc_bn(out)\n out = F.relu(out)\n n, c, w, h = out.size() \n out = out.view(n, c, w*h).mean(2) # this is not true in tf\n return self.linear(out)\n\n\nclass DropPath(nn.Module):\n \"\"\"\n Zeros input x with probability 1-p independently over examples.\n p is the probability of keeping the input, the opposite of the normal\n operation of the Dropout module.\n \"\"\"\n\n def __init__(self, p=0.5, inplace=False):\n super(DropPath, self).__init__()\n if p < 0 or p > 1:\n raise ValueError(\"dropout probability has to be between 0 and 1, \"\n \"but got {}\".format(p))\n self.keep_prob, self.p = p, 1.-p\n self.inplace = inplace\n\n def forward(self, input):\n if not self.training or self.keep_prob > 0.99:\n return input\n batch_size = input.size(0)\n mask = torch.ones(batch_size, 1, 1, 1)\n if input.is_cuda:\n mask = mask.cuda()\n mask = F.dropout(mask, self.p, self.training, self.inplace)\n return mask*input\n\n def __repr__(self):\n inplace_str = ', inplace' if self.inplace else ''\n return self.__class__.__name__ + '(' \\\n + 'p=' + str(self.p) \\\n + inplace_str + ')'\n\n\nclass CellStem0(nn.Module):\n\n def __init__(self, num_conv_filters, stem_multiplier, celltype='A'):\n super(CellStem0, self).__init__()\n nf1, nf2 = 32*stem_multiplier, num_conv_filters//4\n self.conv_1x1 = nn.Sequential()\n self.conv_1x1.add_module('relu', nn.ReLU())\n self.conv_1x1.add_module('conv', nn.Conv2d(nf1, nf2, 1, stride=1, bias=False))\n self.conv_1x1.add_module('bn', nn.BatchNorm2d(nf2, eps=0.001, momentum=0.1, affine=True))\n\n self.comb_iter_0_left = BranchSeparables(nf2, nf2, 5, 2, 2)\n self.comb_iter_0_right = BranchSeparables(nf1, nf2, 7, 2, 3, bias=False, stem=True)\n\n self.comb_iter_1_left = nn.MaxPool2d(3, stride=2, padding=1)\n self.comb_iter_1_right = BranchSeparables(nf1, nf2, 7, 2, 3, bias=False, stem=True)\n\n self.comb_iter_2_left = nn.AvgPool2d(3, stride=2, padding=1, count_include_pad=False)\n self.comb_iter_2_right = BranchSeparables(nf1, nf2, 5, 2, 2, bias=False, stem=True)\n\n self.comb_iter_3_right = nn.AvgPool2d(3, stride=1, padding=1, count_include_pad=False)\n\n self.comb_iter_4_left = BranchSeparables(nf2, nf2, 3, 1, 1, bias=False)\n self.comb_iter_4_right = nn.MaxPool2d(3, stride=2, padding=1)\n\n def forward(self, x):\n x1 = self.conv_1x1(x)\n\n x_comb_iter_0_left = self.comb_iter_0_left(x1)\n x_comb_iter_0_right = self.comb_iter_0_right(x)\n x_comb_iter_0 = x_comb_iter_0_left + x_comb_iter_0_right\n\n x_comb_iter_1_left = self.comb_iter_1_left(x1)\n x_comb_iter_1_right = self.comb_iter_1_right(x)\n x_comb_iter_1 = x_comb_iter_1_left + x_comb_iter_1_right\n\n x_comb_iter_2_left = self.comb_iter_2_left(x1)\n x_comb_iter_2_right = self.comb_iter_2_right(x)\n x_comb_iter_2 = x_comb_iter_2_left + x_comb_iter_2_right\n\n x_comb_iter_3_right = self.comb_iter_3_right(x_comb_iter_0)\n x_comb_iter_3 = x_comb_iter_3_right + x_comb_iter_1\n\n x_comb_iter_4_left = self.comb_iter_4_left(x_comb_iter_0)\n x_comb_iter_4_right = self.comb_iter_4_right(x1)\n x_comb_iter_4 = x_comb_iter_4_left + x_comb_iter_4_right\n\n x_out = torch.cat([x_comb_iter_1, x_comb_iter_2, x_comb_iter_3, x_comb_iter_4], 1)\n return x_out\n\n\nclass CellStem1(nn.Module):\n\n def __init__(self, num_conv_filters, stem_multiplier, celltype='A'):\n super(CellStem1, self).__init__()\n self.conv_1x1 = nn.Sequential()\n self.conv_1x1.add_module('relu', nn.ReLU())\n self.conv_1x1.add_module('conv', nn.Conv2d(num_conv_filters, num_conv_filters//2, 1, stride=1, bias=False))\n self.conv_1x1.add_module('bn', nn.BatchNorm2d(num_conv_filters//2, eps=0.001, momentum=0.1, affine=True))\n\n self.relu = nn.ReLU()\n self.path_1 = nn.Sequential()\n self.path_1.add_module('avgpool', nn.AvgPool2d(1, stride=2, count_include_pad=False))\n self.path_1.add_module('conv', nn.Conv2d(32*stem_multiplier, num_conv_filters//4, 1, stride=1, bias=False))\n self.path_2 = nn.ModuleList()\n self.path_2.add_module('pad', nn.ZeroPad2d((0, 1, 0, 1)))\n self.path_2.add_module('avgpool', nn.AvgPool2d(1, stride=2, count_include_pad=False))\n self.path_2.add_module('conv', nn.Conv2d(32*stem_multiplier, num_conv_filters//4, 1, stride=1, bias=False))\n\n nf = num_conv_filters//2\n self.final_path_bn = nn.BatchNorm2d(nf, eps=0.001, momentum=0.1, affine=True)\n\n self.comb_iter_0_left = BranchSeparables(nf, nf, 5, 2, 2, bias=False)\n self.comb_iter_0_right = BranchSeparables(nf, nf, 7, 2, 3, bias=False)\n\n self.comb_iter_1_left = nn.MaxPool2d(3, stride=2, padding=1)\n self.comb_iter_1_right = BranchSeparables(nf, nf, 7, 2, 3, bias=False)\n\n self.comb_iter_2_left = nn.AvgPool2d(3, stride=2, padding=1, count_include_pad=False)\n self.comb_iter_2_right = BranchSeparables(nf, nf, 5, 2, 2, bias=False)\n\n self.comb_iter_3_right = nn.AvgPool2d(3, stride=1, padding=1, count_include_pad=False)\n\n self.comb_iter_4_left = BranchSeparables(nf, nf, 3, 1, 1, bias=False)\n self.comb_iter_4_right = nn.MaxPool2d(3, stride=2, padding=1)\n\n def forward(self, x_conv0, x_stem_0):\n x_left = self.conv_1x1(x_stem_0)\n\n x_relu = self.relu(x_conv0)\n # path 1\n x_path1 = self.path_1(x_relu)\n # path 2\n x_path2 = self.path_2.pad(x_relu)\n x_path2 = x_path2[:, :, 1:, 1:]\n x_path2 = self.path_2.avgpool(x_path2)\n x_path2 = self.path_2.conv(x_path2)\n # final path\n x_right = self.final_path_bn(torch.cat([x_path1, x_path2], 1))\n\n x_comb_iter_0_left = self.comb_iter_0_left(x_left)\n x_comb_iter_0_right = self.comb_iter_0_right(x_right)\n x_comb_iter_0 = x_comb_iter_0_left + x_comb_iter_0_right\n\n x_comb_iter_1_left = self.comb_iter_1_left(x_left)\n x_comb_iter_1_right = self.comb_iter_1_right(x_right)\n x_comb_iter_1 = x_comb_iter_1_left + x_comb_iter_1_right\n\n x_comb_iter_2_left = self.comb_iter_2_left(x_left)\n x_comb_iter_2_right = self.comb_iter_2_right(x_right)\n x_comb_iter_2 = x_comb_iter_2_left + x_comb_iter_2_right\n\n x_comb_iter_3_right = self.comb_iter_3_right(x_comb_iter_0)\n x_comb_iter_3 = x_comb_iter_3_right + x_comb_iter_1\n\n x_comb_iter_4_left = self.comb_iter_4_left(x_comb_iter_0)\n x_comb_iter_4_right = self.comb_iter_4_right(x_left)\n x_comb_iter_4 = x_comb_iter_4_left + x_comb_iter_4_right\n\n x_out = torch.cat([x_comb_iter_1, x_comb_iter_2, x_comb_iter_3, x_comb_iter_4], 1)\n return x_out\n\ndef guess_output_channels(module, in_channels):\n if isinstance(module, BranchSeparables):\n n_out = module.bn_sep_2.num_features\n elif isinstance(module, MaxPool) or isinstance(module, AvgPool) or \\\n isinstance(module, nn.MaxPool2d) or isinstance(module, nn.AvgPool2d):\n n_out = in_channels\n else:\n raise ValueError(\"Don't know how many output channels this module has\"\n \": %s\"%module)\n return n_out\n\nclass BaseCell(nn.Module):\n def __init__(self, in_channels_left, out_channels_left, in_channels_right,\n out_channels_right, factorized_reduction, keep_prob):\n super(BaseCell, self).__init__()\n self.in_channels_left, self.out_channels_left = in_channels_left, out_channels_left\n self.in_channels_right, self.out_channels_right = in_channels_right, out_channels_right\n self.factorized_reduction = factorized_reduction\n\n self.conv_1x1 = nn.Sequential()\n self.conv_1x1.add_module('relu', nn.ReLU())\n self.conv_1x1.add_module('conv', nn.Conv2d(in_channels_right, out_channels_right, 1, stride=1, bias=False))\n self.conv_1x1.add_module('bn', nn.BatchNorm2d(out_channels_right, eps=0.001, momentum=0.1, affine=True))\n\n if self.factorized_reduction:\n self.relu = nn.ReLU()\n self.path_1 = nn.Sequential()\n self.path_1.add_module('avgpool', nn.AvgPool2d(1, stride=2, count_include_pad=False))\n self.path_1.add_module('conv', nn.Conv2d(in_channels_left, out_channels_left, 1, stride=1, bias=False))\n self.path_2 = nn.ModuleList()\n self.path_2.add_module('pad', nn.ZeroPad2d((0, 1, 0, 1)))\n self.path_2.add_module('avgpool', nn.AvgPool2d(1, stride=2, count_include_pad=False))\n self.path_2.add_module('conv', nn.Conv2d(in_channels_left, out_channels_left, 1, stride=1, bias=False))\n self.final_path_bn = nn.BatchNorm2d(out_channels_left * 2, eps=0.001, momentum=0.1, affine=True)\n else:\n self.conv_prev_1x1 = nn.Sequential()\n self.conv_prev_1x1.add_module('relu', nn.ReLU())\n self.conv_prev_1x1.add_module('conv', nn.Conv2d(in_channels_left, out_channels_left, 1, stride=1, bias=False))\n self.conv_prev_1x1.add_module('bn', nn.BatchNorm2d(out_channels_left, eps=0.001, momentum=0.1, affine=True))\n\n self.drop_path = DropPath(p=keep_prob)\n\n def output_channels(self):\n n_out = {}\n for i in range(self._count_branches()):\n try:\n left = getattr(self, 'comb_iter_%i_left'%i)\n if self.factorized_reduction:\n ch = self.out_channels_left*2\n else:\n ch = self.out_channels_left\n n_out['comb_iter_%i'%i] = \\\n guess_output_channels(left, ch)\n except AttributeError:\n pass\n try:\n right = getattr(self, 'comb_iter_%i_right'%i)\n if 'comb_iter_%i' not in n_out:\n n_out['comb_iter_%i'%i] = \\\n guess_output_channels(right, self.out_channels_right)\n except AttributeError:\n pass\n n_out['left'] = self.out_channels_left*2 if self.factorized_reduction \\\n else self.out_channels_left\n n_out['right'] = self.out_channels_right\n return sum([n_out[k] for k in self.to_cat])\n\n def _count_branches(self):\n branch_idx = 0\n while hasattr(self, 'comb_iter_%i_left'%branch_idx) or\\\n hasattr(self, 'comb_iter_%i_right'%branch_idx):\n branch_idx += 1\n return branch_idx\n\n def register_branch(self, left, right, left_input_key, right_input_key):\n # how many do we have already?\n n_branches = self._count_branches()\n self.__dict__['comb_iter_%i_left_input'%n_branches] = left_input_key\n self.__dict__['comb_iter_%i_right_input'%n_branches] = right_input_key\n if left is not None:\n setattr(self, 'comb_iter_%i_left'%n_branches, left)\n if right is not None:\n setattr(self, 'comb_iter_%i_right'%n_branches, right)\n\n def forward(self, x, x_prev):\n if self.factorized_reduction:\n x_relu = self.relu(x_prev)\n # path 1\n x_path1 = self.path_1(x_relu)\n\n # path 2\n x_path2 = self.path_2.pad(x_relu)\n x_path2 = x_path2[:, :, 1:, 1:]\n x_path2 = self.path_2.avgpool(x_path2)\n x_path2 = self.path_2.conv(x_path2)\n # final path\n x_left = self.final_path_bn(torch.cat([x_path1, x_path2], 1))\n else:\n x_left = self.conv_prev_1x1(x_prev)\n\n x_right = self.conv_1x1(x)\n # branch_inputs is a bad name, considering these are combined to create the output\n branch_inputs = {'left':x_left, 'right':x_right}\n\n for i in range(self._count_branches()):\n left_input = branch_inputs[getattr(self, 'comb_iter_%i_left_input'%i)]\n right_input = branch_inputs[getattr(self, 'comb_iter_%i_right_input'%i)]\n if hasattr(self, 'comb_iter_%i_left'%i):\n left_out = getattr(self, 'comb_iter_%i_left'%i)(left_input)\n else:\n left_out = left_input\n if hasattr(self, 'comb_iter_%i_right'%i):\n right_out = getattr(self, 'comb_iter_%i_right'%i)(right_input)\n else:\n right_out = right_input\n out = right_out + left_out\n out = self.drop_path(out) # randomly drop branches during training\n branch_inputs['comb_iter_%i'%i] = out\n\n return torch.cat([branch_inputs[k] for k in self.to_cat], 1)\n\n\nclass NormalCell(BaseCell):\n\n def __init__(self, in_channels_left, out_channels_left, in_channels_right,\n out_channels_right, keep_prob, factorized_reduction=False):\n super(NormalCell, self).__init__(in_channels_left, out_channels_left,\n in_channels_right, out_channels_right, factorized_reduction,\n keep_prob)\n\n self.register_branch(BranchSeparables(out_channels_right, out_channels_right, 5, 1, 2, bias=False),\n BranchSeparables(out_channels_right, out_channels_right, 3, 1, 1, bias=False),\n 'right', 'left')\n\n self.register_branch(BranchSeparables(out_channels_right, out_channels_right, 5, 1, 2, bias=False),\n BranchSeparables(out_channels_right, out_channels_right, 3, 1, 1, bias=False),\n 'left', 'left')\n\n self.register_branch(nn.AvgPool2d(3, stride=1, padding=1, count_include_pad=False), None,\n 'right', 'left')\n\n self.register_branch(nn.AvgPool2d(3, stride=1, padding=1, count_include_pad=False),\n nn.AvgPool2d(3, stride=1, padding=1, count_include_pad=False),\n 'left', 'left')\n\n self.register_branch(BranchSeparables(out_channels_right, out_channels_right, 3, 1, 1, bias=False), None,\n 'right', 'right')\n \n self.to_cat = ['left'] + ['comb_iter_%i'%i for i in range(5)]\n\n\nclass ReductionCell(BaseCell):\n\n def __init__(self, in_channels_left, out_channels_left, in_channels_right, out_channels_right, keep_prob, pad=False):\n super(ReductionCell, self).__init__(in_channels_left, out_channels_left, in_channels_right, out_channels_right, False, keep_prob) \n \n self.register_branch(BranchSeparables(out_channels_right, out_channels_right, 5, 2, 2, bias=False, reduction=pad),\n BranchSeparables(out_channels_right, out_channels_right, 7, 2, 3, bias=False, reduction=pad),\n 'right', 'left')\n \n self.register_branch(MaxPool(pad=pad),\n BranchSeparables(out_channels_right, out_channels_right, 7, 2, 3, bias=False, reduction=pad),\n 'right', 'left')\n\n self.register_branch(AvgPool(pad=pad),\n BranchSeparables(out_channels_right, out_channels_right, 5, 2, 2, bias=False, reduction=pad),\n 'right', 'left')\n\n self.register_branch(None, nn.AvgPool2d(3, stride=1, padding=1, count_include_pad=False),\n 'comb_iter_1', 'comb_iter_0')\n\n self.register_branch(BranchSeparables(out_channels_right, out_channels_right, 3, 1, 1, bias=False, reduction=pad),\n MaxPool(pad=pad), 'comb_iter_0', 'right')\n\n self.to_cat = ['comb_iter_%i'%i for i in range(1,5)]\n\n\nclass NASNet(nn.Module):\n\n def __init__(self, num_conv_filters, filter_scaling_rate, num_classes,\n num_cells, stem_multiplier, stem, drop_path_keep_prob):\n super(NASNet, self).__init__()\n self.num_classes = num_classes\n self.num_cells = num_cells\n self.stem = stem\n\n stem_filters = 32*stem_multiplier\n if self.stem == 'imagenet':\n self.conv0 = nn.Sequential()\n self.conv0.add_module('conv', nn.Conv2d(in_channels=3,\n out_channels=stem_filters, kernel_size=3, padding=0, stride=2,\n bias=False))\n self.conv0.add_module('bn', nn.BatchNorm2d(stem_filters, eps=0.001,\n momentum=0.1, affine=True))\n\n self.cell_stem_0 = CellStem0(num_conv_filters, stem_multiplier)\n self.cell_stem_1 = CellStem1(num_conv_filters, stem_multiplier)\n elif self.stem == 'cifar':\n self.conv0 = nn.Sequential()\n self.conv0.add_module('conv', nn.Conv2d(in_channels=3,\n out_channels=stem_filters, kernel_size=3, padding=1, stride=2,\n bias=False))\n self.conv0.add_module('bn', nn.BatchNorm2d(stem_filters, eps=0.001,\n momentum=0.1, affine=True)) \n else:\n raise ValueError(\"Don't know what type of stem %s is.\"%stem)\n\n self.block1 = []\n nf, fs = num_conv_filters, filter_scaling_rate\n cell_idx = 0\n self.cell_0 = NormalCell(\n in_channels_left=nf if self.stem == 'imagenet' else 3,\n out_channels_left=nf//fs,\n in_channels_right=nf*fs if self.stem == 'imagenet' else nf*stem_multiplier,\n out_channels_right=nf,\n keep_prob=drop_path_keep_prob,\n factorized_reduction=True)\n self.block1.append(self.cell_0)\n in_ch, out_ch = nf*(fs*3), nf\n cells_per_block = num_cells//3\n for i in range(cells_per_block-1):\n cell_idx += 1\n if i==0 and self.stem=='imagenet':\n ch_left = nf*fs if i == 0 else in_ch\n elif i==0 and self.stem=='cifar':\n ch_left = nf*stem_multiplier\n else:\n ch_left = in_ch\n next_cell = NormalCell(in_channels_left=ch_left,\n out_channels_left=nf,\n in_channels_right=in_ch,\n out_channels_right=out_ch,\n keep_prob=drop_path_keep_prob)\n # hack to not break sanity check\n setattr(self, \"cell_%i\"%cell_idx, next_cell)\n self.block1.append(next_cell)\n\n out_ch = nf*fs\n self.reduction_cell_0 = ReductionCell(in_channels_left=in_ch, out_channels_left=out_ch,\n in_channels_right=in_ch, out_channels_right=out_ch,\n keep_prob=drop_path_keep_prob,\n pad=True)\n\n cell_idx += 1\n next_cell = NormalCell(in_channels_left=in_ch, out_channels_left=out_ch//fs,\n in_channels_right=in_ch+nf*fs, out_channels_right=out_ch,\n keep_prob=drop_path_keep_prob,\n factorized_reduction=True)\n setattr(self, \"cell_%i\"%cell_idx, next_cell)\n in_ch = nf*(fs*6)\n for i in range(cells_per_block-1):\n cell_idx += 1\n next_cell = NormalCell(in_channels_left=nf*fs*4 if i == 0 else in_ch, out_channels_left=out_ch,\n in_channels_right=in_ch, out_channels_right=out_ch,\n keep_prob=drop_path_keep_prob)\n setattr(self, \"cell_%i\"%cell_idx, next_cell)\n self.block1.append(next_cell)\n\n\n in_planes = next_cell.output_channels()\n self.aux_head = AuxHead(in_planes, num_classes=num_classes)\n\n out_ch = nf*fs*2\n self.reduction_cell_1 = ReductionCell(in_channels_left=in_ch, out_channels_left=out_ch,\n in_channels_right=in_ch, out_channels_right=out_ch,\n keep_prob=drop_path_keep_prob)\n\n cell_idx += 1\n next_cell = NormalCell(in_channels_left=in_ch, out_channels_left=out_ch//fs,\n in_channels_right=in_ch+nf*fs*2, out_channels_right=out_ch, \n keep_prob=drop_path_keep_prob,\n factorized_reduction=True)\n setattr(self, \"cell_%i\"%cell_idx, next_cell)\n\n in_ch = nf*(fs*12)\n for i in range(cells_per_block-1):\n cell_idx += 1\n next_cell = NormalCell(in_channels_left=nf*fs*8 if i == 0 else in_ch, out_channels_left=out_ch,\n in_channels_right=in_ch, out_channels_right=out_ch,\n keep_prob=drop_path_keep_prob)\n setattr(self, \"cell_%i\"%cell_idx, next_cell)\n self.block1.append(next_cell)\n\n self.relu = nn.ReLU()\n self.dropout = nn.Dropout()\n self.last_linear = nn.Linear(in_ch, self.num_classes)\n\n def features(self, input):\n x_conv0 = self.conv0(input)\n if self.stem == 'imagenet':\n x_stem_0 = self.cell_stem_0(x_conv0)\n x_stem_1 = self.cell_stem_1(x_conv0, x_stem_0)\n cell_stack = [x_stem_1, x_stem_0]\n else:\n cell_stack = [x_conv0, input]\n\n cell_idx = 0\n for i in range(self.num_cells//3):\n next_cell = getattr(self, \"cell_%i\"%cell_idx)\n next_out = next_cell(*cell_stack[:2])\n cell_stack = [next_out] + cell_stack\n cell_idx += 1\n\n x_reduction_cell_0 = self.reduction_cell_0(*cell_stack[:2])\n cell_stack = [x_reduction_cell_0] + cell_stack\n\n for i in range(self.num_cells//3):\n next_cell = getattr(self, \"cell_%i\"%cell_idx)\n next_out = next_cell(*cell_stack[:2])\n cell_stack = [next_out] + cell_stack\n cell_idx += 1\n\n # stores most recent aux out in model\n self.aux_out = self.aux_head(cell_stack[0])\n\n x_reduction_cell_1 = self.reduction_cell_1(*cell_stack[:2])\n cell_stack = [x_reduction_cell_1] + cell_stack\n\n for i in range(self.num_cells//3):\n next_cell = getattr(self, \"cell_%i\"%cell_idx)\n next_out = next_cell(*cell_stack[:2])\n cell_stack = [next_out] + cell_stack\n cell_idx += 1\n\n return cell_stack[0]\n\n def logits(self, features):\n x = self.relu(features)\n x = F.avg_pool2d(x, x.size(2))\n x = x.view(x.size(0), -1)\n x = self.dropout(x)\n x = self.last_linear(x)\n return x\n\n def forward(self, input):\n x = self.features(input)\n x = self.logits(x)\n return x\n\n\nclass NASNetALarge(NASNet):\n def __init__(self, num_classes=1001):\n super(NASNetALarge, self).__init__(num_conv_filters=168,\n filter_scaling_rate=2, num_classes=num_classes, num_cells=18,\n stem_multiplier=3, stem='imagenet', drop_path_keep_prob=0.7)\n\n\nclass NASNetAMobile(NASNet):\n def __init__(self, num_classes=1001):\n super(NASNetAMobile, self).__init__(num_conv_filters=44,\n filter_scaling_rate=2, num_classes=num_classes, num_cells=12,\n stem_multiplier=1, stem='imagenet', drop_path_keep_prob=1.0)\n\n\nclass NASNetAcifar(NASNet):\n def __init__(self, num_classes=10):\n super(NASNetAcifar, self).__init__(num_conv_filters=32,\n filter_scaling_rate=2, num_classes=num_classes, num_cells=18,\n stem_multiplier=3, stem='cifar', drop_path_keep_prob=0.6)\n\n\ndef nasnetalarge(num_classes=1001, pretrained='imagenet'):\n r\"\"\"NASNetALarge model architecture from the\n `\"NASNet\" `_ paper.\n \"\"\"\n if pretrained:\n settings = pretrained_settings['nasnetalarge'][pretrained]\n assert num_classes == settings['num_classes'], \\\n \"num_classes should be {}, but is {}\".format(settings['num_classes'], num_classes)\n\n # both 'imagenet'&'imagenet+background' are loaded from same parameters\n model = NASNetALarge(num_classes=1001)\n model.load_state_dict(model_zoo.load_url(settings['url']))\n\n if pretrained == 'imagenet':\n new_last_linear = nn.Linear(model.last_linear.in_features, 1000)\n new_last_linear.weight.data = model.last_linear.weight.data[1:]\n new_last_linear.bias.data = model.last_linear.bias.data[1:]\n model.last_linear = new_last_linear\n\n model.input_space = settings['input_space']\n model.input_size = settings['input_size']\n model.input_range = settings['input_range']\n\n model.mean = settings['mean']\n model.std = settings['std']\n else:\n model = NASNetALarge(num_classes=num_classes)\n return model\n\n\ndef nasnetamobile(num_classes=1001, pretrained='imagenet'):\n r\"\"\"NASNetAMobile model architecture from the\n `\"NASNet\" `_ paper.\n \"\"\"\n raise NotImplementedError(\"Not yet trained a mobile ImageNet model.\")\n if pretrained:\n settings = pretrained_settings['nasnetalarge'][pretrained]\n assert num_classes == settings['num_classes'], \\\n \"num_classes should be {}, but is {}\".format(settings['num_classes'], num_classes)\n\n # both 'imagenet'&'imagenet+background' are loaded from same parameters\n model = NASNetALarge(num_classes=1001)\n model.load_state_dict(model_zoo.load_url(settings['url']))\n\n if pretrained == 'imagenet':\n new_last_linear = nn.Linear(model.last_linear.in_features, 1000)\n new_last_linear.weight.data = model.last_linear.weight.data[1:]\n new_last_linear.bias.data = model.last_linear.bias.data[1:]\n model.last_linear = new_last_linear\n\n model.input_space = settings['input_space']\n model.input_size = settings['input_size']\n model.input_range = settings['input_range']\n\n model.mean = settings['mean']\n model.std = settings['std']\n else:\n model = NASNetALarge(num_classes=num_classes)\n return model\n\ndef channel_inference_test(model, batch_size=2):\n assert isinstance(model, NASNetALarge)\n endpoints_shapes = {'cell_0': [batch_size, 42, 42, 1008],\n 'cell_1': [batch_size, 42, 42, 1008],\n 'cell_2': [batch_size, 42, 42, 1008],\n 'cell_3': [batch_size, 42, 42, 1008],\n 'cell_4': [batch_size, 42, 42, 1008],\n 'cell_5': [batch_size, 42, 42, 1008],\n 'cell_6': [batch_size, 21, 21, 2016],\n 'cell_7': [batch_size, 21, 21, 2016],\n 'cell_8': [batch_size, 21, 21, 2016],\n 'cell_9': [batch_size, 21, 21, 2016],\n 'cell_10': [batch_size, 21, 21, 2016],\n 'cell_11': [batch_size, 21, 21, 2016],\n 'cell_12': [batch_size, 11, 11, 4032],\n 'cell_13': [batch_size, 11, 11, 4032],\n 'cell_14': [batch_size, 11, 11, 4032],\n 'cell_15': [batch_size, 11, 11, 4032],\n 'cell_16': [batch_size, 11, 11, 4032],\n 'cell_17': [batch_size, 11, 11, 4032],\n 'reduction_cell_0': [batch_size, 21, 21, 1344],\n 'reduction_cell_1': [batch_size, 11, 11, 2688]}\n for k in sorted(endpoints_shapes.keys()):\n cell = getattr(model, k)\n if not cell.output_channels() == endpoints_shapes[k][3]:\n raise ValueError(\"Cell %s: inferred channels %i does not match expected output channels for this model %i\"%(k, cell.output_channels(), endpoints_shapes[k][3]))\n\nif __name__ == \"__main__\":\n model = NASNetALarge()\n model.eval()","repo_name":"akshitagupta15june/Face-X","sub_path":"Recognition-Algorithms/Recognition_using_NasNet/models/nasnet.py","file_name":"nasnet.py","file_ext":"py","file_size_in_byte":32248,"program_lang":"python","lang":"en","doc_type":"code","stars":557,"dataset":"github-code","pt":"15"} +{"seq_id":"29965489042","text":"from __future__ import annotations\n\nimport asyncio\nimport sys\nimport weakref\nfrom collections.abc import Coroutine, Sequence\nfrom datetime import timedelta\nfrom ipaddress import IPv4Address\nfrom operator import attrgetter\nfrom typing import TYPE_CHECKING, Any, Literal\n\nfrom typing_extensions import Self\n\nfrom . import utils\nfrom ._const import DOCS_BUILDING, URL\nfrom .abc import BaseUser, Messageable\nfrom .app import PartialApp\nfrom .enums import Language, PersonaState, PersonaStateFlag, Result, TradeOfferState, Type\nfrom .errors import ClientException, ConfirmationError, HTTPException\nfrom .id import _ID64_TO_ID32, ID\nfrom .profile import ClientUserProfile, OwnedProfileItems, ProfileInfo, ProfileItem\nfrom .protobufs import player\nfrom .types.id import ID32, ID64, AppID, Intable\nfrom .utils import DateTime, parse_bb_code\n\nif TYPE_CHECKING:\n from .app import App\n from .friend import Friend\n from .media import Media\n from .message import UserMessage\n from .protobufs.friends import CMsgClientPersonaStateFriend as UserProto\n from .state import ConnectionState\n from .trade import Inventory, Item, TradeOffer\n\n__all__ = (\n \"User\",\n \"ClientUser\",\n \"AnonymousClientUser\",\n)\n\n\nclass _BaseUser(BaseUser):\n __slots__ = (\n \"name\",\n \"app\",\n \"state\",\n \"flags\",\n \"trade_url\",\n \"last_seen_online\",\n \"last_logoff\",\n \"last_logon\",\n \"rich_presence\",\n \"game_server_ip\",\n \"game_server_port\",\n \"_state\",\n \"_avatar_sha\",\n )\n\n def __init__(self, state: ConnectionState, proto: UserProto):\n super().__init__(state, proto.friendid)\n self._update(proto)\n\n def _update(self, proto: UserProto) -> None:\n self.name = proto.player_name\n \"\"\"The user's username.\"\"\"\n self._avatar_sha = proto.avatar_hash\n self.trade_url = URL.COMMUNITY / f\"tradeoffer/new/?partner={self.id}\"\n \"\"\"The trade url of the user.\"\"\"\n\n self.game_server_ip = IPv4Address(proto.game_server_ip) if proto.game_server_ip else None\n \"\"\"The IP address of the game server the user is currently playing on.\"\"\"\n self.game_server_port = proto.game_server_port or None\n \"\"\"The port of the game server the user is currently playing on.\"\"\"\n\n self.last_logoff = DateTime.from_timestamp(proto.last_logoff)\n \"\"\"The last time the user logged off from steam.\"\"\"\n self.last_logon = DateTime.from_timestamp(proto.last_logon)\n \"\"\"The last time the user logged into steam.\"\"\"\n self.last_seen_online = DateTime.from_timestamp(proto.last_seen_online)\n \"\"\"The last time the user could be seen online.\"\"\"\n self.rich_presence = {message.key: message.value for message in proto.rich_presence}\n \"\"\"The rich presence of the user.\"\"\"\n self.app = (\n PartialApp(self._state, name=proto.game_name, id=proto.game_played_app_id)\n if proto.game_played_app_id\n else None\n )\n \"\"\"The app the user is playing. Is ``None`` if the user isn't in a app or one that is recognised by the API.\"\"\"\n self.state = PersonaState.try_value(proto.persona_state) or self.state\n \"\"\"The current persona state of the account (e.g. LookingToTrade).\"\"\"\n self.flags = PersonaStateFlag.try_value(proto.persona_state_flags) or self.flags\n \"\"\"The persona state flags of the account.\"\"\"\n\n\nclass User(_BaseUser, Messageable[\"UserMessage\"]):\n \"\"\"Represents a Steam user's account.\n\n .. container:: operations\n\n .. describe:: x == y\n\n Checks if two users are equal.\n\n .. describe:: str(x)\n\n Returns the user's name.\n \"\"\"\n\n __slots__ = ()\n\n async def add(self) -> None:\n \"\"\"Sends a friend invite to the user to your friends list.\"\"\"\n await self._state.add_user(self.id64)\n\n async def remove(self) -> None:\n \"\"\"Remove the user from your friends list.\"\"\"\n await self._state.remove_user(self.id64)\n self._state.user._friends.pop(self.id, None)\n\n async def cancel_invite(self) -> None:\n \"\"\"Cancels an invitation sent to the user. This effectively does the same thing as :meth:`remove`.\"\"\"\n await self._state.remove_user(self.id64)\n\n async def block(self) -> None:\n \"\"\"Blocks the user.\"\"\"\n await self._state.block_user(self.id64)\n\n async def unblock(self) -> None:\n \"\"\"Unblocks the user.\"\"\"\n await self._state.unblock_user(self.id64)\n\n async def escrow(self, token: str | None = None) -> timedelta | None:\n \"\"\"Check how long any received items would take to arrive. ``None`` if the user has no escrow or has a\n private inventory.\n\n Parameters\n ----------\n token\n The user's trade offer token, not required if you are friends with the user.\n \"\"\"\n resp = await self._state.http.get_user_escrow(self.id64, token)\n their_escrow = resp[\"response\"].get(\"their_escrow\")\n if their_escrow is None: # private\n return None\n seconds = their_escrow[\"escrow_end_duration_seconds\"]\n return timedelta(seconds=seconds) if seconds else None\n\n def _message_func(self, content: str) -> Coroutine[Any, Any, UserMessage]:\n return self._state.send_user_message(self.id64, content)\n\n def _media_func(self, media: Media) -> Coroutine[Any, Any, None]:\n return self._state.http.send_user_media(self.id64, media)\n\n async def send(\n self,\n content: Any = None,\n *,\n trade: TradeOffer | None = None,\n media: Media | None = None,\n ) -> UserMessage | None:\n \"\"\"Send a message, trade or image to an :class:`User`.\n\n Parameters\n ----------\n content\n The message to send to the user.\n trade\n The trade offer to send to the user.\n\n Note\n ----\n This will have its :attr:`~steam.TradeOffer.id` attribute updated after being sent.\n\n media\n The media to send to the user.\n\n Raises\n ------\n :exc:`~steam.HTTPException`\n Sending the message failed.\n :exc:`~steam.Forbidden`\n You do not have permission to send the message.\n\n Returns\n -------\n The sent message only applicable if ``content`` is passed.\n \"\"\"\n\n message = await super().send(content, media=media)\n if trade is not None:\n to_send = [item.to_dict() for item in trade.sending]\n to_receive = [item.to_dict() for item in trade.receiving]\n try:\n resp = await self._state.http.send_trade_offer(\n self, to_send, to_receive, trade.token, trade.message or \"\"\n )\n except HTTPException as e:\n if e.code == Result.Revoked and (\n any(item.owner != self for item in trade.receiving)\n or any(item.owner != self._state.user for item in trade.sending)\n ):\n if sys.version_info >= (3, 11):\n e.add_note(\n \"You've probably sent an item isn't either in your inventory or the user's inventory\"\n )\n else:\n raise ValueError(\n \"You've probably sent an item isn't either in your inventory or the user's inventory\"\n ) from e\n raise e\n trade._has_been_sent = True\n needs_confirmation = resp.get(\"needs_mobile_confirmation\", False)\n trade._update_from_send(self._state, resp, self, active=not needs_confirmation)\n if needs_confirmation:\n for tries in range(5):\n try:\n await trade.confirm()\n except ConfirmationError:\n break\n except ClientException:\n await asyncio.sleep(tries * 2)\n trade.state = TradeOfferState.Active\n\n # make sure the trade is updated before this function returns\n self._state._trades[trade.id] = trade\n self._state._trades_to_watch.add(trade.id)\n await self._state.wait_for_trade(trade.id)\n self._state.dispatch(\"trade_send\", trade)\n\n return message\n\n\nclass ClientUser(_BaseUser):\n \"\"\"Represents your account.\n\n .. container:: operations\n\n .. describe:: x == y\n\n Checks if two users are equal.\n\n .. describe:: str(x)\n\n Returns the user's name.\n \"\"\"\n\n # TODO more stuff to add https://github.com/DoctorMcKay/node-steamcommunity/blob/master/components/profile.js\n\n __slots__ = (\"_friends\", \"_inventory_locks\")\n\n def __init__(self, state: ConnectionState, proto: UserProto):\n super().__init__(state, proto)\n self._friends: dict[ID32, Friend] = {}\n self._inventory_locks = weakref.WeakValueDictionary[AppID, asyncio.Lock]()\n\n async def friends(self) -> Sequence[Friend]:\n \"\"\"A list of the user's friends.\"\"\"\n return list(self._friends.values())\n\n def get_friend(self, id: Intable) -> Friend | None:\n \"\"\"Get a friend from the client user's friends list.\"\"\"\n id32 = _ID64_TO_ID32(utils.parse_id64(id, type=Type.Individual))\n return self._friends.get(id32)\n\n async def inventory(self, app: App, *, language: Language | None = None) -> Inventory[Item[Self], Self]:\n try:\n lock = self._inventory_locks[app.id]\n except KeyError:\n lock = self._inventory_locks[app.id] = asyncio.Lock()\n\n async with lock: # requires a per-app lock to avoid Result.DuplicateRequest\n return await super().inventory(app, language=language)\n\n async def setup_profile(self) -> None:\n \"\"\"Set up your profile if possible.\"\"\"\n params = {\"welcomed\": 1}\n await self._state.http.get(URL.COMMUNITY / \"my/edit\", params=params)\n\n async def clear_nicks(self) -> None:\n \"\"\"Clears the client user's nickname/alias history.\"\"\"\n await self._state.http.clear_nickname_history()\n\n async def profile_items(self, *, language: Language | None = None) -> OwnedProfileItems[Self]:\n \"\"\"Fetch all the client user's profile items.\n\n Parameters\n ----------\n language\n The language to fetch the profile items in. If ``None`` the current language is used\n \"\"\"\n items = await self._state.fetch_profile_items(language)\n return OwnedProfileItems(\n backgrounds=[\n ProfileItem(self._state, self, background, um=player.SetProfileBackgroundRequest)\n for background in items.profile_backgrounds\n ],\n mini_profile_backgrounds=[\n ProfileItem(self._state, self, mini_profile_background, um=player.SetMiniProfileBackgroundRequest)\n for mini_profile_background in items.mini_profile_backgrounds\n ],\n avatar_frames=[\n ProfileItem(self._state, self, avatar_frame, um=player.SetAvatarFrameRequest)\n for avatar_frame in items.avatar_frames\n ],\n animated_avatars=[\n ProfileItem(self._state, self, animated_avatar, um=player.SetAnimatedAvatarRequest)\n for animated_avatar in items.animated_avatars\n ],\n modifiers=[ProfileItem(self._state, self, modifier) for modifier in items.profile_modifiers],\n )\n\n async def profile(self, *, language: Language | None = None) -> ClientUserProfile:\n return ClientUserProfile(\n *await asyncio.gather(\n self.equipped_profile_items(language=language),\n self.profile_info(),\n self.profile_customisation_info(),\n self.profile_items(language=language),\n )\n )\n\n async def profile_info(self: ClientUser | Friend) -> ProfileInfo:\n \"\"\"The friend's profile info.\"\"\"\n info = await self._state.fetch_friend_profile_info(self.id64)\n # why this is friend only I'm not really sure considering it's available through the API\n return ProfileInfo(\n created_at=DateTime.from_timestamp(info.time_created),\n real_name=info.real_name or None,\n city_name=info.city_name or None,\n state_name=info.state_name or None,\n country_name=info.country_name or None,\n headline=info.headline or None,\n summary=parse_bb_code(info.summary),\n )\n\n async def edit(\n self,\n *,\n name: str | None = None,\n real_name: str | None = None,\n url: str | None = None,\n summary: str | None = None,\n country: str | None = None,\n state: str | None = None,\n city: str | None = None,\n avatar: Media | None = None,\n # TODO privacy params, use ums\n ) -> None:\n \"\"\"Edit the client user's profile. Any values that aren't set will use their defaults.\n\n Parameters\n ----------\n name\n The new name you wish to go by.\n real_name\n The real name you wish to go by.\n url\n The custom url ending/path you wish to use.\n summary\n The summary/description you wish to use.\n country\n The country you want to be from.\n state\n The state you want to be from.\n city\n The city you want to be from.\n avatar\n The avatar you wish to use.\n\n Note\n ----\n This needs to be at least 184px x 184px.\n\n Raises\n -------\n :exc:`~steam.HTTPException`\n Editing your profile failed.\n \"\"\"\n if any((name, real_name, url, summary, country, state, city)):\n await self._state.http.edit_profile_info(name, real_name, url, summary, country, state, city)\n if avatar is not None:\n await self._state.http.update_avatar(avatar)\n # TODO privacy stuff\n\n\nclass WrapsUser(User if TYPE_CHECKING or DOCS_BUILDING else BaseUser, Messageable[\"UserMessage\"]):\n \"\"\"Internal class used for creating a User subclass optimised for memory. Composes the original user and forwards\n all of its attributes.\n\n Similar concept to discord.py's Member except more generalised for the larger number situations Steam throws at us.\n Slightly different however in that isinstance(SubclassOfWrapsUser(), User) should pass.\n\n Note\n ----\n This class does not forward ClientUsers attribute's so things like Clan().me.clear_nicks() will fail.\n\n If DOCS_BUILDING is True then this class behaves like a normal User because we need to be able to access the\n doc-strings reliably and memory usage isn't a concern.\n \"\"\"\n\n __slots__ = (\"_user\",)\n\n def __init__(self, state: ConnectionState, user: User):\n ID.__init__(self, user.id64, type=Type.Individual) # type: ignore\n self._user = user\n\n def __init_subclass__(cls) -> None:\n super().__init_subclass__()\n\n for name, function in set(User.__dict__.items()) - set(object.__dict__.items()):\n if not name.startswith(\"__\"):\n setattr(cls, name, function)\n\n if not DOCS_BUILDING:\n for name in _BaseUser.__slots__:\n setattr(cls, name, property(attrgetter(f\"_user.{name}\"))) # TODO time this with a compiled property\n # probably wont be different than the above\n\n User.register(cls)\n\n\nclass AnonymousClientUser(ID[Literal[Type.AnonUser]]):\n __slots__ = (\"_state\",)\n\n def __init__(self, state: ConnectionState, id64: int):\n super().__init__(id64, type=Type.AnonUser)\n self._state = state\n\n def __repr__(self) -> str:\n return f\"\"\n","repo_name":"AlimRs/steam.py","sub_path":"steam/user.py","file_name":"user.py","file_ext":"py","file_size_in_byte":16004,"program_lang":"python","lang":"en","doc_type":"code","dataset":"github-code","pt":"15"} +{"seq_id":"33153233380","text":"from flask import url_for\nimport atexit\nimport threading\nimport numpy as np\nfrom time import sleep\nimport random, cv2\nimport csv, os\n\ndef save_coordinates(coordinates, id, archive):\n # Lê o conteúdo do arquivo CSV existente, se houver\n current_data = {}\n try:\n with open(archive, 'r') as csv_archive:\n reader = csv.reader(csv_archive)\n for line in reader:\n current_data[line[0]] = line[1]\n except FileNotFoundError:\n pass\n\ndef generate_random_img(res):\n return np.random.randint(0, 255, size=(*res, 3), dtype=np.uint8)\n\ndef generate_random_text_image(width, height, text, font_scale):\n bg_color = np.random.randint(0, 256, 3)\n\n image = np.full((height, width, 3), bg_color, dtype=np.uint8)\n\n text_x = random.randint(50, width - 50)\n text_y = random.randint(50, height - 50)\n\n font = cv2.FONT_HERSHEY_SIMPLEX\n font_color = (255, 255, 255)\n thickness = 2\n\n (text_width, text_height), _ = cv2.getTextSize(text, font, font_scale, thickness)\n\n text_x -= text_width // 2\n text_y += text_height // 2\n\n cv2.putText(image, text, (text_x, text_y), font, font_scale, font_color, thickness)\n\n return image\n\nclass ModelDaemon(threading.Thread):\n def __init__(self, weights_path, demo_url, save_folder, seg_file_path=None, f=30):\n super().__init__(daemon=True)\n self.weights_path = weights_path\n self.demo_url = demo_url\n self.vid = None\n self.current_frame = None\n self.source = demo_url\n self.f = f\n self.running = False\n self.finished = False\n self.model = None\n self.save_folder = save_folder\n self.seg_file_path = seg_file_path\n self.user_seg = None\n\n def get_current_frame(self):\n if self.current_frame is not None:\n return self.current_frame\n return generate_random_img((1280, 720))\n \n def placeholder_loop(self):\n self.running = True\n while self.running:\n self.current_frame = generate_random_text_image(1280, 720, 'This is a test!', 1)\n sleep(1 / self.f)\n self.finished = True\n \n def set_seg(self, seg): \n if len(seg) > 3:\n self.user_seg = [[round(xy) for xy in l] for l in seg]\n if self.seg_file_path and os.path.exists(self.seg_file_path):\n save_coordinates(self.user_seg, self.demo_url, self.seg_file_path)\n return True\n return False\n\n def stop_running(self):\n self.running = False\n while not self.finished:\n sleep(0.01)\n\n def video_loop(self):\n #implemente a lógica do modelo aqui.\n\n self.placeholder_loop()\n\n def run(self):\n if not self.weights_path or not self.demo_url:\n print('YOLO model not detected. Using placeholder loop...')\n self.placeholder_loop()\n else:\n self.video_loop()\n\ndef kill_thread(model_daemon):\n print('\\n\\STOPPING MODEL')\n try:\n model_daemon.stop_running()\n except KeyboardInterrupt:\n print('\\n\\nFINISHED')\n \n\ndef create_module(app):\n from .views import inference_bp\n app.model_daemon = ModelDaemon(app.config.get('YOLO_WEIGHTS'), app.config.get('DEMO_URL'), seg_file_path=app.config.get('COORDENADAS'), save_folder=app.config.get('UPLOAD_FOLDER'))\n app.model_daemon.start()\n atexit.register(kill_thread, model_daemon=app.model_daemon)\n app.register_blueprint(inference_bp)","repo_name":"RenderV/camera-monitor","sub_path":"app/inference/__init__.py","file_name":"__init__.py","file_ext":"py","file_size_in_byte":3476,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"15"} +{"seq_id":"39583785797","text":"# -*- coding: utf-8 -*-\n\nimport math;\nimport numpy as np;\nfrom scipy.linalg import svdvals\n\npi = math.pi;\n\n\n\n#--------------dnorm_log-----------------------------------------------\n# Density function\ndef dnorm_log(x,mu,sigma):\n p = math.log(1.0/math.sqrt(2 * pi * sigma**2)) -0.5 * ((x-mu)/sigma)**2;\n return p;\n\n\n#--------------C_ii-------------------------------------------------\n# Calculates autocovariance within each model\ndef C_ii(par, d):\n \n A = math.exp(par[2]);\n B = math.exp(par[3]);\n v = math.exp(par[0]);\n w = math.exp(par[1]);\n \n C_ii_u = pi**0.5 * v**2 * 1.0/math.sqrt(A) * math.exp(-A*d**2*0.25);\n C_ii_v = pi**0.5 * w**2 * 1.0/math.sqrt(B) * math.exp(-B*d**2*0.25);\n \n C_ii = C_ii_u + C_ii_v;\n return C_ii;\n\n\n# #--------------C_12-------------------------------------------------\n# Calculates cross covariance between model 1 and 2\n\ndef C_12(par,d):\n A_1 = math.exp(par[2]);\n A_2 = math.exp(par[3]);\n v_1 = par[0];\n v_2 = par[1];\n miu = par[4];\n Sigma = A_1*(A_1 + A_2)**(-1)*A_2;\n C_12_u = (2*pi)**0.5*v_1*v_2*1.0/math.sqrt(A_1 + A_2) * math.exp(-Sigma*(d-miu)**2*0.5);\n return C_12_u\n\n\n# #--------------C_21-------------------------------------------------\n# Calculates cross covariance between model 2 and 1\n\ndef C_21(par, d):\n A_1 = math.exp(par[2]);\n A_2 = math.exp(par[3]);\n v_1 = par[0];\n v_2 = par[1];\n miu = par[4];\n \n Sigma = A_1*(A_1 + A_2)**(-1)*A_2;\n C_21_u = (2*pi)**0.5*v_1*v_2*1.0/math.sqrt(A_1+A_2) * math.exp(-Sigma*(d+miu)**2*0.5);\n return C_21_u;\n \n#--------------Covariance------------------------------------------------- \n# Construct covariance matrices using the above covariance functions \n# parameters:; [v1 w1 f1 g1 Beta1 v2 w2 f2 g2 Beta2 mu];\n\ndef Covariance(par, t1, t2):\n # Parameters for independant 1\n par1 = par[0:5]; \n \n # Parameters for independant 2\n par2 = par[5:10]; \n # Shared parameters\n par3 = [par[0], par[5], par[2], par[7], par[10]]; \n # Number of samples in model one \n N1 = len(t1);\n # Number of samples in model 2\n N2 = len(t2);\n # Total dimensions for matrices\n dim = N1 + N2; \n \n # Set up blank covariance matrices\n I = np.ndarray(shape = (dim,dim));\n Cv = np.ndarray(shape = (dim, dim)); \n C11 = np.ndarray(shape = (N1, N1));\n C22 = np.ndarray(shape = (N2, N2));\n C12 = np.ndarray(shape = (N1, N2));\n C21 = np.ndarray(shape = (N2, N1));\n count = 0;\n # Model one autocovariance\n for i in range(N1):\n for j in range(N1):\n C11[i,j] = C_ii(par1, t1[i] - t1[j])\n if i == j:\n I[i,j] = math.exp(par1[4])**2;\n\n # Model two auto covariance\n for i in range(N2):\n for j in range(N2): \n C22[i,j] = C_ii(par2, t2[i]-t2[j])\n if i == j:\n I[(N1 + i),(N1 + j)] = math.exp(par2[4])**2;\n \n # Cross covariance for 1 and 2\n for i in range(N1):\n for j in range(N2): \n C12[i,j] = C_12(par3, t1[i]-t2[j])\n \n for i in range(N2):\n for j in range(N1):\n C21[i,j] = C_21(par3, t2[i]-t1[j])\n \n # Construct final matrix\n Cv[0:N1,0:N1] = C11; \n Cv[(N1):dim + 1,(N1):dim] = C22; \n\n Cv[(N1):dim + 1,0:N1] = C21 \n Cv[0:N1,(N1):dim + 1] = C12 \n Cv = Cv + I\n return Cv\n \n#--------------log_lik-------------------------------------------------\ndef log_lik(par,Y,t1,t2,prior):\n \n N = len(Y)\n C = Covariance(par, t1, t2)\n C_I = np.linalg.inv(C)\n\n \n prior_v1 = dnorm_log(par[0], prior[0], prior[1])\n prior_v2 = dnorm_log(par[5], prior[0], prior[1])\n \n prior_w1 = dnorm_log(par[1], prior[2], prior[3])\n prior_w2 = dnorm_log(par[6], prior[2], prior[3])\n \n prior_f1 = dnorm_log(par[2], prior[4], prior[5])\n prior_f2 = dnorm_log(par[7], prior[4], prior[5])\n\n prior_g1 = dnorm_log(par[3], prior[6], prior[7])\n prior_g2 = dnorm_log(par[8], prior[6], prior[7])\n\n prior_b1 = dnorm_log(par[4], prior[8], prior[9])\n prior_b2 = dnorm_log(par[9], prior[8], prior[9])\n \n prior_mu = dnorm_log(par[10], prior[10], prior[11])\n \n ty = np.transpose(Y)\n M = ty.dot(C).dot(C_I)\n\n v = prior_v1 + prior_v2\n w = prior_w1 + prior_w2\n f = prior_f1 + prior_f2\n g = prior_g1 + prior_g2\n beta = prior_b1 + prior_b2\n\n SVD = svdvals(C) \n A = np.log10(SVD)\n A = np.sum(A)\n print(A)\n log_lkh = -1*(-0.5 * A - 0.5 * M - 0.5 * N * math.log(2*pi) + v + w + f + g + beta + prior_mu)\n \n return log_lkh;","repo_name":"hpetch-smith/MSC_thesis","sub_path":"Code/Python/MOGP.py","file_name":"MOGP.py","file_ext":"py","file_size_in_byte":4571,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"15"} +{"seq_id":"72279191050","text":"import os\nimport pandas as pd\nimport numpy as np\nimport pickle\nimport telebot\nimport openai\nfrom sentence_transformers import SentenceTransformer\n\nmodel = SentenceTransformer('paraphrase-MiniLM-L6-v2')\n\nopenai.api_key = os.environ[\"OPENAI_API_KEY\"]\nbot = telebot.TeleBot(os.environ[\"TELEGRAM_KEY\"])\n\npkl_embeddings = 'questions_embeddings.pkl'\n\ncsv_questions = pd.read_csv('questions.csv')\n\n\n# Save and read pkl embeddings\ndef save_to_pkl(data):\n with open(pkl_embeddings, 'wb') as f:\n return pickle.dump(data, f)\n\n\ndef open_pkl_object():\n with open(pkl_embeddings, 'rb') as f:\n return pickle.load(f)\n\n\n# Create csv file embeddings and save to pkl\nquestion_embeddings = model.encode(csv_questions['Question'].tolist())\nanswer_embeddings = model.encode(csv_questions['Answer'].tolist())\n\ndata = {}\nfor i, row in csv_questions.iterrows():\n question = row['Question']\n data[question] = {'question_emb': question_embeddings[i], 'answer_emb': answer_embeddings[i]}\n\nsave_to_pkl(data)\n\n\ndef get_best_answer(message):\n data = open_pkl_object()\n questions = list(data.keys())\n question_embeddings = np.array([data[q]['question_emb'] for q in questions])\n\n user_embedding = model.encode([message])[0]\n\n # Calculate the cosine similarity between the user embedding and the question embeddings\n similarities = np.dot(question_embeddings, user_embedding) / (\n np.linalg.norm(question_embeddings, axis=1) * np.linalg.norm(user_embedding))\n\n best_question_index = np.argmax(similarities)\n\n print(similarities)\n\n if similarities[best_question_index] < 0.4:\n return [0,\n \"Fale que não sabe sobre a questão. Pergunte se pode ajudar em \"\n \"algo mais?\"]\n\n best_response = csv_questions.iloc[best_question_index]['Answer']\n\n return [1, best_response]\n\n\ndef create_prompt(message):\n return f\"Você é um atendente que está ajudando um cliente do Rei dos Salgadinhos\\n\\nResponda conforme:{get_best_answer(message)}\\n\\nQ:{message}\\n\\nA:\"\n\n\n# Telegram bot\n@bot.message_handler(commands=['start'])\ndef handle_start(message):\n bot.send_message(message.chat.id, \"Seja bem vindo! Como posso ajudá-lo? Lembre-se de começar suas mensagens com /p!\")\n\n\n@bot.message_handler(commands=['p'])\ndef handle_chat(message):\n question = message.text[3:]\n response = openai.Completion.create(model=\"text-davinci-003\",\n prompt=create_prompt(question), temperature=0.3,\n max_tokens=250,\n top_p=1)\n answer = response['choices'][0]['text']\n bot.send_message(message.chat.id, answer)\n\n\nbot.polling()\n","repo_name":"jeanthomaz/waiter-ai","sub_path":"main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":2708,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"15"} +{"seq_id":"20402332101","text":"from PIL import Image\nim = Image.open(\"earthpixel.jpg\")\n#im.rotate(45).show()\n\ndark_blue = (0, 51, 76)\nred = (217, 26, 33)\nlight_blue = (112, 150, 158)\nyellow = (252, 227, 166)\n\n\npixels = im.getdata()\npixel_list = list(im.getdata())\n\n#print(pixel_list)\n\nnew_pixels = []\n\nfor pixel in pixels:\n\ttotal = pixel[0] + pixel[1] + pixel[2]\n\n\tif total <182:\n\t\tnew_pixels.append(dark_blue)\n\telif total >= 182 and total <= 364:\n\t\tnew_pixels.append(red)\n\telif total >= 364 and total <= 546:\n\t\tnew_pixels.append(light_blue)\n\telse:\n\t\tnew_pixels.append(yellow)\n\nnew_image = Image.new(im.mode, im.size)\nnew_image.putdata(new_pixels)\nnew_image.show()\nnew_image.save(\"outputttt.jpg\", \"jpeg\") \n\n\n\n","repo_name":"yiselb/Python","sub_path":"roseobamicon.py","file_name":"roseobamicon.py","file_ext":"py","file_size_in_byte":678,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"15"} +{"seq_id":"74438474571","text":"import csv\n\n\ndef findHighScore():\n file = open('scores.csv')\n fileRead = csv.reader(file)\n data = list(fileRead)\n\n if data:\n highScore = data[0][1]\n else:\n highScore = 0\n file.close()\n\n return int(highScore)\n\n\ndef newHighScore(name, score):\n file = open('scores.csv', 'r')\n readFile = csv.reader(file)\n data = list(readFile)\n\n file.close()\n\n file = open('scores.csv', 'w')\n write = csv.writer(file)\n write.writerow([name, str(score)])\n for row in data:\n write.writerow(row)\n file.close()\ndef addScore(name, score):\n file = open('scores.csv')\n readFile = csv.reader(file)\n data = list(readFile)\n print(data)\n file.close()\n\n file = open('scores.csv', 'w')\n write = csv.writer(file)\n index = 0\n for i in range(len(data)):\n if int(data[i][1])10:\n return data[:10]\n else:\n return data\n","repo_name":"ArV29/PianoTiles","sub_path":"fileStuf.py","file_name":"fileStuf.py","file_ext":"py","file_size_in_byte":1228,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"15"} +{"seq_id":"16791041982","text":"# -*- coding: utf-8 -*-\nimport requests\nimport config\n\n\ndef get_temp(domain, region):\n response = requests.get(\"%s?region=%s\" % (domain, region))\n #response.encoding = 'CP1251'\n s = response.text\n # color = s[s.find('\") - 5]\n wind_speed = s[s.find('') + 12:s.find(\"\")]\n wind_direction = s[s.find('\")] \\\n .replace('>', '')\n s = s[s.find('\") + 14]\n s = s[s.find('color=') + 15:s.find(\"\")] \\\n .replace(\"<' + 'br>\", \"\\n\") \\\n .replace(\"<' + 'br />\", \"\\n\") \\\n .replace('<', '<') \\\n .replace('>', '>') \\\n .replace('"', \"'\") \\\n .replace(' ', ' ')\n s = \"\"\"Температура за бортом %s°C. Ветер %s, %s м/с.\"\"\" % (s, wind_direction, wind_speed)\n # s = (\"%s?region=%s\" % (domain, region))\n return s\n\n\ntemp = get_temp(config.ya_weather_url, 213)\nprint(temp)\n","repo_name":"Ksardos/DomovoyValera","sub_path":"yandex_weather.py","file_name":"yandex_weather.py","file_ext":"py","file_size_in_byte":1051,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"15"} +{"seq_id":"533088070","text":"#!/usr/bin/python3\nimport sys\nimport argparse\nfrom score import Score\nfrom math import log\n\ndef blocksFromFiles(files):\n \"\"\"load and return blocks from the given files\n \"\"\"\n blocks = []\n for f in files:\n sequences = f.readlines()\n sequences = list(map(lambda x: x.strip(), sequences))\n blocks.append(sequences)\n return blocks\n\ndef haveEnoughtIdentity(seq1, seq2, percentage):\n \"\"\"Calculate identity between two sequences\n return True if identity between seq1 and seq2 > percentage%\n \"\"\"\n identical = 0\n different = 0\n for aa1, aa2 in zip(seq1, seq2):\n if aa1 == aa2:\n identical += 1\n if identical / float(len(seq1)) >= percentage / 100.0:\n return True\n else:\n different += 1\n if different / float(len(seq1)) > 1 - (percentage / 100.0):\n return False\n\n return identical / float(len(seq1)) >= percentage / 100.0\n\ndef canPlace(sequence, group, percentage):\n \"\"\" Verify if a sequence can be placed in a given group with a percentage\n \"\"\"\n for seq in group:\n if haveEnoughtIdentity(seq, sequence, percentage):\n return True\n return False\n\ndef placeInGroups(sequences, percentage):\n \"\"\"\n Make groups with all the sequences\n \"\"\"\n groups = []\n for seq in sequences:\n for group in groups:\n if canPlace(seq, group, percentage):\n group.append(seq)\n break\n else:\n groups.append([seq])\n return groups\n\ndef ponderateFrequencyMatrix(groups):\n \"\"\"\n Return the weighted matrix for the groups\n \"\"\"\n matrix = Score()\n length = len(groups[0][0])\n for i in range(length):\n for iGroup, group in enumerate(groups):\n for seq in group:\n aa1 = seq[i]\n for iOtherGroup, otherGroup in enumerate(groups):\n if iGroup != iOtherGroup:\n for otherSeq in otherGroup:\n aa2 = otherSeq[i]\n freq = (1 / len(group)) * (1 / len(otherGroup))\n if aa1 == aa2:\n freq = freq / 2\n matrix[aa1, aa2] = matrix.get((aa1, aa2), 0) + freq\n return matrix\n\ndef calculateFreqSum(matrix):\n \"\"\"\n Calculate the sum of the frequencies of a matrix.\n \"\"\"\n diag, tot = 0, 0\n for key, val in matrix.items():\n if key[0] == key[1]:\n diag += val\n else:\n tot += val\n tot = tot / 2 + diag\n return tot\n\ndef occurenceProbability(matrix):\n \"\"\"\n Calculate the occurrence weighted matrix of a frequencies matrix\n \"\"\"\n ponderate = Score()\n freqSum = calculateFreqSum(matrix)\n\n for key, val in matrix.items():\n ponderate[key] = val / freqSum\n return ponderate\n\ndef propability(matrix, aa):\n \"\"\"\n give the probability of a replacement for an aa\n \"\"\"\n prob = 0\n for key, val in matrix.items():\n if key[0] == aa and key[1] != aa:\n prob += val / 2\n return prob + matrix.get((aa, aa), 0)\n\ndef expectedFrequency(matrix):\n \"\"\"\n give the evolution matrix\n \"\"\"\n expected = Score()\n\n for key in matrix.keys():\n if key[0] == key[1]:\n expected[key] = propability(matrix, key[0]) ** 2\n else:\n expected[key] = 2 * propability(matrix, key[0]) * propability(matrix, key[1])\n return expected\n\ndef loggOddRatio(ponderate, expected, blosum):\n \"\"\"\n return the log odd ratio matrix.\n \"\"\"\n for key in ponderate.keys():\n blosum[key] = blosum.get(key, 0) + 2 * log(ponderate[key] / expected[key], 2)\n return blosum\n\ndef average(blosum, nbBlocks):\n \"\"\"\n Compute the average of the matrix by the number of blocks.\n \"\"\"\n for key in blosum.keys():\n blosum[key] = round(blosum[key] / nbBlocks)\n return blosum\n\ndef main(args):\n percentage = args.identity\n blosum = Score()\n blocks = blocksFromFiles(args.blocks)\n\n for sequences in blocks:\n groups = placeInGroups(sequences, percentage)\n frequencies = ponderateFrequencyMatrix(groups)\n ponderate = occurenceProbability(frequencies)\n expected = expectedFrequency(ponderate)\n blosum = loggOddRatio(ponderate, expected, blosum)\n blosum = average(blosum, len(blocks))\n print(blosum)\n if args.output:\n args.output.write(str(blosum))\n\nif __name__ == \"__main__\":\n parser = argparse.ArgumentParser(description=\"Create blosum matrix from blocs\")\n parser.add_argument(\"identity\", type=int, help=\"The percentage of identity that 2 sequences must have.\")\n parser.add_argument('blocks', type=argparse.FileType('r'), nargs='+', help=\"All the files each containing a block to use to create the blosum matrix.\")\n parser.add_argument('-o', \"--output\", type=argparse.FileType('w'), help=\"The file to write the generated matrix.\")\n\n args = parser.parse_args()\n main(args)\n\n","repo_name":"etnarek/info-f-208","sub_path":"projet2/blosum.py","file_name":"blosum.py","file_ext":"py","file_size_in_byte":5005,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"15"} +{"seq_id":"5098252290","text":"import pandas as pd\nimport ssl\nssl._create_default_https_context = ssl._create_unverified_context\n\nif __name__ == '__main__':\n df = pd.read_excel(\n 'https://stepik.org/media/attachments/lesson/245290/trekking3.xlsx')\n dairy = pd.read_excel(\n 'https://stepik.org/media/attachments/lesson/245290/trekking3.xlsx',\n sheet_name='Раскладка', index_col=False)\n\n merged = pd.merge(dairy, df, right_on=['Unnamed: 0'],\n left_on='Продукт')\n merged.fillna(0, inplace=True)\n\n merged['fats'] = merged['Вес в граммах'] * (merged['Ж на 100'] / 100)\n merged['carb'] = merged['Вес в граммах'] * (merged['У на 100'] / 100)\n merged['nuc'] = merged['Вес в граммах'] * (merged['Б на 100'] / 100)\n merged['cal'] = merged['Вес в граммах'] * (merged['ККал на 100'] / 100)\n\n res = pd.DataFrame()\n for item in ['cal', 'nuc', 'fats', 'carb']:\n res = pd.concat([res, merged.groupby('День')[item].sum()], axis=1)\n\n print(res.astype(int))","repo_name":"amamonova/web_data_analysis","sub_path":"stepik_practice_python/csc_task11.py","file_name":"csc_task11.py","file_ext":"py","file_size_in_byte":1068,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"15"} +{"seq_id":"10239248391","text":"import cv2 as cv\nfrom rx import Observable, Observer\nfrom rx.subjects import Subject \nfrom rx.concurrency import NewThreadScheduler, \\\n ThreadPoolScheduler, \\\n TkinterScheduler\n\nclass Webcam:\n def __init__(self):\n self._cap = cv.VideoCapture(0)\n self._stop_webcam = False\n # set up observable using multithreading\n producer_thread = ThreadPoolScheduler(1)\n\n self.observable = Observable.create(self._observer_fn) \\\n .subscribe_on(producer_thread) \\\n .publish() \\\n .auto_connect()\n\n # self._source = Observable.interval(1) \\\n # .take(1000) \\\n # .subscribe_on(NewThreadScheduler()) \\\n # .do_action(print) \\\n # .map(lambda i: self._cap.read()[1]) \\\n # .publish() \\\n # .auto_connect()\n\n def as_observable(self):\n # wrap it into Observable\n return self.observable\n\n def _observer_fn(self, observer):\n while True and not self._stop_webcam:\n ok, frame = self._cap.read()\n if ok:\n observer.on_next(frame)\n else:\n observer.on_error('Cannot read camera device')\n self.release()\n break\n\n return self.release\n\n def release(self):\n print('webcam.release')\n self._stop_webcam = True\n self._cap.release()","repo_name":"bencolove/com_italent_webcam","sub_path":"com_italent_webcam/webcam.py","file_name":"webcam.py","file_ext":"py","file_size_in_byte":1390,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"15"} +{"seq_id":"35061425045","text":"from flask import Flask\n\nfrom handler.request_handler import RequestHandler\n\napp = Flask(__name__)\n\n\n@app.route(\"/health\")\ndef health():\n return '', 200\n\n\n@app.route(\"/compute/\")\ndef handle_compute(freqGroupID):\n handler = RequestHandler()\n result = handler.execute_tasks(freqGroupID)\n return result, 200\n\n\nif __name__ == '__main__':\n app.run(debug=True, host='0.0.0.0', port=80)\n","repo_name":"real-time-footfall-analysis/rtfa-analytics","sub_path":"webapp.py","file_name":"webapp.py","file_ext":"py","file_size_in_byte":412,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"15"} +{"seq_id":"42979456368","text":"import os\n\nfrom celery import Celery\nfrom flask import Flask\n\nfrom config import config\n\n\ndef create_app(config_name, register_blueprint=True):\n app = Flask(__name__)\n app.config.from_object(config[config_name])\n\n if register_blueprint:\n from app.test_celery import test_celery as test_celery_blueprint\n app.register_blueprint(test_celery_blueprint)\n\n return app\n\n\ndef make_celery_app(app=None):\n app = app or create_app(os.getenv('FLASK_CONFIG') or 'default',\n register_blueprint=False)\n\n celery = Celery(\n app.import_name,\n backend=app.config['CELERY_RESULT_BACKEND'],\n broker=app.config['CELERY_BROKER_URL']\n )\n\n celery.conf.update(app.config)\n\n class ContextTask(celery.Task):\n\n def __call__(self, *args, **kwargs):\n with app.app_context():\n return self.run(*args, **kwargs)\n\n celery.Task = ContextTask\n return celery\n","repo_name":"newbieof410/dockerize-flask-celery","sub_path":"app/__init__.py","file_name":"__init__.py","file_ext":"py","file_size_in_byte":950,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"15"} +{"seq_id":"2936621994","text":"# coding:utf-8\n\"\"\"\nScript that scans 3 band tiff files and creates csv file with columns:\nimage_id, width, height\n\"\"\"\nfrom __future__ import division\nfrom owslib.wms import WebMapService\nimport extra_functions\nimport os\nfrom tqdm import tqdm\nfrom tqdm import trange\nimport pandas as pd\nimport cv2\nimport numpy as np\nimport shapely\nimport threading\n\ntry: # python3\n import queue as Queue\nexcept ImportError: # python2\n import Queue\nimport time\nimport tifffile as tiff\n\ndata_path = '../data'\n\nthree_band_path = os.path.join(data_path, 'three_band')\n\ntestData_path = '../data/'\ntest_testData_path = os.path.join(testData_path, 'test')\nfile_names = []\nwidths_3 = []\nheights_3 = []\n\nImageURL = \"https://geodata.nationaalgeoregister.nl/luchtfoto/rgb/wms?request=GetCapabilities\"\nContourURL = \"https://geodata.nationaalgeoregister.nl/aan/wms?request=GetCapabilities\"\nImageOutDirectory = '../data/image_tiles/'\nContourOutDirectory = '../data/contour_tiles/'\n\n\nclass DownloadThread(threading.Thread):\n def __init__(self, parameter, queue):\n threading.Thread.__init__(self)\n self.queue = queue\n self.ImageURL = parameter['ImageURL']\n self.ContourURL = parameter['ContourURL']\n self.ImageOutDirectory = parameter['ImageOutDirectory']\n self.ContourOutDirectory = parameter['ContourOutDirectory']\n self.x_num = parameter['x_num']\n self.y_num = parameter['y_num']\n self.x_stride = parameter['x_stride']\n self.y_stride = parameter['y_stride']\n self.x_start = parameter['x_start']\n self.y_start = parameter['y_start']\n\n def run(self):\n time.sleep(np.random.randint(0, 40))\n ImageWms = WebMapService(self.ImageURL, version='1.1.1', timeout=200)\n ContourWms = WebMapService(self.ContourURL, version='1.1.1', timeout=200)\n x_min = self.x_start\n y_min = self.y_start\n for ii in range(0, self.x_num):\n for jj in range(0, self.y_num):\n ll_x_ = x_min + ii * self.x_stride\n ll_y_ = y_min + jj * self.y_stride\n bbox = (ll_x_, ll_y_, ll_x_ + self.x_stride, ll_y_ + self.y_stride)\n try:\n img_3 = tiff.imread(\"%s%f_%f_%f_%f.tif\" % (ImageOutDirectory, bbox[0], bbox[1], bbox[2], bbox[3]))\n if (img_3.max() - img_3.min()) < 30:\n try:\n img = ImageWms.getmap(layers=['Actueel_ortho25'], srs='EPSG:4326', bbox=bbox,\n size=(1024, 1024), format='image/GeoTIFF', transparent=True)\n except:\n self.queue.put(0)\n continue\n try:\n ContourImg = ContourWms.getmap(layers=['aan'], srs='EPSG:4326', bbox=bbox,\n size=(4096, 4096), format='image/png', transparent=True)\n except:\n self.queue.put(0)\n continue\n self.queue.put(1)\n continue\n except BaseException:\n try:\n img = ImageWms.getmap(layers=['Actueel_ortho25'], srs='EPSG:4326', bbox=bbox, size=(1024, 1024),\n format='image/GeoTIFF', transparent=True)\n except:\n self.queue.put(0)\n continue\n try:\n ContourImg = ContourWms.getmap(layers=['aan'], srs='EPSG:4326', bbox=bbox, size=(4096, 4096),\n format='image/png', transparent=True)\n except:\n self.queue.put(0)\n continue\n filename = \"{}_{}_{}_{}.tif\".format(bbox[0], bbox[1], bbox[2], bbox[3])\n filename2 = \"{}_{}_{}_{}.png\".format(bbox[0], bbox[1], bbox[2], bbox[3])\n with open(self.ImageOutDirectory + filename, 'wb') as out:\n out.write(img.read())\n with open(self.ContourOutDirectory + filename2, 'wb') as out1:\n out1.write(ContourImg.read())\n self.queue.put(1)\n # time.sleep(np.random.randint(10, 20))\n\n\ndef download_map_data(ImageURL, ContourURL, ImageOutDirectory, ContourOutDirectory):\n parameter = {}\n q = Queue.Queue()\n thead_num = 100\n x_min = 4.525307\n y_min = 51.689726\n parameter['ImageURL'] = ImageURL\n parameter['ContourURL'] = ContourURL\n parameter['ImageOutDirectory'] = ImageOutDirectory\n parameter['ContourOutDirectory'] = ContourOutDirectory\n parameter['x_stride'] = 0.005\n parameter['y_stride'] = 0.005\n no_tiles_x = 100\n no_tiles_y = 100\n total_no_tiles = no_tiles_x * no_tiles_y\n # 确保可以整除\n x_block = no_tiles_x / thead_num\n for ii in range(0, thead_num):\n parameter['x_start'] = x_min + ii * x_block * parameter['x_stride']\n parameter['y_start'] = y_min\n parameter['x_num'] = int(x_block)\n parameter['y_num'] = no_tiles_y\n t = DownloadThread(parameter, q)\n t.start()\n pbar = tqdm(total=total_no_tiles)\n number = 0\n k = 0\n while number < total_no_tiles:\n i = q.get()\n if i == 1:\n pbar.update(i)\n else:\n k += 1\n print(\"下载出现错误已经跳过\")\n number += 1\n pbar.close()\n print(\"预备下载:%d\" % total_no_tiles)\n print(\"实际下载:%d\" % (total_no_tiles - k))\n print(\"下面开始检查图片\")\n\n\n# 针对有些数据没有现在完全,将其检查出来并重新下载。\ndef downloadcheck(x_min, y_min, x_num, y_num, x_stride, y_stride, ImageOutDirectory, ContourOutDirectory):\n num = 0\n for ii in trange(x_num):\n for jj in range(y_num):\n ll_x_ = x_min + ii * x_stride\n ll_y_ = y_min + jj * y_stride\n bbox = (ll_x_, ll_y_, ll_x_ + x_stride, ll_y_ + y_stride)\n try:\n img_3 = tiff.imread(\"%s%f_%f_%f_%f.tif\" % (ImageOutDirectory, bbox[0], bbox[1], bbox[2], bbox[3]))\n except BaseException:\n print(\"%s%f_%f_%f_%f.tif\" % (ImageOutDirectory, bbox[0], bbox[1], bbox[2], bbox[3]))\n singleDownloadmap(bbox, ImageURL, ContourURL, ImageOutDirectory, ContourOutDirectory)\n num += 1\n print(\"已经修复%d张缺失或下载错误的tif卫星图\" % num)\n print(\"下面开始生成csv文件\")\n\n\ndef singleDownloadmap(bbox, ImageURL, ContourURL, ImageOutDirectory, ContourOutDirectory):\n ImageWms = WebMapService(ImageURL, version='1.1.1', timeout=2000)\n ContourWms = WebMapService(ContourURL, version='1.1.1', timeout=2000)\n img = ImageWms.getmap(layers=['Actueel_ortho25'], srs='EPSG:4326', bbox=bbox, size=(1024, 1024),\n format='image/GeoTIFF', transparent=True)\n ContourImg = ContourWms.getmap(layers=['aan'], srs='EPSG:4326', bbox=bbox, size=(4096, 4096),\n format='image/png', transparent=True)\n filename = \"{}_{}_{}_{}.tif\".format(bbox[0], bbox[1], bbox[2], bbox[3])\n filename2 = \"{}_{}_{}_{}.png\".format(bbox[0], bbox[1], bbox[2], bbox[3])\n with open(ImageOutDirectory + filename, 'wb') as out:\n out.write(img.read())\n with open(ContourOutDirectory + filename2, 'wb') as out1:\n out1.write(ContourImg.read())\n\n\ndef create_contour_csv(ContourOutDirectory, outputPath):\n result = []\n numb = 0\n num = 0\n # 黑白轮廓图所占比例\n blankcoef = 0.1\n coef = 0.1\n k = 0\n pbar = tqdm(total=int(coef * len(sorted(os.listdir(ContourOutDirectory)))))\n for file_name in tqdm(sorted(os.listdir(ContourOutDirectory))):\n try:\n img_3 = extra_functions.read_image_new_3(file_name[0:-4]) * 2047\n if (img_3.max() - img_3.min()) < 30:\n k += 1\n continue\n except:\n k+=1\n continue\n ContourImg = cv2.imread(ContourOutDirectory + file_name)\n # print(file_name)\n ContourImg = ContourImg[:, :, 0]\n if ContourImg.min()==ContourImg.max():\n if numb== int(blankcoef*coef*len(sorted(os.listdir(ContourOutDirectory)))):\n continue\n else:\n numb+=1\n polygons = extra_functions.png2polygons_layer(ContourImg)\n result += [(file_name[0:-4], shapely.wkt.dumps(polygons))]\n num += 1\n pbar.update(1)\n if num == int(coef * len(sorted(os.listdir(ContourOutDirectory)))):\n break\n pbar.close()\n contoursCSV = pd.DataFrame(result, columns=['file_name', 'MultipolygonWKT'])\n contoursCSV.to_csv(os.path.join(outputPath, 'contours.csv'), index=False)\n print(\"出现%d张脏数据\" % k)\n print(\"存入%d张空白轮廓图和%d张农田轮廓图,共%d张轮廓图\" % (numb, num-numb, num))\n print(\"csv文件生成成功!\")\n\n\nif __name__ == '__main__':\n # download_map_data(ImageURL, ContourURL, ImageOutDirectory, ContourOutDirectory)\n # downloadcheck(4.525307,51.689726,100,100,0.005,0.005,ImageOutDirectory, ContourOutDirectory)\n create_contour_csv(ContourOutDirectory, testData_path)\n\n","repo_name":"boran-dev/SatelliteImageSegmentation","sub_path":"src/download_data.py","file_name":"download_data.py","file_ext":"py","file_size_in_byte":9323,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"15"} +{"seq_id":"1746014455","text":"import pygame\n\nfrom constant.constant import Constant\nfrom level.level import Level\n\n\nclass GraphicLevel(Level):\n \"\"\"\n class used to diplay the maze in pygame\n \"\"\"\n def __init__(self, file):\n Level.__init__(self, file)\n self.file = file\n\n @staticmethod\n def resize_set(pic):\n \"\"\"\n resizing sets pictures\n \"\"\"\n return pygame.transform.scale(\n pygame.image.load(pic).convert_alpha(), (30, 30))\n\n def display(self, window):\n \"\"\"\n maze displaying items and bad guy\n \"\"\"\n macgyver = self.resize_set(Constant.constant['macgyver'])\n wall = self.resize_set(Constant.constant['wall_picture'])\n floor = self.resize_set(Constant.constant['floor_picture'])\n flag = self.resize_set(Constant.constant['flag_picture'])\n bad_guy = self.resize_set(Constant.constant['bad_guy_picture'])\n needle = self.resize_set(Constant.constant['needle_picture'])\n ether = self.resize_set(Constant.constant['ether_picture'])\n syringe = self.resize_set(Constant.constant['syringe_picture'])\n tube = self.resize_set(Constant.constant['tube_picture'])\n line_number = 0\n for line in self.structure:\n sprite_number = 0\n for sprite in line:\n x = sprite_number * Constant.constant['sprite_size']\n y = line_number * Constant.constant['sprite_size']\n if sprite == 'm':\n window.blit(wall, (x, y))\n elif sprite == 'X':\n window.blit(floor, (x, y))\n window.blit(macgyver, (x, y))\n elif sprite == '0':\n window.blit(floor, (x, y))\n elif sprite == 'd' or sprite == 'a':\n window.blit(flag, (x, y))\n elif sprite == 'b':\n window.blit(floor, (x, y))\n window.blit(bad_guy, (x, y))\n elif sprite == 'N':\n window.blit(floor, (x, y))\n window.blit(needle, (x, y))\n elif sprite == 'E':\n window.blit(floor, (x, y))\n window.blit(ether, (x, y))\n elif sprite == 'S':\n window.blit(floor, (x, y))\n window.blit(syringe, (x, y))\n elif sprite == 'T':\n window.blit(floor, (x, y))\n window.blit(tube, (x, y))\n sprite_number += 1\n line_number += 1\n","repo_name":"romainh3nry/MacGyver_Maze","sub_path":"level/graphic_level.py","file_name":"graphic_level.py","file_ext":"py","file_size_in_byte":2546,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"15"} +{"seq_id":"22870321018","text":"# Funktion zum Umdrehen und Invertieren eines zwei-\r\n# dimensionalen Arrays. An die Funktion wird das zu\r\n# bearbeitende Array übergeben. Die Funktion selbst\r\n# gibt das fertig bearbeitete Array zurück.\r\ndef flip_and_invert(input_data):\r\n # Ausgabe-Array mit gleicher Größe\r\n out = create_array(len(input_data), len(input_data[0]))\r\n\r\n # Gehe jede Zeile und Spalte durch\r\n for i in range(0, len(input_data)):\r\n for j in range(0, len(input_data[0])):\r\n # Oben wird unten hingeschrieben und umgekehrt\r\n # Inhalt wird invertiert\r\n if input_data[i][j]:\r\n content = False\r\n else:\r\n content = True\r\n out[len(input_data) - 1 - i][j] = content\r\n return out\r\n\r\n\r\n# Funktion zur grafischen Darstellung eines\r\n# zweidimensionalen Arrays, welches an die\r\n# Funktion übergeben wird\r\ndef display_array(input_data):\r\n # Höhe und Breite des Arrays bestimmen\r\n i_width = len(input_data[0])\r\n i_height = len(input_data)\r\n\r\n # Größe pro Rechteck, abhängig vom Bildschirmfenster\r\n x_size = width / i_width\r\n y_size = height / i_height\r\n\r\n # Gehe jede Zeile und Spalte durch\r\n for y in range(0, i_height):\r\n for x in range(0, i_width):\r\n # Bestimme Farbe\r\n # True = Setze Farbe auf Weiß\r\n if input_data[y][x]:\r\n fill(255)\r\n # Sonst setze Farbe auf Grau\r\n else:\r\n fill(125)\r\n # Male Kasten auf Bildschirm\r\n rect(x * x_size, y * y_size, x_size, y_size)\r\n\r\n\r\n# Generiert leeres 2D-Array in den Dimensionen size_x x size_y\r\ndef create_array(size_x, size_y):\r\n print(size_x, size_y)\r\n output = []\r\n for x in range(0, size_x):\r\n row = []\r\n for y in range(0, size_y):\r\n row = row + [False]\r\n output = output + [row]\r\n return output\r\n\r\n\r\n# Startpunkt des Hauptprogramms\r\n# Hier wird die implementierte Funktion zu Demonstrations- und\r\n# Testzwecken aufgerufen.\r\nsize(800, 800)\r\ninput = [[False, True, True],\r\n [True, False, True],\r\n [True, True, False],\r\n [True, False, True]]\r\n\r\n# display_array(input_data)\r\ndisplay_array(flip_and_invert(input))\r\n","repo_name":"protrain/loesungen","sub_path":"loesungen_in_python/06-arrays/aufgabe_W_6_12_flipandinvert/aufgabe_W_6_12_flipandinvert.pyde","file_name":"aufgabe_W_6_12_flipandinvert.pyde","file_ext":"pyde","file_size_in_byte":2242,"program_lang":"python","lang":"de","doc_type":"code","stars":15,"dataset":"github-code","pt":"15"} +{"seq_id":"34336760659","text":"import os\nimport sys\nimport json\nimport spotipy\nimport spotipy.util as util\nimport spotipy.oauth2 as oauth2\nfrom spotipy import Spotify\nimport math\nfrom config import CLIENT_ID, CLIENT_SECRET, REDIRECT\n\n\n'''\nwork harder, work smarter\nbut work harder to work smarter\n'''\nclass Connectify(Spotify):\n\n def __init__(self, auth=None, requests_session=True, client_credentials_manager=None, proxies=None, requests_timeout=None):\n super().__init__( auth, requests_session,\n client_credentials_manager, proxies,\n requests_timeout)\n\n def login(self, username, password):\n pass\n\n def delete_duplicate(self, list1):\n dict = {}\n for element in list1:\n dict[element] = True\n return list(dict.keys())\n\n def recommend(self, seed_artists=None, seed_genres=None, seed_tracks=None, limit=20, country=None, **kwargs):\n \"\"\"\n *** since math.ceil is used, the number of recommended songs will be greater than limit\n Returns:\n this is kinda odd, it returns a list of songs in json notation but they are only the songs in json\n currently can only handle seed_artists or seed_tracks\n rewrite to actually work with Spotify.recommendations\n\n Purpose: bypasses the 5 input limit on Spotify.recommendations\n\n make the tracks list more space and time effiecit\n \"\"\"\n\n tracks = []\n if seed_artists:\n tracksPerLoop = math.ceil(limit*5/len(seed_artists))\n for i in range(0, len(seed_artists), 5):\n tracks = tracks + self.recommendations(seed_artists = seed_artists[i:i+4], limit = tracksPerLoop)['tracks']\n\n elif seed_tracks:\n tracksPerLoop = math.ceil(limit * 5 / len(seed_tracks))\n for i in range(0, len(seed_tracks), 5):\n tracks = tracks + self.recommendations(seed_tracks=seed_tracks[i:i + 5], limit=tracksPerLoop)['tracks']\n\n return tracks\n\n def create_playlist_from_two_artist(self, list1, list2, type='artist', limit=20, playlistName = None):\n \"\"\"\n *** make compatable with collabrative play lists\n this is meant for longer playlsit with many songs with two playlists that are simalar\n\n :param self: current Spotify Obj\n :param list1: playlist id\n :param list2: playlist id\n :param type: type of list to return\n 'artist' or 'track'\n :param limit: number of songs in playlist\n :param playlistName: a str to name the playlist\n :return: none, a fucking play list is made. lets fucking goooo\n\n PURPOSE: create a playlist from two other playlists\n \"\"\"\n pl1 = self.playlist(list1)\n pl2 = self.playlist(list2)\n\n ownerId = [pl1['owner']['id'], pl2['owner']['id']]\n rootOwner = self.me()['id']\n ownerNames = [pl1['owner']['display_name'], pl2['owner']['display_name']]\n\n if playlistName is None:\n playlistName = 'Connectify between ' + ownerNames[0] + ' and ' + ownerNames[1]\n\n inCommon = [] # a list of in common factors (artists ext) the list has\n hash = {}\n flaggedhash = {} # a hash of the songs that were added hash list, stores the song id that wash hashed opn\n \"\"\"\n hash sub item is using pl1 by defualt but could be improved (time and space) by adding something that detirmins\n which list has less elements and ueses that one \n i am working fast so i will come back to this \n \"\"\"\n rtnKey = 'id'\n for track in pl1['tracks']['items']:\n for artist in track['track']['artists']:\n hash[artist[rtnKey]] = True\n flaggedhash[artist[rtnKey]] = track['track']['id']\n\n flaggedSongs = [] # songs thayt trigger a match will be added to the new list\n for track in pl2['tracks']['items']:\n try:\n for artist in track['track']['artists']:\n try:\n if hash[artist[rtnKey]] == True:\n inCommon.append(artist[rtnKey])\n if flaggedhash[artist[rtnKey]] != track['track'][rtnKey]:\n flaggedSongs.append(flaggedhash[artist[rtnKey]])\n flaggedSongs.append(track['track'][rtnKey])\n except KeyError:\n pass\n except TypeError:\n pass\n\n flaggedSongs = self.delete_duplicate(flaggedSongs) # delete duplicates is ineffiect but the lists are small so it does matter\n recommended = self.recommend(seed_artists = inCommon, limit=limit)\n\n ids = [recommended[x]['id'] for x in range(len(recommended))] # ids of tracks to be added to the playlist\n ids = flaggedSongs + ids\n\n pl = self.user_playlist_create(rootOwner, playlistName)\n\n self.user_playlist_add_tracks(rootOwner, pl['id'], ids[0:limit])\n\n def create_playlist_from_two_track(self, list1, list2, type='artist', limit=20, playlistName = None):\n \"\"\"\n *** make compatable with collabrative play lists\n Notes: list1s user\n\n :param self: current Spotify Obj\n :param list1: playlist id\n :param list2: playlist id\n :param type: type of list to return\n 'artist' or 'track'\n :param limit: number of songs in playlist\n :param playlistName: a str to name the playlist\n :return: none, a fucking play list is made. lets fucking goooo\n\n PURPOSE: create a playlist from two other playlists\n \"\"\"\n pl1 = self.playlist(list1)\n pl2 = self.playlist(list2)\n\n ownerId = [pl1['owner']['id'], pl2['owner']['id']]\n rootOwner = self.me()['id']\n ownerNames = [pl1['owner']['display_name'], pl2['owner']['display_name']]\n\n if playlistName is None:\n playlistName ='Connectify between '+ ownerNames[0] + ' and ' + ownerNames[1]\n\n inCommon = [] # a list of in common factors (artists ext) the list has\n hash = {}\n flaggedhash = {} # a hash of the songs that were added hash list, stores the song id that wash hashed opn\n \"\"\"\n hash sub item is using pl1 by defualt but could be improved (time and space) by adding something that detirmins\n which list has less elements and ueses that one \n i am working fast so i will come back to this \n \"\"\"\n rtnKey = 'id'\n for track in pl1['tracks']['items']:\n try:\n hash[track['track'][rtnKey]] = True\n flaggedhash[track['track'][rtnKey]] = track['track']['id']\n flaggedSongs = [] # songs thayt trigger a match will be added to the new list\n for track in pl2['tracks']['items']:\n try:\n if hash[track['track'][rtnKey]] == True:\n inCommon.append(track['track'][rtnKey])\n flaggedSongs.append(track['track'][rtnKey])\n except KeyError:\n pass\n\n except TypeError:\n pass\n\n\n flaggedSongs = self.delete_duplicate(flaggedSongs) # delete duplicates is ineffiect but the lists are small so it does matter\n\n recommended = self.recommend(seed_tracks = inCommon, limit = limit)\n\n ids = [recommended[x]['id'] for x in range(len(recommended))]# ids of tracks to be added to the playlist\n ids = flaggedSongs + ids\n\n pl = self.user_playlist_create(rootOwner, playlistName)\n self.user_playlist_add_tracks(rootOwner, pl['id'], ids[0:limit])\n\n def get_user_playlist_names(self, userId, limit = 10):\n \"\"\"\n :param self: self\n :param userId: id of userhttps://open.spotify.com/playlist/3qxMbjCfMeOE1sk330CzwW?si=VW25orjiR7uhbumulLeOXA\n :return: a list of the users ids and names\n \"\"\"\n jsonList = self.user_playlists(userId, limit = limit)['items']\n l = len(jsonList)\n lists = [[jsonList[x]['name'] for x in range(l)], [jsonList[x]['id'] for x in range(l)]]\n return lists\n\n def link_to_id(self, string):\n \"\"\"\n This only works if the id comes after the forth '/'\n make sure this is alwauys the case before release\n \"\"\"\n start = 0\n for i in range(4):\n start = string.find('/', start+1)\n end = string.find('?')\n return string[start+1:end]\n\n def connect_playlists_artist(self, lists, limit = 20, playlistName = None):\n \"\"\"\n *** to do : add defualt playlist name\n :param lists: a list of playlist ids to refference\n :return: nothing, creates a fucking playlist\n\n Logic: we will dict hash the lists\n each dictonry entry will have a number (in c i would make this a byte bc i never need more than 30ish scores)\n the number will represent how many times the ARTIST comes up.\n ***NOTICABLE FLAW IN CURRENT ALGORTHEM\n if one user has an artist 5 times but no other user has that artist it will still be scored\n this could potentialy be changed by wieghting each entry ex the forst time an artist is found in a list the\n number is increased by 5 but each subsenent time the number is only increased by 1\n \"\"\"\n if len(lists) > 5 or len(lists) < 1:\n print('you may input 5 playlists at max')\n pass\n\n rootOwner = self.me()['id']\n playlists = [] # array of playlists\n ownerId = []\n ownerName = []\n\n i = 0\n for item in lists:\n playlists.append(self.playlist(item))\n ownerId.append(playlists[i]['owner']['id'])\n ownerName.append(playlists[i]['owner']['display_name'])\n i += 1\n\n # creating a defualt playlist name\n if playlistName == None:\n playlistName = \"Connectify between \"\n l = len(ownerName) # temp variable j used to as length of playlists inputed\n for i in range(l-1):\n playlistName = playlistName + ownerName[i] + \", \"\n playlistName = playlistName + \"and \" + ownerName[l-1]\n\n hash = {} # hashing dict\n longestHash = {}\n longest = [] # keeps track of witch tracks are longest (index 0 being the longest)\n rtnKey = 'id'\n\n for playlist in playlists:\n weight = 5\n for trackFile in playlist['tracks']['items']:\n try:\n for artist in trackFile['track']['artists']:\n try:\n hash[artist[rtnKey]] += weight\n weight = 1\n index = longestHash[artist[rtnKey]]\n while index > 0 and hash[longest[index]] > hash[longest[index - 1]]:\n temp = longest[index]\n longest[index] = longest[index - 1]\n longest[index - 1] = temp\n longestHash[longest[index]] = index\n longestHash[longest[index - 1]] = index - 1\n index -= 1\n except KeyError:\n hash[artist[rtnKey]] = weight\n weight = 1\n longest.append(artist[rtnKey])\n longestHash[artist[rtnKey]] = len(longest) - 1\n except TypeError:\n pass\n weight = 5\n\n recommended = self.recommend(seed_artists = longest[0:limit], limit = limit) # a playlist of recommended songs\n\n ids = [recommended[x]['id'] for x in range(len(recommended))] # geting a string of id's\n\n plNew = self.user_playlist_create(rootOwner, playlistName) # creating a new playlist\n self.user_playlist_add_tracks(rootOwner, plNew['id'], ids) # adding tracks to the plalist,\n\n # plNew['id'] return the id to the playlist, not the ids to the song itself\n\n def connect_playlists_track(self, lists, limit = 20, playlistName = None):\n \"\"\" :param lists: a list of play lit ids to refference\n :return: nothing, creates a fucking playlst\n\n \"\"\"\n if len(lists) > 5 or len(lists) < 1:\n print('you may input 5 playlists at max')\n pass\n rootOwner = self.me()['id']\n playlists = [] # array of playlists\n ownerId = []\n ownerName = []\n i = 0\n for item in lists:\n playlists.append(self.playlist(item))\n ownerId.append(playlists[i]['owner']['id'])\n ownerName.append(playlists[i]['owner']['display_name'])\n i+=1\n\n # creating a defualt playlist name\n if playlistName == None:\n playlistName = \"Connectify between \"\n l = len(ownerName) # temp variable j used to as length of playlists inputed\n for i in range(l-1):\n playlistName = playlistName + ownerName[i] + \", \"\n playlistName = playlistName + \"and \" + ownerName[l-1]\n\n hash = {} # hashing dict\n longestHash = {}\n longest = [] # keeps track of witch tracks are longest (index 0 being the longest)\n rtnKey = 'id'\n for playlist in playlists:\n weight = 5\n for track in playlist['tracks']['items']:\n try:\n hash[track['track'][rtnKey]] += weight\n weight = 1\n index = longestHash[track['track'][rtnKey]]\n while index > 0 and hash[longest[index]] > hash[longest[index - 1]]:\n temp = longest[index]\n longest[index] = longest[index - 1]\n longest[index - 1] = temp\n longestHash[longest[index]] = index\n longestHash[longest[index - 1]] = index - 1\n index -= 1\n except KeyError:\n hash[track['track'][rtnKey]] = weight\n weight = 1\n longest.append(track['track'][rtnKey])\n longestHash[track['track'][rtnKey]] = len(longest) - 1\n except TypeError:\n pass\n weight = 5\n\n inCommon = longest[0:limit] # id's of the tracks that are in Common\n\n recommended = self.recommend(seed_tracks = inCommon, limit = limit) # a playlist of recommended songs\n\n ids = [recommended[x]['id'] for x in range(len(recommended))] # geting a string of id's\n\n plNew = self.user_playlist_create(rootOwner, playlistName) # creating a new playlist\n self.user_playlist_add_tracks(rootOwner, plNew['id'], ids) # adding tracks to the plalist,\n # plNew['id'] return the id to the playlist, not the ids to the song itself\n\nusername = '22brul7byn6y4j7mbf7b3lqni?si=mbEmeKifRma_KPfhvCeJEw'\nscope = 'playlist-modify-private, playlist-modify-public'\n# token access\ntry:\n token = util.prompt_for_user_token(username, scope, client_id=CLIENT_ID, client_secret=CLIENT_SECRET, redirect_uri=REDIRECT)\nexcept (AttributeError, JSONDecodeError):\n os.remove(f\".cache-{username}\")\n token = util.prompt_for_user_token(username, scope, client_id=CLIENT_ID, client_secret=CLIENT_SECRET, redirect_uri=REDIRECT) # add scope\n\n\nif __name__ == '__main__':\n sp = Connectify(auth = token)\n oliList = sp.link_to_id('https://open.spotify.com/playlist/2qHQAeWodnTIwaBAq2XMFK?si=4XyoD_1SS6SiDwfrCifxVg')\n bradsList = sp.link_to_id('https://open.spotify.com/playlist/5jgWyRgmourpdGKwcJlaVb?si=dP52a-iJQrStZ69yvWAFEg')\n tatumList = '337iuYE8p67CgpYLkxJQAB'\n bradsDailyMix = sp.link_to_id('https://open.spotify.com/playlist/37i9dQZF1E35DWQ5HH0zaM?si=0Uzm2yaxRxqMd9Hv55TH7Q')\n katieList = sp.link_to_id('https://open.spotify.com/playlist/68Femg7qFxcDEqndrJHPek?si=5BFJn2ASSTW8v72oIDUpnw')\n dm2 = sp.link_to_id('https://open.spotify.com/playlist/37i9dQZF1E3ai78NrdudXr?si=qACwzK5VRNeN0ptb9M-Vmw')\n elana = sp.link_to_id('https://open.spotify.com/playlist/58XMVSxtc3XwQfviDelrTX?si=wgMOL-EAQkKXMARRYFi8cg')\n trizz = sp.link_to_id('https://open.spotify.com/playlist/0VBzREMhSP09IJ3rTjhd3O?si=WxZT695bQfWRBBa9L241Og')\n helen = sp.link_to_id('https://open.spotify.com/playlist/5Um4Is3sUnmKRe13pmULDC?si=PfPcdoKJQpCNm1Veh2KGWQ')\n jack = '58nLGY8huHXWPcINIBRDH6'\n shower = '27Pcoi5En5FI9KKIYAdHQ6'\n #sp.createPlaylist(bradsList, oliList)\n #sp.connect_playlists_artist([bradsList, tatumList], limit =19)\n #sp.connect_playlists_track([bradsList, tatumList, oliList], limit =33)\n zach = sp.link_to_id('https://open.spotify.com/playlist/2tyqz4AjNPa3CRXaUIdJyv?si=1Nwi00svSMyBvy4_1tIvcQ')\n rapcav = sp.link_to_id('https://open.spotify.com/user/spotify/playlist/37i9dQZF1DX0XUsuxWHRQd?si=rWDHChIeSzui1G8r4fV3RQ')\n hannahO = sp.link_to_id('https://open.spotify.com/playlist/0q7ec8w5bjEdRBd5FBC86O?si=JOrwoV4KTQSdnkEVdq6eZA')\n mtsnow = sp.link_to_id('https://open.spotify.com/playlist/2NiMMSW7GVKCjpdAFT3hZN?si=qSbwukZGTN-l9h5xuirdxQ')\n sp.create_playlist_from_two_artist(bradsList, zach, limit=30)\n","repo_name":"electricdarb/Portfolio","sub_path":"mian.py","file_name":"mian.py","file_ext":"py","file_size_in_byte":17359,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"15"} +{"seq_id":"71761550733","text":"\"\"\"\n프로그래머스 - 순위 검색\n- list comprehension으로 풀었다\n- 정확성은 다 맞았는데, 효율성은 다 틀렸다.\n- 효율성 개선 방법(카카오 풀이 참고)\n 1. 모든 경우의 수 그룹을 dict로 미리 만든다. 마치 Hash Table처럼. {'조건합친값':''}\n - from itertools import combinations 쓸 줄 알아야 함\n - ''(빈 문자열)도 dict의 key가 될 수 있구나\n 2. 점수만 list에 넣고 x 이상인 점수가 몇��인지 찾는다.\n 3. 'x 이상인 점'을 찾기 위해 binary search 를 쓴다.\n - 당연히 binary search니까 정렬 해야겠지 먼저\n - binary search는 정확한 값을 찾는거라서, lower bound를 찾도록(이상인 점!) 조금 수정한다.\n- 런타임 에러 .. 뭐야 ... : key가 dict에 없는 경우를 처리 안해줬었다.\n- 바이너리 서치 해도 시간초과.. 답은 다 맞는데 .. \n (효율성 2개 통과) 정렬을 16번 * query 갯수만큼 하니까 시간초과났다. 정렬은 딱 번씩만 미리 해줘야한다.\n (효율성 4개 모두 통과) list comprehension을 뺐다.. - 도 계속 remove 하게\n\"\"\"\nfrom itertools import combinations\n\ndef solution(info, query):\n # 1. 가능한 모든 경우의 수 그룹 저장\n applicants = {}\n\n for item in info:\n info_list = item.split()\n score = int(info_list[-1])\n info_list = info_list[:-1]\n\n # 효율성 개선 핵심. 하나의 info에서 가능한 모든 조합을 미리 만들어둔다\n # 모든 조합 구하는 문법 알아두기 (다 지우고 다시 해보자)\n for i in range(5):\n combs = combinations(info_list, i) # 리스트, 조합의 원소 수. 예) 2이면 2개짜리 모든 조합 구해줌\n \n for c in combs:\n key = ''.join(c) # 문자열.join(iterable한 타입)\n \n if key in applicants:\n applicants[key].append(score)\n else:\n applicants[key] = [score]\n \n # 정렬을 딱 한번씩만 먼저 해준다.\n for key in applicants:\n applicants[key].sort()\n\n # 2. 쿼리마다 맞는 답 몇 명인지 찾기\n answer = []\n for q in query:\n query_list = q.split()\n del query_list[1:6:2] # and를 다 없앤다 1,3,5번 index\n\n score = int(query_list[-1])\n query_list = query_list[:-1]\n\n # 여기때문에 시간초과 났음 !!!!!!\n # key = ''.join([x for x in query_list if x!='-'])\n while '-' in query_list: # 그냥 -를 빼준다.\n query_list.remove('-')\n key = ''.join(query_list)\n\n # 바이너리 서치 할거니까 정렬\n # (런타임 에러)아얘 없는 키가 있을 수도 있으니까 꼭 처리해줘야 함\n if key in applicants:\n data = applicants[key]\n # print(data)\n\n # 3. (핵심) 이분탐색으로 score이상인 애들이 몇개인지 찾기\n if len(data) == 0: # 조건 만족하는 애가 아무도 없으면..\n answer.append(0)\n else:\n # 바이너리 서치\n left = 0\n right = len(data) - 1\n\n while left <= right:\n mid = (left+right)//2\n\n # x 이상이면 (원하는 값을 찾음. 범위를 줄이자!)\n if data[mid] >= score:\n right = mid-1\n else: # 너무 작으면, 더 큰값을 찾아 떠난다.\n left = mid+1\n # 갯수\n answer.append(len(data)-left)\n else:\n answer.append(0)\n return answer\n\ninfo = [\"java backend junior pizza 150\",\"python frontend senior chicken 210\",\"python frontend senior chicken 150\",\"cpp backend senior pizza 260\",\"java backend junior chicken 80\",\"python backend senior chicken 50\"]\nquery = [\"java and backend and junior and pizza 250\",\"python and frontend and senior and chicken 200\",\"cpp and - and senior and pizza 250\",\"- and backend and senior and - 150\",\"- and - and - and chicken 100\",\"- and - and - and - 150\"]\n\nans = solution(info, query)\nprint(ans)\n","repo_name":"easyfordev/algorithm","sub_path":"programmers/순위검색.py","file_name":"순위검색.py","file_ext":"py","file_size_in_byte":4239,"program_lang":"python","lang":"ko","doc_type":"code","stars":0,"dataset":"github-code","pt":"15"} +{"seq_id":"36745265607","text":"import pandas as pd\r\nimport matplotlib.pyplot as plt\r\n\r\ndf = pd.read_csv(input())\r\ndf.drop(['Unnamed: 0'], axis='columns', inplace=True)\r\n\r\nnames=df[\"CARGO\"].unique()\r\n\r\nnumber=[]\r\ncost=[]\r\nmass=[]\r\n\r\nfor i in range(len(names)):\r\n number.append(df.CARGO.value_counts()[names[i]])\r\n cost.append(df.loc[df['CARGO'] == names[i]]['PRICE'].sum())\r\n mass.append(df.loc[df['CARGO'] == names[i]]['WEIGHT'].sum())\r\n\r\nfig, axs = plt.subplots(nrows=1, ncols=3)\r\naxs[0].bar(names,number)\r\naxs[0].set_title('Number of flights')\r\naxs[1].bar(names,cost)\r\naxs[1].set_title('Total weight')\r\naxs[2].bar(names,mass)\r\naxs[2].set_title('Total price')\r\n\r\nplt.show()","repo_name":"irinapashkevich/lab3","sub_path":"lab3.2.py","file_name":"lab3.2.py","file_ext":"py","file_size_in_byte":652,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"15"} +{"seq_id":"28461050238","text":"#!/usr/bin/python3\n\nimport os\nimport copy\nfrom prolog_parser import parser\nfrom interp_v3 import interprete4\nfrom exc import NotUnifiable\nfrom utils import filter\n\n\nprint(\"================ Interpreteur Prolog ================\")\n\n\ndef interp_help():\n \"\"\"\n Fonction permettant d'afficher l'aide de l'interpreteur\n \"\"\"\n print(\n \"help:\\n\"\n \"\\tcommandes mode normal (>):\\n\"\n \"\\t\\tload [PATH]: charger un programme depuis un chemin, un seul programme est interprete a la fois\\n\"\n \"\\t\\thelp: affiche cette aide\\n\"\n \"\\t\\texit: sortir de l'interpreteur\\n\"\n \"\\tcommandes mode programme (#>):\\n\"\n \"\\t\\t[RULE]: ajout d'une regle au programme courant\\n\"\n \"\\t\\t?-[GOAL]: interpretation d'un goal\\n\"\n \"\\t\\ttrace [0/1]: desactiver/activer le mode trace\\n\"\n \"\\t\\tsols [0/1]: desactiver/activer la recherche de toutes les solutions\\n\"\n \"\\t\\texit: retour au mode normal\\n\"\n )\n\n\ndef load(path: str):\n \"\"\"\n Fonction permettant de charger un programme depuis un fichier\n \"\"\"\n if not os.path.exists(path):\n print(f\"programme non trouvé: {path}\")\n return None\n return parser.parseFile(path)\n\n\ndef interp(prg, cmd: str, trace: bool, allsols: bool):\n \"\"\"\n Fonction permettant d'interpreter un programme, en prenant en compte les différentes options demandées (trace, plusieurs solutions ...)\n\n Args:\n prg: programme a interpreter\n cmd: but a resoudre\n trace: si l'affichage trace doit etre activé\n allsols: si toutes les solutions doivent etre affichées\n \"\"\"\n prg = copy.deepcopy(prg)\n prg.decls += parser.parseString(cmd).decls\n\n lst = []\n try:\n while True:\n env = interprete4(prg, trace, lst)\n #print(env)\n lst.append(env)\n filtered_env = filter(env)\n if filtered_env == {}:\n print(\"solution: true\")\n else:\n print(f\"solution: {filtered_env}\")\n if not allsols:\n break\n else:\n i = input(\"continue [y/n]: \")\n if i != \"y\":\n break\n except NotUnifiable:\n print(\"pas de solution trouvée : false\")\n\n\n\nprog = None\nshell = \">\"\ntrace = False\nall_sols = True\n\ninterp_help()\n\nwhile True:\n i = input(shell + \" \")\n if len(i) < 4:\n continue\n cmd = i[0:4]\n if shell == \">\":\n if cmd == \"load\":\n if len(i) < 6:\n print(\"veuillez entrer un chemin valide\")\n continue\n prog = load(i[5:])\n if prog is not None:\n shell = \"#>\"\n elif cmd == \"help\":\n interp_help()\n elif cmd == \"exit\":\n exit()\n else:\n print(\"commande inconnue\")\n else:\n if cmd == \"trac\":\n if len(i) == 7:\n trace = i[6] == \"1\"\n if trace:\n print(\"trace activée\")\n else:\n print(\"trace desactivée\")\n else:\n print(\"entrée invalide\")\n elif cmd == \"sols\":\n if len(i) == 7:\n all_sols = i[6] == \"1\"\n if all_sols:\n print(\"affichage toutes les solutions activée\")\n else:\n print(\"affichage toutes les solutions desactivée\")\n else:\n print(\"entrée invalide\")\n elif cmd == \"exit\":\n prog = None\n shell = \">\"\n else:\n if i[0] == \"?\":\n interp(prog, i, trace, all_sols)\n else:\n prog.decls += parser.parseString(cmd).decls\n","repo_name":"kirito-night/Sorbonne","sub_path":"L3 INFO/S2/LU3IN032/Projet/projet/python/main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":3704,"program_lang":"python","lang":"fr","doc_type":"code","stars":5,"dataset":"github-code","pt":"15"} +{"seq_id":"22307798795","text":"import discord\r\nimport json\r\nfrom discord.ext import commands\r\n\r\nclass Welcomemsg(commands.Cog):\r\n def __init__(self, bot):\r\n self.bot = bot\r\n\r\n\r\n\r\n\r\n @commands.Cog.listener()\r\n async def on_member_join(self,member):\r\n channel = self.bot.get_channel(853602966966501428)\r\n channel2 = self.bot.get_channel(853606717824303124)\r\n channel3 = self.bot.get_channel(853604724846624818)\r\n channel4 = self.bot.get_channel(862629281682948106)\r\n mc = str(member.guild.member_count)\r\n em = discord.Embed(title=f\"Welcome to NeXus Official Server\",description=\":small_red_triangle_down: Make sure\\n:small_blue_diamond: Read:- <#853604724846624818> follow them.\\n:small_blue_diamond: Read:- <#862629281682948106> react to emojis to view channel\\n:small_blue_diamond: Use:- <#853606717824303124> for chatting with other members\\n:small_blue_diamond: Read <#870912068147097631> To get help regarding your coding help\")\r\n em.set_image(url=\"https://www.google.com/url?sa=i&url=https%3A%2F%2Ftenor.com%2Fsearch%2Fanimated-welcome-gifs&psig=AOvVaw3WbwACfHO1CUpr5vFgESNy&ust=1633755368148000&source=images&cd=vfe&ved=0CAkQjRxqFwoTCPDi7ZWDuvMCFQAAAAAdAAAAABAD\")\r\n em.add_field(name=\"☆━━━━━━━━━━━━━━━━━━━━━━━━━━☆\",value=\"\\u200b\",inline=False)\r\n em.add_field(name=\"User Registered - 🔹\", value=f\"{member.mention}\",inline=False)\r\n em.add_field(name=\"Now we have:\", value=f\"{mc} members\",inline=True)\r\n em.set_author(name=\"NeXus Welcome's you\", icon_url=\"https://cdn.discordapp.com/attachments/857143597132677141/895891970046717972/New_Project_19.png\")\r\n em.set_thumbnail(url=member.avatar.url)\r\n em.set_footer(text=f\"Be active in the server and have fun 💖\", icon_url=\"https://cdn.discordapp.com/attachments/857143597132677141/895891970046717972/New_Project_19.png\")\r\n await channel.send(embed=em)\r\n await member.send(\"🔻 Make sure\\n🔹 React:-to chat in channels, click 👉 <#862629281682948106> to get verified or else you cant talk in the server \\n🔹 please read <#853604724846624818>\\n If any issues like cant talk or smthing else \\n DM <@!862186182242861077> and explain your issue we will help\\nInvite your friend using the link below \\nhttps://discord.gg/pEmrd7J448\") \r\n await channel2.send(f\"Hey Everyone \\nLets welcome our new user {member.mention}\\nhope you enjoy in the server\\nNow we have: **{mc}** members\")\r\n await channel3.send(f\"{member.mention}\", delete_after = 1)\r\n await channel4.send(f\"{member.mention}\", delete_after = 1)\r\n\r\n\r\n\r\n @commands.Cog.listener()\r\n async def on_member_remove(self,member):\r\n channel = self.bot.get_channel(854722331687911434)\r\n mc = str(member.guild.member_count)\r\n await channel.send(f\"Bad news **{member.mention}** just left the server 😪\\nI hope he had a great time here\\nNow we have only **{mc} members** :sob:\")\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\ndef setup(bot):\r\n bot.add_cog(Welcomemsg(bot))\r\n","repo_name":"alexyy802/nca","sub_path":"cogs/welcomemsg.py","file_name":"welcomemsg.py","file_ext":"py","file_size_in_byte":3058,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"15"} +{"seq_id":"41426801637","text":"#!/usr/bin/python3\n\nimport matplotlib.pyplot as plt\nimport numpy as np\nimport math\nfrom definitions import *\n\n\nclass DotGraph:\n def __init__(self, x, y1, y2=None):\n self.fig, self.ax = plt.subplots(1, 1, tight_layout=True, figsize=(plot_width, plot_height), dpi=plot_dpi)\n\n self.ax.plot(x, y1, color=color_dot_1, linestyle=\"\", marker=\"D\")\n if y2 is not None:\n self.ax.plot(x, y2, color=color_dot_2, linestyle=\"\", marker=\"o\")\n self.ax.plot([0, 1], [1, 1], color=color_flat_line, linestyle=\":\", marker=\"\")\n self.ax.set_ylim(0.9, 1.1)\n\n def save(self, path):\n self.fig.savefig(path)\n\n def show(self):\n self.fig.show()\n\n\nif __name__ == \"__main__\":\n np.random.seed(19680801)\n N_points = 50\n\n y = np.random.randn(N_points)\n y *= 0.2\n y += math.pi\n\n dg = DotGraph(range(len(y)), y)\n dg.show()\n","repo_name":"DavidRisch/buffon","sub_path":"util/dot_graph.py","file_name":"dot_graph.py","file_ext":"py","file_size_in_byte":876,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"15"} +{"seq_id":"41143525799","text":"import re\n\nfrom leapp.libraries.common.vsftpdutils import (\n get_default_config_hash,\n STRICT_SSL_READ_EOF,\n TCP_WRAPPERS,\n VSFTPD_DEFAULT_CONFIG_PATH\n)\nfrom leapp.libraries.stdlib import api\n\nANONYMOUS_ENABLE = 'anonymous_enable'\n\n\nclass FileOperations(object):\n def read(self, path):\n with open(path, 'r') as f:\n return f.read()\n\n def write(self, path, content):\n with open(path, 'w') as f:\n f.write(content)\n\n\ndef _replace_in_config(config_lines, option, value):\n res = []\n for line in config_lines:\n if re.match(r'^\\s*' + option, line) is None:\n res.append(line)\n else:\n res.append('# Commented out by Leapp:')\n res.append('#' + line)\n if value is not None:\n res.append('# Added by Leapp:')\n res.append('%s=%s' % (option, value))\n return res\n\n\ndef _restore_default_config_file(fileops=FileOperations()):\n try:\n content = fileops.read(VSFTPD_DEFAULT_CONFIG_PATH)\n except IOError as e:\n api.current_logger().warning('Failed to read vsftpd configuration file: %s' % e)\n return\n lines = content.split('\\n')\n lines = _replace_in_config(lines, ANONYMOUS_ENABLE, 'YES')\n content = '\\n'.join(lines)\n content += '\\n'\n fileops.write(VSFTPD_DEFAULT_CONFIG_PATH, content)\n\n\ndef _migrate_config(config, fileops=FileOperations()):\n if not config.tcp_wrappers and config.strict_ssl_read_eof is not None:\n return\n try:\n content = fileops.read(config.path)\n except IOError as e:\n api.current_logger().warning('Failed to read vsftpd configuration file %s: %s'\n % (config.path, e))\n return\n lines = content.split('\\n')\n if config.tcp_wrappers:\n lines = _replace_in_config(lines, TCP_WRAPPERS, 'NO')\n if config.strict_ssl_read_eof is None:\n lines = _replace_in_config(lines, STRICT_SSL_READ_EOF, 'NO')\n content = '\\n'.join(lines)\n content += '\\n'\n try:\n fileops.write(config.path, content)\n except IOError as e:\n api.current_logger().warning('Failed to write vsftpd configuration file %s: %s'\n % (config.path, e))\n\n\ndef migrate_configs(facts, fileops=FileOperations()):\n if facts.default_config_hash is not None:\n new_hash = get_default_config_hash(read_func=fileops.read)\n # If the default config file was unmodified, it got replaced during the RPM upgrade,\n # so we have to change it back.\n if facts.default_config_hash != new_hash:\n _restore_default_config_file(fileops=fileops)\n for config in facts.configs:\n _migrate_config(config, fileops=fileops)\n","repo_name":"oamg/leapp-repository","sub_path":"repos/system_upgrade/el7toel8/actors/vsftpdconfigupdate/libraries/vsftpdconfigupdate.py","file_name":"vsftpdconfigupdate.py","file_ext":"py","file_size_in_byte":2717,"program_lang":"python","lang":"en","doc_type":"code","stars":37,"dataset":"github-code","pt":"15"} +{"seq_id":"41922124876","text":"# Program asks for total bill, then will ask for percentage to be tipped.\n# Finally it will ask how many people will split the bill.\n# Output should only contain decimals upto 2 digits.\n\nprint(\"Welcome to the tip calculator\")\ntotal_bill = int(input(\"What is the total bill?\\n\"))\npercent_tip = int(input(\"What percent would you like to tip?\\n\"))\ntotal_number_of_people = int(input(\"How many people to split the bill?\\n\"))\ncost_per_person = (total_bill + (total_bill * (percent_tip / 100))) / total_number_of_people\nprint(f\"Each person pays {cost_per_person}\")","repo_name":"jeronimo1708/python_projects","sub_path":"tip-calculator/main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":558,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"15"} +{"seq_id":"10595654560","text":"# -*- coding: utf-8 -*-\n\"\"\"\nCreated on Tue May 17 18:16:32 2016\n\n@author: vpuller\n\"\"\"\nfrom __future__ import division\n#import numpy as np\nfrom Bio import Phylo\nimport sys, os\nimport matplotlib.pyplot as plt\n\nsys.path.append('/ebio/ag-neher/share/users/vpuller/betatree/')\nfrom betatree import betatree as bt\n\nif __name__==\"__main__\":\n '''Generate test trees'''\n plt.ioff()\n outdir_name = '/ebio/ag-neher/share/users/vpuller/GTR_staggered/trees/'\n if not os.path.exists(outdir_name):\n os.makedirs(outdir_name) \n \n nleaves = 1000\n myT = bt.betatree(nleaves,alpha = 2)\n myT.yule = True\n myT.coalesce()\n myT.BioTree.ladderize()\n\n\n for jclade, clade in enumerate(myT.BioTree.get_terminals()):\n clade.name = 'A' + clade.name\n \n Phylo.write(myT.BioTree, outdir_name + 'test_tree{}.nwk'.format(nleaves), 'newick')\n \n fig10=plt.figure(10,figsize=(20,20)) \n plt.clf()\n ax10=fig10.add_subplot(1,1,1)\n Phylo.draw(myT.BioTree,do_show = False,axes = ax10)\n plt.savefig(outdir_name + 'test_tree.pdf')\n plt.close(10)\n ","repo_name":"vpuller/GTR_sitespec","sub_path":"test_trees.py","file_name":"test_trees.py","file_ext":"py","file_size_in_byte":1093,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"15"} +{"seq_id":"13721383537","text":"import os\nimport json\nimport re\n\nimport numpy as np\nimport altair as alt\nfrom codemetrics.vega import vis_ages\nfrom codemetrics.vega import vis_hot_spots\n\n\n# TODO: verify duplication in codemetrics report\n\n\nIGNORE_PATHS = (\".\", \"docs\", \"doc\", \"tests\", \"test\", \"notebooks\")\nIGNORE_LANGS = (\"reStructuredText\", \"Markdown\", \"make\")\nIGNORE_EXTS = (\n \"geo\",\n \"xmf\",\n \"xdmf\",\n \"h5\",\n \"hdf5\",\n \"xml\",\n \"json\",\n \"yml\",\n \"yaml\",\n \"csv\",\n \"svg\",\n \"png\",\n)\n\n\ndef create_loc_chart(loc_df):\n loc_sum = (\n loc_df.groupby(\"language\")\n .sum()\n .reset_index()\n .melt(id_vars=[\"language\"])\n .rename(columns={\"variable\": \"type\", \"value\": \"lines\"})\n )\n\n chart = (\n alt.Chart(loc_sum)\n .mark_bar()\n .encode(\n x=alt.X(\"lines:Q\"),\n y=alt.Y(\n \"language:N\",\n sort=alt.EncodingSortField(field=\"lines\", op=\"sum\", order=\"descending\"),\n ),\n color=alt.Color(\"type:N\", scale=alt.Scale(scheme=\"accent\")),\n tooltip=[\"lines:Q\", \"type:O\"],\n )\n .properties(title=\"Lines of code\")\n )\n\n return chart\n\n\ndef create_age_chart(ages_df, weeks=52):\n\n width = 1000\n weeks = list(range(weeks))\n chart = alt.Chart(ages_df).encode(color=\"language\")\n top = (\n chart.mark_bar()\n .encode(\n x=alt.X(\n \"age_agg:O\",\n sort=\"ascending\",\n title=\"age in weeks\",\n scale=alt.Scale(domain=weeks),\n ),\n y=alt.Y(\"count(path):Q\", title=\"Number of files\"),\n color=alt.Color(\"language\", scale=alt.Scale(scheme=\"tableau10\")),\n tooltip=[\"count(path)\", \"language\"],\n )\n .transform_calculate(age_agg=\"floor(datum.age / 7)\")\n .properties(width=width)\n )\n bottom = (\n chart.mark_tick(size=60, thickness=2, opacity=0.3)\n .encode(x=alt.X(\"age:Q\", title=\"age in days\"), tooltip=\"path\")\n .properties(width=width)\n )\n chart = alt.vconcat(top, bottom)\n\n return chart\n\n\ndef create_age_loc_chart(ages_df, height=500, width=500, **kwargs):\n \"\"\"\n Notes:\n Use `VegaLite` to visualize output.\n \"\"\"\n return vis_ages(ages_df, height=height, width=width, **kwargs)\n\n\ndef create_hotspots_chart(\n hspots, width=500, height=500, size_column=\"complexity\", **kwargs\n):\n \"\"\"\n Notes:\n Use `VegaLite` to visualize output.\n \"\"\"\n return vis_hot_spots(\n hspots, width=width, height=height, size_column=size_column, **kwargs\n )\n\n\ndef exclude_paths(df, ignore_paths=IGNORE_PATHS, col_name=\"path\"):\n if \".\" in ignore_paths:\n df = exclude_root_files(df, col_name=col_name)\n ignore_paths = list(ignore_paths)\n ignore_paths.remove(\".\")\n\n exc_indices = _exclude_str(df[col_name], ignore_paths, method=\"startswith\")\n return df[~exc_indices]\n\n\ndef exclude_root_files(df, col_name=\"path\"):\n inc_indices = _exclude_str(df[col_name], [\"/\"], \"contains\")\n return df[inc_indices]\n\n\ndef exclude_languages(df, ignore_langs=IGNORE_LANGS):\n exc_indices = _exclude_str(df[\"language\"], ignore_langs, method=\"match\")\n\n return df[~exc_indices]\n\n\ndef exclude_file_types(df, ignore_exts=IGNORE_EXTS, col_name=\"path\"):\n ignore_exts = [f\".{ext}\" for ext in ignore_exts]\n exc_indices = _exclude_str(df[col_name], ignore_exts, \"endswith\")\n\n return df[~exc_indices]\n\n\ndef include_only_paths(df, include_paths, col_name=\"path\"):\n for path in include_paths:\n inc_indices = _exclude_str(df[col_name], include_paths, method=\"startswith\")\n\n return df[inc_indices]\n\n\ndef _exclude_str(df_col, ignores, method):\n exc_indices = np.array([False] * df_col.size)\n\n for ignore in ignores:\n fnc = getattr(df_col.str, method)\n exc_indices = np.logical_or(exc_indices, fnc(ignore))\n\n return exc_indices\n\n\ndef create_html_report(project_name, charts_json, filename=\"codemetrics_report.html\"):\n \"\"\"\n Args:\n charts_json (dict): JSON data.\n Must contain: 'loc', 'age', 'loc_age', 'hotspots'.\n \"\"\"\n\n # read template\n template_filename = os.path.join(\n os.path.dirname(os.path.abspath(__file__)), \"codemetrics_template.html\"\n )\n with open(template_filename, \"r\") as file:\n template = file.read()\n\n # add json data\n html = template\n for plot_name, chart_data in charts_json.items():\n search_str = r\"\\{\\{\" + plot_name + r\"\\}\\}\"\n html = re.sub(search_str, json.dumps(chart_data), html)\n\n # add project name\n html = re.sub(r\"\\{\\{project_name\\}\\}\", project_name, html)\n\n # create html file\n with open(filename, \"w\") as file:\n file.write(html)\n\n\ndef create_html_report_from_files(\n project_name, charts_dir, filename=\"codemetrics_report.html\"\n):\n\n # read json\n charts_json = {}\n for plot_name in [\"loc\", \"age\", \"loc_age\", \"hotspots\"]:\n chart_filename = os.path.join(charts_dir, plot_name)\n\n with open(f\"{chart_filename}.json\", \"r\") as file:\n charts_json[plot_name] = json.load(file)\n\n return create_html_report(project_name, charts_json, filename=filename)\n\n\ndef altair2json(chart):\n return json.loads(chart.to_json())\n","repo_name":"luisfpereira/pyutils","sub_path":"src/pyutils/codemetrics.py","file_name":"codemetrics.py","file_ext":"py","file_size_in_byte":5243,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"15"} +{"seq_id":"19214532824","text":"import torch\nfrom torch.nn import BatchNorm2d\nfrom torch.autograd import Variable\nfrom model.tiramisu import Tiramisu\nimport numpy\nimport cv2\nfrom matplotlib import pyplot\nfrom collections import OrderedDict\nfrom generator.lapis import LAPIS\nfrom torch.utils.data import DataLoader\nfrom torchvision.utils import make_grid\n\ndef from_classes_to_color(batch_array):\n \"\"\"\n\n :param batch_array: array di dimensione BxCxWxH \n :return: \n \"\"\"\n\n batch_array = torch.squeeze(batch_array, 1).numpy()\n # LABEL COLOR\n label_c = numpy.zeros((len(batch_array), 224, 224, 3))\n for index_color, (name, color) in enumerate(colors.items()):\n # devo metterlo in scala\n color = numpy.array(color[0:3]) * 255\n\n color = color.astype(\"int32\")\n\n # devo mettere in channel last\n\n # trovo maschera\n mask = batch_array == index_color\n label_c[mask] = color\n # mi serve sapere il numero di elementi a True\n # out_c[mask] = numpy.repeat(color,numpy.sum(mask[:,0]))\n label_c = numpy.transpose(label_c, (0, 3, 1, 2))\n return label_c\n\n\nLABELS = OrderedDict([\n (\"bolt\", (1.0, 0.0, 0.0, 1)),\n (\"cup\", (1.0, 0.501960754395, 0.501960754395, 1)),\n (\"hex\", (1.0, 0.433333396912, 0.0, 1)),\n (\"mouse\", (1.0, 0.717777848244, 0.501960754395, 1)),\n (\"pen\", (1.0, 0.866666734219, 0.0, 1)),\n (\"remote\", (1.0, 0.933594822884, 0.501960754395, 1)),\n (\"scrissor\", (0.699999928474, 1.0, 0.0, 1)),\n (\"washer\", (0.850588202477, 1.0, 0.501960754395, 1)),\n (\"bottle\", (0.266666531563, 1.0, 0.0, 1)),\n (\"fork\", (0.634771168232, 1.0, 0.501960754395, 1)),\n (\"keys\", (0.0, 1.0, 0.16666674614, 1)),\n (\"nails\", (0.501960754395, 1.0, 0.584967374802, 1)),\n (\"plate\", (0.0, 1.0, 0.600000143051, 1)),\n (\"screw\", (0.501960754395, 1.0, 0.800784349442, 1)),\n (\"spoon\", (0.0, 0.966666460037, 1.0, 1)),\n (\"wrench\", (0.501960754395, 0.983398616314, 1.0, 1)),\n (\"cellphone\", (0.0, 0.533333063126, 1.0, 1)),\n (\"hammer\", (0.501960754395, 0.767581582069, 1.0, 1)),\n (\"knife\", (0.0, 0.0999999046326, 1.0, 1)),\n (\"nut\", (0.501960754395, 0.551764667034, 1.0, 1)),\n (\"pliers\", (0.333333492279, 0.0, 1.0, 1)),\n (\"screwdriver\", (0.667973935604, 0.501960754395, 1.0, 1)),\n (\"tootbrush\", (0.766666889191, 0.0, 1.0, 1)),\n])\n\nLABELS_BACK = OrderedDict([\n (\"back\", (0, 0, 0, 1)),\n (\"table\", (1, 1, 1, 1))\n])\n\nWEIGHTS = OrderedDict([\n (\"back\", 0.2),\n (\"table\", 0.002),\n (\"bolt\", 0.1),\n (\"cup\", 0.05),\n (\"hex\", 0.1),\n (\"mouse\", 0.05),\n (\"pen\", 0.1),\n (\"remote\", 0.025),\n (\"scrissor\", 0.025),\n (\"washer\", 0.05),\n (\"bottle\", 0.025),\n (\"fork\", 0.025),\n (\"keys\", 0.05),\n (\"nails\", 0.025),\n (\"plate\", 0.025),\n (\"screw\", 0.05),\n (\"spoon\", 0.025),\n (\"wrench\", 0.025),\n (\"cellphone\", 0.025),\n (\"hammer\", 0.025),\n (\"knife\", 0.025),\n (\"nut\", 0.1),\n (\"pliers\", 0.025),\n (\"screwdriver\", 0.025),\n (\"tootbrush\", 0.025),\n\n])\n\n\ncolors = [(key, val) for key, val in LABELS_BACK.items()]\ncolors.extend([(key, val) for key, val in LABELS.items()])\n\ncolors = OrderedDict(colors)\n\n\nmodel = Tiramisu(in_features=3,num_classes=25,layers=(4,5,7,10),bottleneck=15,compress=False).cuda()\nmodel.load_state_dict(torch.load(\"models/Nov02_17-57-47_lapis-ml/Nov03_03-52-09_0.0505296368858_\"))\nmodel.eval()\n#batch_norm fa andare tutto a merda\n[i.train() for i in model.modules() if isinstance(i,BatchNorm2d)]\nLIVE = False\nif LIVE:\n cam = cv2.VideoCapture(0)\n while True:\n ret_val, img = cam.read()\n img = cv2.bilateralFilter(img,d=3,sigmaColor=1,sigmaSpace=1)\n\n cv2.imshow('my webcam_original', numpy.copy(img))\n img = cv2.cvtColor(img, cv2.COLOR_BGR2RGB)\n\n img = cv2.resize(img, (224, 224))\n img = img.astype(\"float32\") / 255.0\n img = numpy.transpose(img, (2, 0, 1))\n\n data = Variable(torch.FloatTensor(img[numpy.newaxis, ...]).cuda(), volatile=True)\n out = model(data)\n _, out = torch.max(out, 1)\n\n out = numpy.squeeze(from_classes_to_color(out.data.cpu()))\n out = numpy.transpose(out, (1, 2, 0))\n\n cv2.imshow('my webcam', out.astype(\"uint8\"))\n if cv2.waitKey(1) == 27:\n break # esc to quit\n cv2.destroyAllWindows()\nelse:\n dataset = LAPIS(\"/home/lapis/Desktop/LAPIS-dataset/data/test_1/data/\", \"/home/lapis/Desktop/LAPIS-dataset/data/test_1/labels/\",data_aug=False,reshape=True)\n loader_test_reshape = DataLoader(dataset,batch_size=3,shuffle=False)\n\n label_test_color = []\n out_test_color = []\n in_test_color = []\n for k, (data_batch, labels_batch) in enumerate(loader_test_reshape):\n #\n data_batch = Variable(data_batch, requires_grad=False, volatile=True).float().cuda()\n # calcolo uscita\n out = model(data_batch)\n _, out = torch.max(out, 1)\n # LOG tensorboard\n out_test_color.append(from_classes_to_color(out.data.cpu()))\n break\n\n grid = make_grid(torch.FloatTensor(numpy.concatenate(out_test_color)), nrow=5)\n img = grid.numpy().astype(\"uint8\")\n img = numpy.transpose(img,(1,2,0))\n pyplot.imshow(img)\n pyplot.show()\n\n\n\n\n\n","repo_name":"lucabergamini/torch_snippets","sub_path":"test_tiramisu_lapis.py","file_name":"test_tiramisu_lapis.py","file_ext":"py","file_size_in_byte":5158,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"15"} +{"seq_id":"9021426110","text":"def make_sweeper():\n for r in range(size):\n for c in range(size):\n if matrix[r][c] == \"-\":\n current_sum = 0\n for direction in directions:\n if 0 <= r + direction[0] < size and 0 <= c + direction[1] < size:\n if matrix[r + direction[0]][c + direction[1]] == \"*\":\n current_sum += 1\n matrix[r][c] = str(current_sum)\n\n\nsize = int(input())\nbombs = int(input())\nmatrix = []\n\ndirections = {\n (-1, 0),\n (1, 0),\n (0, -1),\n (0, 1),\n (-1, -1),\n (-1, 1),\n (1, -1),\n (1, 1),\n\n}\nfor row in range(size):\n current_row = []\n for col in range(size):\n current_row.append('-')\n matrix.append(current_row)\n\nfor _ in range(bombs):\n r, c = map(int, input().strip('(').strip(\")\").split(\", \"))\n if 0 <= r < size and 0 <= c < size:\n matrix[r][c] = \"*\"\n\nmake_sweeper()\n\nfor row in matrix:\n print(\" \".join(row))\n","repo_name":"DelchevV/Software-University","sub_path":"Python/Advanced/Exam Preparation/19 August 2020/minesweeper_generator.py","file_name":"minesweeper_generator.py","file_ext":"py","file_size_in_byte":973,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"15"} +{"seq_id":"11595723929","text":"#-*- coding: utf-8 -*-\nimport maya.cmds as rig\nimport maya.mel as MEL\nfrom RIG.selectJoint import SK_selectSkinJnt\nfrom RIG.commonly.bodyTemplate import SK_BodyJointPosition\nfrom RIG.commonly.restoreJoint import *\nfrom RIG.fingerPose import *\nfrom RIG.commonly.base import *\nfrom RIG.combine import SK_combinationFinal\nfrom RIG.commonly.mirrorCurve import SK_MirrorCurveControlCmd\nfrom RIG.commonly.resetControllerDefaultPose import SK_creatConDefaultPos\nfrom RIG.commonly.addFingerJoint import SK_createFingers \nfrom RIG.IKFK import SK_IKFKSwitchCommand\nfrom RIG.tools.skeletoneToController import buildSKTOCON\nfrom RIG.tools.deformerConvert import softModToCluster\nfrom RIG.tools.base import *\nfrom RIG.selectProject import SK_SelectProject\n\nclass SK_IDMTRigUI(object):\n def __init__(self):\n self.displayUI()\n \n def displayUI(self):\n IDMTRigGUI='autoRigging'\n if rig.window(IDMTRigGUI,exists=True):\n rig.deleteUI(IDMTRigGUI)\n rig.window(IDMTRigGUI,title='IDMT 2009 AutoRig',menuBar=True,wh= (400,500),minimizeButton=True,maximizeButton=True)\n \n #===============================================================================\n # 开始菜单\n #===============================================================================\n rig.menu( label='File',tearOff=True )\n rig.menuItem( label='New')\n rig.menuItem( label='Open')\n rig.menuItem( label='Save')\n rig.menuItem( divider=True)\n rig.menuItem( label='Quit')\n rig.menu(label='Help',helpMenu=True)\n rig.menuItem( 'Application...\"',label= u'帮助文档',c='from RIG.Help.helpUI import *;SK_helptUI()' )\n \n self.tabs = rig.tabLayout(innerMarginWidth=5,innerMarginHeight=5)\n #===============================================================================\n # 开始\"AutoRiggingLayout\" \n #===============================================================================\n self.AutoRiggingLayout = rig.columnLayout(w =100,h=600,columnAlign='center')\n \n \n rig.button(label = u' 导入模版 ',w=322 , c='SK_BodyJointPosition()')\n rig.separator(w = 322,h=15,style='in')\n rig.setParent(self.AutoRiggingLayout)\n \n rig.intSliderGrp('fingerNumsField',field=True, label=u'手指个数:',minValue=0, maxValue=5, fieldMinValue=0, fieldMaxValue=100, value=5,columnAttach=[(1,'left',0),(2,'left',0),(3,'both',0)],columnWidth3 = (55,50,222))\n rig.intSliderGrp('toesNumsField', field=True, label=u'脚趾个数:',minValue=0, maxValue=5, fieldMinValue=0, fieldMaxValue=100, value=5,columnAttach=[(1,'left',0),(2,'left',0),(3,'both',0)],columnWidth3 = (55,50,222))\n rig.intSliderGrp('neckSegsField', field=True, label=u'脖子段数:',minValue=2, maxValue=5, fieldMinValue=2, fieldMaxValue=100, value=2,columnAttach=[(1,'left',0),(2,'left',0),(3,'both',0)],columnWidth3 = (55,50,222))\n rig.intSliderGrp('waistSegsField', field=True, label=u'腰部段数:',minValue=3, maxValue=10, fieldMinValue=4, fieldMaxValue=100, value=0,columnAttach=[(1,'left',0),(2,'left',0),(3,'both',0)],columnWidth3 = (55,50,222))\n rig.setParent(self.AutoRiggingLayout)\n \n rig.separator(w = 322,h=15,style='in')\n \n rig.rowColumnLayout(numberOfColumns = 2,columnWidth=[(1, 161), (2, 161)],columnAttach=(2,'both',0) )\n rig.button(label=u' 刷新模版 ',w = 130,c='SK_refreshTemp()')\n rig.button(label=u' 镜像骨骼 ',w=130,c='orientAndMirrorJoint ()')\n rig.setParent(self.AutoRiggingLayout)\n \n rig.separator(w = 322,h=15,style='in')\n \n rig.text(l = u'选择项目')#选择项目\n rig.radioCollection()\n rig.rowColumnLayout(nc = 4,columnWidth = [(1,85),(2,85),(3,85),(4,85)])\n self.OrigenRB = rig.radioButton( label= u'初始版本',sl = 1)\n self.WoodliesRB = rig.radioButton( label='Woodlies' )\n self.motionBuilder = rig.radioButton( label='MotionBuilder')\n self.WinxTVRB = rig.radioButton( label='WinxTV',vis = False)\n rig.setParent(self.AutoRiggingLayout)\n \n rig.button(label=u' 生成身体设置 ',w = 322,h = 40, c = lambda x:self.buildSetup())\n \n rig.separator(w = 322,h=15,style='in')\n \n rig.columnLayout('MeshListLayout')\n rig.textScrollList('meshList',w=322,h=100,allowMultiSelection=True,deleteKeyCommand='SK_delMeshList() ')\n rig.setParent(self.AutoRiggingLayout)\n \n rig.separator(w = 322,h=15,style='in')\n \n rig.rowColumnLayout(numberOfColumns = 2,columnWidth=[(1, 161), (2, 161)],columnAttach=(2,'both',0) )\n rig.button(label= u' 添加绑定模型 ',w = 130,c='SK_addMeshList()')\n rig.button(label= u' 对绑定模型蒙皮 ',w=130,c='SK_rigSkin()')\n rig.setParent(self.AutoRiggingLayout)\n \n rig.separator(w = 322,h=15,style='in')\n rig.button(l= u'IK<-->FK',w=322,h=40,c = 'SK_IKFKSwitchCommand()')\n \n rig.separator(w = 322,h=15,style='in')\n rig.button(l= u'恢复初始POSE',w=322,h=40,c = 'SK_creatConDefaultPos(0)')\n \n rig.setParent( self.tabs )\n #===============================================================================\n # 开始\"assemblageLayout\" \n #===============================================================================\n self.assemblageLayout = rig.columnLayout(w =300,h=355)\n \n rig.text(u'1:->选择你要复制的部件2:->在下面的输入复制的数量\\n3:->完成复制4:->完成镜像')\n rig.rowColumnLayout('skinningLayout',numberOfColumns = 3,columnWidth=[(1, 109), (2, 109),(3,109)],columnAttach=(2,'both',0) )\n rig.intField('numOfduplicate' , min = 1 , max = 100 , value=1 ,step=1 )\n rig.button(label= u' 完成复制 ', c = 'SK_duplicateJnt()')\n rig.button(label= u' 完成镜像 ',c='SK_mirrorDupJoint ()')\n rig.setParent('..')\n rig.separator(w = 332,h=15,style='in')\n \n rig.setParent(self.tabs)\n #===============================================================================\n # 开始\"RiggingToolsLayout\" \n #===============================================================================\n self.RiggingToolsLayout = rig.columnLayout(w =300,h=355)\n \n #------------------------------------------------------------------------------ \n modelFL = rig.frameLayout(w=327,label= u\"模型工具\", borderStyle='in' ,cll=True ,cl=True)\n rig.frameLayout(modelFL,edit=True,expandCommand=\"rig.frameLayout(\\\"\"+modelFL+\"\\\" ,edit=True,h=200)\")\n rig.frameLayout(modelFL,edit=True,collapseCommand=\"rig.frameLayout(\\\"\"+modelFL+\"\\\" ,edit=True,h=20)\")\n rig.columnLayout()\n \n rig.separator(w = 312,h=5,style='in')\n rig.button(label = u' 打开模型工具窗口 ' ,w=312 ,c = 'from RIG.tools.modelTools.modelUI import *; SK_modelUI()')\n \n rig.setParent(self.RiggingToolsLayout) \n #------------------------------------------------------------------------------ \n simulationFL = rig.frameLayout(w=327,label= u\"解算设置工具\", borderStyle='in' ,cll=True ,cl=True)\n rig.frameLayout(simulationFL,edit=True,expandCommand=\"rig.frameLayout(\\\"\"+simulationFL+\"\\\" ,edit=True,h=200)\")\n rig.frameLayout(simulationFL,edit=True,collapseCommand=\"rig.frameLayout(\\\"\"+simulationFL+\"\\\" ,edit=True,h=20)\")\n rig.columnLayout()\n \n rig.separator(w = 312,h=5,style='in')\n rig.text(u'增加布料设置')\n rig.button(label = u' 打开布料设置窗口 ' ,w=312 ,c = 'from RIG.simulation.simulationUI import *; SK_simulationUI()')\n \n rig.separator(w = 312,h=5,style='in')\n rig.text(u'增加动力学IK设置')\n rig.button(label = u' 打开动力学IK设置设置窗口 ' ,w=312 ,c = 'from RIG.tools.dynamicCurve.DC_dynamicCurveUI import *; SK_dynamicIKUI()')\n \n rig.setParent(self.RiggingToolsLayout)\n #------------------------------------------------------------------------------ \n fingerFL = rig.frameLayout(w=327,label= u\"手指工具\", borderStyle='in' ,cll=True ,cl=True)\n rig.frameLayout(fingerFL,edit=True,expandCommand=\"rig.frameLayout(\\\"\"+fingerFL+\"\\\" ,edit=True,h=200)\")\n rig.frameLayout(fingerFL,edit=True,collapseCommand=\"rig.frameLayout(\\\"\"+fingerFL+\"\\\" ,edit=True,h=20)\")\n rig.scrollLayout()\n fingerMoLayout = rig.columnLayout()\n \n rig.separator(w = 312,h=5,style='in')\n rig.text(u' 增加手指工具')\n rig.button(label = u' 打开窗口 ' ,w=312 ,c = 'SK_fingerAnimUI()')\n rig.setParent(self.RiggingToolsLayout)\n #------------------------------------------------------------------------------ \n resetFL = rig.frameLayout(w=327,label= u\"恢复工具\", borderStyle='in' ,cll=True ,cl=True)\n rig.frameLayout(resetFL,edit=True,expandCommand=\"rig.frameLayout(\\\"\"+resetFL+\"\\\" ,edit=True,h=200)\")\n rig.frameLayout(resetFL,edit=True,collapseCommand=\"rig.frameLayout(\\\"\"+resetFL+\"\\\" ,edit=True,h=20)\")\n rig.scrollLayout()\n resetMoLayout = rig.columnLayout()\n \n rig.text(u\"重新恢复到模版文件\")\n rig.button( label = u' 恢复 ' ,w=312 ,c = 'SK_restoreJoint(True)')\n rig.setParent(self.RiggingToolsLayout)\n #------------------------------------------------------------------------------ \n curveFL = rig.frameLayout(w=327,label= u\"曲线工具\", borderStyle='in' ,cll=True ,cl=True)\n rig.frameLayout(curveFL,edit=True,expandCommand=\"rig.frameLayout(\\\"\"+curveFL+\"\\\" ,edit=True,h=200)\")\n rig.frameLayout(curveFL,edit=True,collapseCommand=\"rig.frameLayout(\\\"\"+curveFL+\"\\\" ,edit=True,h=20)\")\n curveMoScr = rig.scrollLayout()\n rig.columnLayout()\n \n rig.text(u\" 导入-导出控制器形状 \")\n rig.button(label = u' 打开窗口' ,w=312 ,c = 'from RIG.tools.importExputCurveShape import *\\nSK_ImportExportUI().displayUI()')\n rig.separator(w = 312,h=15,style='in')\n \n rig.text(u\"镜像控制器形状\")\n rig.rowColumnLayout('curveMirrorLayout' , numberOfColumns=2,columnWidth = [(1,156),(2,156)],columnAttach = (2,'both',0))\n rig.button(l= u'左 ——>右',c='SK_MirrorCurveControlCmd(1)')\n rig.button(l= u'右 ——>左',c='SK_MirrorCurveControlCmd(0)')\n rig.separator(w = 312,h=15,style='in')\n rig.setParent( '..' )\n \n rig.text(u\" 增加控制器到bodySet \")\n rig.button(label = u' 增加' ,w=312 ,c = 'from RIG.tools.addSet import *\\nSK_AddToSet(\"bodySet\",rig.ls(sl = True),True)')\n rig.separator(w = 312,h=15,style='in')\n rig.setParent(self.RiggingToolsLayout) \n #------------------------------------------------------------------------------ \n extraFL = rig.frameLayout('extraFrame',w=327,label= u\"附加工具\", borderStyle='in' ,cll=True ,cl=True)\n rig.frameLayout(extraFL,edit=True,expandCommand=\"rig.frameLayout(\\\"\"+extraFL+\"\\\" ,edit=True,h=300)\")\n rig.frameLayout(extraFL,edit=True,collapseCommand=\"rig.frameLayout(\\\"\"+extraFL+\"\\\" ,edit=True,h=20)\")\n rig.columnLayout()\n \n # 选择骨骼增加控制器\n rig.text(u'为选择的骨骼添加控制器:')\n rig.button(label = u'确定' ,w=312 ,c = 'buildSKTOCON()')\n rig.separator(w = 312,h=15,style='in')\n \n # 将软选择变形器转为CLUSTER\n rig.text(u'将softMod转为cluster:')\n rig.button(label = u'确定' ,w=312 ,c = 'softModToCluster()')\n rig.separator(w = 312,h=15,style='in')\n \n rig.text(u'重设簇的形节点位置:')\n rig.button(label = u'确定' ,w=312 ,c = 'resetClusterPos()')\n rig.separator(w = 312,h=15,style='in')\n\n rig.text(u'关闭场景中局部旋转轴向显示:')\n rig.button(label = u'确定' ,w=312 ,c = 'TL_CloseDisplayLocalAxis()')\n rig.separator(w = 312,h=15,style='in')\n \n rig.text(u'创建线性IK:')\n rig.button(label = u'打开窗口' ,w=312 ,c = 'from RIG.tools.IKsplineTool.ikSpline import * \\nIKSplineUI()')\n rig.setParent(self.RiggingToolsLayout)\n #------------------------------------------------------------------------------ \n skinFL = rig.frameLayout('skinTools',w=327,label= u\"权重工具\", borderStyle='in' ,cll=True ,cl=True)\n rig.frameLayout(skinFL,edit=True,expandCommand=\"rig.frameLayout(\\\"\"+skinFL+\"\\\" ,edit=True,h=200)\")\n rig.frameLayout(skinFL,edit=True,collapseCommand=\"rig.frameLayout(\\\"\"+skinFL+\"\\\" ,edit=True,h=20)\")\n rig.columnLayout()\n \n rig.separator(w = 312,h=5,style='in')\n rig.text(u' 将一个物体的权重拷给多个物体')\n rig.button(label = u' 确定 ' ,w = 312 ,c = 'from RIG.tools.copyWeigths import *\\nSK_copyWeightToOtherObj()')\n \n rig.separator(w = 312,h=5,style='in')\n rig.text(u'检测是否有影响物体重叠')\n rig.button(label = u' 确定 ' ,w = 312 ,c = 'from RIG.tools.detectInfluence import *\\ndetectInfluenceObj()')\n \n rig.separator(w = 312,h=5,style='in')\n rig.text(u'导入导出权重')\n rig.button(label = u' 打开工具窗口 ' ,w = 312 ,c = 'from RIG.tools.IOWeights.IOWeightsUI import *\\nSK_IOWeightsUI()')\n \n rig.setParent(self.RiggingToolsLayout)\n rig.setParent(self.tabs)\n #===============================================================================\n # 开始\"faceRiggingLayout\" \n #===============================================================================\n self.faceRiggingLayout = rig.columnLayout(w =300,h=355)\n \n rig.button(l= u'打开面部设置窗口',c='from RIG.face.faceUI import *\\nOpenFaceUI()',w = 325)\n \n rig.separator(w = 325,h=5,style='in')\n rig.button(l= u'打开最新面部设置窗口',c='import RIG.WDface.WD_FaceUI as face;face.WD_SelectUI()',w = 325)\n\n rig.separator(w = 325,h=5,style='in')\n rig.text(u' 增加下颚设置')\n rig.rowColumnLayout(numberOfColumns=2,columnWidth = [(1,162),(2,162)])\n rig.button(label = u' 确定 ' ,c = 'from RIG.tools.AddJawSetup import *\\nSK_AddJawSetup()')\n rig.button(l= u'移除设置',c = 'from RIG.tools.AddJawSetup import *\\nSK_removeJawSetup()')\n rig.setParent('..')\n \n rig.separator(w = 325,h=5,style='in')\n rig.text(u' 增加眼睛设置') \n rig.rowColumnLayout(numberOfColumns=3,columnWidth = [(1,108),(2,108),(3,108)],columnAttach = (3,'both',0))\n rig.button(l= u'导入控制器',c= 'from RIG.tools.AddEyeSetup import SK_AddEyeSetup\\nSK_AddEyeSetup(True)')\n rig.button(l= u'完成设置',c= 'from RIG.tools.AddEyeSetup import SK_AddEyeSetup\\nSK_AddEyeSetup(False)')\n rig.button(l= u'移除设置',c= 'from RIG.tools.AddEyeSetup import SK_removeEyeSetup\\nSK_removeEyeSetup()')\n \n rig.setParent(self.tabs )\n rig.tabLayout( self.tabs,edit=True,tabLabel=((self.AutoRiggingLayout,'AutoRigging'), (self.assemblageLayout,'assemblage'), (self.RiggingToolsLayout,'RiggingTools'),(self.faceRiggingLayout,'faceRigging')),\\\n selectTabIndex = self.getOptionVar(),changeCommand = lambda x = 0:self.setOptionVar())\n \n rig.showWindow(IDMTRigGUI) \n rig.window(IDMTRigGUI,e=True,wh=(344,680))\n #-------------------------------------------------------------------------- 界面结束\n \n #===============================================================================\n # 增加OptionVar\n #===============================================================================\n def setOptionVar(self):\n RIG_Tab_Var = 'RIG_Tab_Var'\n selectID = rig.tabLayout(self.tabs,q = True,selectTabIndex = True)\n rig.optionVar(iv = (RIG_Tab_Var,selectID))\n \n def getOptionVar(self):\n RIG_Tab_Var = 'RIG_Tab_Var'\n if rig.optionVar( exists= RIG_Tab_Var):\n getID = rig.optionVar(q = RIG_Tab_Var)\n else:\n getID = 1\n \n return getID\n #------------------------------------------------------------- 结束OptionVar设置\n \n #===========================================================================\n # 生成设置\n #===========================================================================\n def buildSetup(self):\n SK_combinationFinal()\n SK_SelectProject(self.OrigenRB,self.WoodliesRB,self.WinxTVRB,self.MotionBuilder)#选择项目\n\ndef SK_fillTextField():\n name = rig.optionMenuGrp('nameListField',q=True,value=True)\n rig.textField('aTF',e= True , text =name ) \n\n\ndef SK_fingerAnimUI(): \n\n GUI='fingerAnimUI'\n if rig.window(GUI,exists=True):\n rig.deleteUI(GUI)\n rig.window(GUI,title='FingerAnim',menuBar=True,wh=(180,150),minimizeButton=True,maximizeButton=True)\n MCL=rig.columnLayout()\n rig.text('**-- fill in the name--**')\n \n MRL=rig.rowColumnLayout(numberOfColumns = 3 , columnAttach=(1, 'left', 1),columnWidth=[(1, 70),(2, 100),(3, 120)] )\n rig.text(' FingerAnim :')\n rig.textField('aTF',text = 'curl',width=80)\n \n rig.optionMenuGrp('nameListField',label=' default:',columnWidth =[(1,55),(2,150)],changeCommand = 'SK_fillTextField()')\n rig.menuItem( label='curl' )\n rig.menuItem( label='relax' )\n rig.menuItem( label='spread' )\n rig.menuItem( label='scrunch' )\n rig.menuItem( label='cup' )\n rig.menuItem( label='twist' )\n rig.menuItem( label='lean' )\n\n rig.setParent( '..' )\n rig.separator(height =30,w=300)\n \n MBL=rig.rowColumnLayout(numberOfColumns = 3 )\n rig.button('AddButton',label='Add',width=50,command='SK_fingerAdd()')\n rig.button('ResetButton',label='Reset',width=50,command='SK_fingerCopy()')\n rig.button('EditButton',label='Edit',width=50,en = False,command='SK_fingerEdit()')\n \n rig.setParent( '..' ) \n\n rig.text('''------------------------\n hope you enjoy that''')\n \n rig.window(GUI,e=True,wh=(315,165))\n\n rig.showWindow(GUI)\n\n\ndef SK_fillTextField():\n name = rig.optionMenuGrp('nameListField',q=True,value=True)\n rig.textField('aTF',e= True , text =name ) \n\n\ndef SK_loadJoint():\n objs = rig.ls(sl = True)[0]\n if('joint' == rig.nodeType(objs)):\n rig.textFieldButtonGrp('SK_BT_textFieldButtonGrpLoadJnt',e = True,tx = objs)\n rig.textFieldGrp('SK_BT_textFieldGrpJointName',e = True,tx = objs)\n\n \ndef SK_addMeshList():\n listSel = rig.textScrollList('meshList',q= True,allItems=True )\n if (str(type(listSel)) == \"\"):\n listSel = []\n else:\n pass\n meshSel = rig.ls(sl=True)\n\n\n for eachMesh in meshSel:\n if eachMesh in listSel:\n pass\n else:\n rig.textScrollList('meshList',e= True,append=eachMesh )\n \ndef SK_getFilePath():\n getFilePath = __file__\n fixPath = getFilePath.replace('rigUI.pyc','')\n fixPath = fixPath.replace('rigUI.py','')\n getPath = fixPath.replace('\\\\','/')\n return getPath\n\ndef SK_delMeshList():\n listSel = rig.textScrollList('meshList',q= True,selectItem=True )\n for eachListSel in listSel:\n rig.textScrollList('meshList',e= True,removeItem=eachListSel)\n\n\ndef SK_rigSkin():\n jnts = SK_selectSkinJnt()\n rig.select(cl = True)\n skinMeshList = rig.textScrollList('meshList',q=True,allItems=True)\n for eachSelMesh in skinMeshList:\n if rig.listRelatives(eachSelMesh,s = True):\n rig.skinCluster(jnts,eachSelMesh,toSelectedBones=True,maximumInfluences=2,dropoffRate=4,removeUnusedInfluence=False)\n else:\n try:\n skinObjs = [rig.listRelatives(obj,p = True)[0] for obj in rig.listRelatives(eachSelMesh,ad = True,c = True,type = 'shape')]\n if skinObjs:\n for obj in skinObjs:\n rig.skinCluster(jnts,obj,toSelectedBones=True,maximumInfluences=2,dropoffRate=4,removeUnusedInfluence=False)\n \n except:\n pass\n","repo_name":"Bn-com/myProj_octv","sub_path":"OLD/COMMON/set/RIG/rigUI.py","file_name":"rigUI.py","file_ext":"py","file_size_in_byte":20247,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"15"} +{"seq_id":"73283831690","text":"import sqlite3\nfrom sqlite3 import Error\n\ndef create_connection(db_file):\n \"\"\" create a database connection to the SQLite database specified by db_file\n :param db_file: database file\n :return Connection object or None\"\"\"\n\n try:\n conn = sqlite3.connect(db_file)\n return conn\n except Error as e:\n print(e)\n\n return None\n\n\ndef select_all_data(conn, select_sql):\n \"\"\"\n Execute the select_sql statement to get all rows from database\n :param conn: the Connection object\n :param select_sql: the SELECT statement\n :return:\n \"\"\"\n cur = conn.cursor()\n cur.execute(select_sql)\n\n rows = cur.fetchall()\n\n for row in rows:\n print(row)\n\n\ndef main():\n database = \"C:\\\\Users\\\\user\\\\Desktop\\\\Bella\\\\sqlite\\\\db\\\\chinook.db\"\n\n select_all_customers = \"SELECT * FROM customers\"\n\n # create a database connection\n conn = create_connection(database)\n\n with conn:\n print(\"Query all customers\")\n select_all_data(conn, select_all_customers)\n\n\nif __name__ == '__main__':\n main()","repo_name":"bellabellahuang/YSC2018","sub_path":"practice/sqlite3_select_data.py","file_name":"sqlite3_select_data.py","file_ext":"py","file_size_in_byte":1057,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"15"} +{"seq_id":"37926517241","text":"import os\n\nfrom django.conf import settings\n\nROOT_DIR = os.path.join(os.path.dirname(settings.BASE_DIR), 'nlp-libs')\nDOWNLOAD_DIR = os.path.join(ROOT_DIR, 'polyglot_data')\n\n# To filter scrapping results with relevant content using following words and their nearest [k] neighbors\nFILTER_LIST_WORDS = ['jobs', 'employee', 'freelance', 'employment', 'fulltime', 'work', 'parttime', 'placement', 'gig',\n 'incumbency', 'occupation', 'opportunity', 'work', 'development']\n\nNEAREST_NEIGHBORS = 10 # [k]\n\nFILTER_WORD_FILE_PATH = os.path.join(settings.BASE_DIR, 'scrappers_miners', 'utils', 'FilterList.txt')\n\nACCEPTABLE_KEYWORDS_TYPE = ('NOUN', 'PROPN', 'NUM') # Noun, Proper noun, Number\n","repo_name":"lagosito/jobi","sub_path":"scrappers_miners/utils/settings.py","file_name":"settings.py","file_ext":"py","file_size_in_byte":703,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"15"} +{"seq_id":"72981218892","text":"#!/usr/bin/env python3\n# -*- coding: utf-8 -*-\n\"\"\"\nCreated on Thu Dec 3 17:23:48 2020\n\n@author: vishnumaganti\n\"\"\"\n\nfrom sklearn.feature_extraction.text import CountVectorizer\nfrom sklearn.decomposition import LatentDirichletAllocation\nimport nltk\nimport csv\nimport re\nwith open('/Users/vishnumaganti/Documents/text _analysis_project/project_texts_articles..txt', newline='') as f:\n reader = csv.reader(f)\n data = list(reader)\n \ndata = [str(x) for x in data]\n\n#pre processing \n#1.Expand contractions \n\n\nCONTRACTION_MAP = {\n\"'cause\": \"because\",\n\"'til\": \"until\",\n\"ain't\": \"is not\",\n\"aren't\": \"are not\",\n\"can't\": \"cannot\",\n\"can't've\": \"cannot have\",\n\"could've\": \"could have\",\n\"couldn't\": \"could not\",\n\"couldn't've\": \"could not have\",\n\"didn't\": \"did not\",\n\"doesn't\": \"does not\",\n\"don't\": \"do not\",\n\"hadn't\": \"had not\",\n\"hadn't've\": \"had not have\",\n\"hasn't\": \"has not\",\n\"haven't\": \"have not\",\n\"he'd\": \"he would\",\n\"he'd've\": \"he would have\",\n\"he'll\": \"he will\",\n\"he'll've\": \"he he will have\",\n\"he's\": \"he is\",\n\"how'd\": \"how did\",\n\"how'd'y\": \"how do you\",\n\"how'll\": \"how will\",\n\"how's\": \"how is\",\n\"I'd\": \"I would\",\n\"I'd've\": \"I would have\",\n\"I'll\": \"I will\",\n\"I'll've\": \"I will have\",\n\"I'm\": \"I am\",\n\"I've\": \"I have\",\n\"i'd\": \"i would\",\n\"i'd've\": \"i would have\",\n\"i'll\": \"i will\",\n\"i'll've\": \"i will have\",\n\"i'm\": \"i am\",\n\"i've\": \"i have\",\n\"isn't\": \"is not\",\n\"it'd\": \"it would\",\n\"it'd've\": \"it would have\",\n\"it'll\": \"it will\",\n\"it'll've\": \"it will have\",\n\"it's\": \"it is\",\n\"let's\": \"let us\",\n\"ma'am\": \"madam\",\n\"mayn't\": \"may not\",\n\"might've\": \"might have\",\n\"mightn't\": \"might not\",\n\"mightn't've\": \"might not have\",\n\"must've\": \"must have\",\n\"mustn't\": \"must not\",\n\"mustn't've\": \"must not have\",\n\"needn't\": \"need not\",\n\"needn't've\": \"need not have\",\n\"o'clock\": \"of the clock\",\n\"oughtn't\": \"ought not\",\n\"oughtn't've\": \"ought not have\",\n\"shan't\": \"shall not\",\n\"sha'n't\": \"shall not\",\n\"shan't've\": \"shall not have\",\n\"she'd\": \"she would\",\n\"she'd've\": \"she would have\",\n\"she'll\": \"she will\",\n\"she'll've\": \"she will have\",\n\"she's\": \"she is\",\n\"should've\": \"should have\",\n\"shouldn't\": \"should not\",\n\"shouldn't've\": \"should not have\",\n\"so've\": \"so have\",\n\"so's\": \"so as\",\n\"that'd\": \"that would\",\n\"that'd've\": \"that would have\",\n\"that's\": \"that is\",\n\"there'd\": \"there would\",\n\"there'd've\": \"there would have\",\n\"there's\": \"there is\",\n\"they'd\": \"they would\",\n\"they'd've\": \"they would have\",\n\"they'll\": \"they will\",\n\"they'll've\": \"they will have\",\n\"they're\": \"they are\",\n\"they've\": \"they have\",\n\"to've\": \"to have\",\n\"wasn't\": \"was not\",\n\"we'd\": \"we would\",\n\"we'd've\": \"we would have\",\n\"we'll\": \"we will\",\n\"we'll've\": \"we will have\",\n\"we're\": \"we are\",\n\"we've\": \"we have\",\n\"weren't\": \"were not\",\n\"what'll\": \"what will\",\n\"what'll've\": \"what will have\",\n\"what're\": \"what are\",\n\"what's\": \"what is\",\n\"what've\": \"what have\",\n\"when's\": \"when is\",\n\"when've\": \"when have\",\n\"where'd\": \"where did\",\n\"where's\": \"where is\",\n\"where've\": \"where have\",\n\"who'll\": \"who will\",\n\"who'll've\": \"who will have\",\n\"who's\": \"who is\",\n\"who've\": \"who have\",\n\"why's\": \"why is\",\n\"why've\": \"why have\",\n\"will've\": \"will have\",\n\"won't\": \"will not\",\n\"won't've\": \"will not have\",\n\"would've\": \"would have\",\n\"wouldn't\": \"would not\",\n\"wouldn't've\": \"would not have\",\n\"y'all\": \"you all\",\n\"y'all'd\": \"you all would\",\n\"y'all'd've\": \"you all would have\",\n\"y'all're\": \"you all are\",\n\"y'all've\": \"you all have\",\n\"you'd\": \"you would\",\n\"you'd've\": \"you would have\",\n\"you'll\": \"you will\",\n\"you'll've\": \"you will have\",\n\"you're\": \"you are\",\n\"you've\": \"you have\"\n}\n\ndef expand_contractions(text):\n for word in text.split():\n if word.lower() in CONTRACTION_MAP:\n text = text.replace(word, CONTRACTION_MAP[word.lower()])\n return(text)\n\n\ndef remove_special_characters(string):\n # remove any leading or trailing spaces using string.strip method\n string = string.strip()\n \n # create a pattern for anything but alpha-numeric characters ^ = not\n PATTERN = r'[^a-zA-Z0-9 ]'\n filtered_string = re.sub(PATTERN, r'', string)\n return filtered_string\n\nfrom nltk.stem import PorterStemmer \ndef tokenize(text):\n tokens = nltk.word_tokenize(text)\n stemmer=PorterStemmer()\n return [stemmer.stem(token) for token in tokens]\n \n\n\nnew_documents=[]\nnew_documents2=[]\nnew_documents3=[]\n\nfor i in data:\n new_documents.append(expand_contractions(i))\n\nfor i in new_documents:\n new_documents2.append(remove_special_characters(i)) \nfor i in new_documents2:\n new_documents3.append(tokenize(i))\n \npreprocessed = [str(x) for x in new_documents3] \n\nnum_features = 4500\nnum_topics = 5\nnum_top_words=30\n\ntf_vectorizer = CountVectorizer(lowercase='boolean',max_features=num_features ,stop_words='english',min_df=1,max_df=1.0)\ntf=tf_vectorizer.fit_transform(preprocessed)\ntf_feature_names = tf_vectorizer.get_feature_names()\n\n\ndef display_topics(model, feature_names, num_top_words):\n for topic_idx, topic in enumerate(model.components_):\n print(\"Topic %d:\" % (topic_idx))\n print(\" \".join([feature_names[i]\n for i in topic.argsort()[:-num_top_words - 1:-1]]))\n \n \n \nlda = LatentDirichletAllocation(n_components=num_topics, max_iter=20, learning_method='online', learning_offset=50.,random_state=0).fit(tf)\ndisplay_topics(lda, tf_feature_names, num_top_words)\n\n\n","repo_name":"srivishnumaganti/NY-Times-articles-Topic-modelling-NLP-","sub_path":"project code/final report (1).py","file_name":"final report (1).py","file_ext":"py","file_size_in_byte":5344,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"15"} +{"seq_id":"21437947041","text":"#!/usr/bin/env python\n\n\"\"\"\nA Kestrel client library.\n\"\"\"\n\nfrom collections import defaultdict\nimport random\nimport re\nimport threading\n\nimport memcache\n\n\nclass Client(threading.local):\n \"\"\"Kestrel queue client.\"\"\"\n\n def __init__(self, servers):\n \"\"\"Constructor.\n\n :param servers: The list of servers to connect to, really should only\n be one for a kestrel client;\n :type servers: list\n\n \"\"\"\n\n self.__memcache = KestrelMemcacheClient(servers=servers)\n\n def add(self, queue, data, expire=None):\n \"\"\"Add a job onto the queue.\n\n WARNING: You should only send strings through to the queue, if not\n the python-memcached library will serialize these objects and since\n kestrel ignores the flags supplied during a set operation, when the\n object is retrieved from the queue it will not be unserialized.\n\n :param queue: The name of the key to work against\n :type queue: string\n :param data: The job itself\n :type data: mixed\n :param expire: The expiration time of the job, if a job doesn't get\n used in this amount of time, it will silently die away.\n :type expire: int\n :return: True/False\n :rtype: bool\n\n \"\"\"\n\n if not isinstance(data, str):\n raise TypeError('data must be of type string')\n\n if expire is None:\n expire = 0\n\n ret = self.__memcache.set(queue, data, expire)\n\n if ret == 0:\n return False\n\n return True\n\n def get(self, queue, timeout=None):\n \"\"\"Get a job off the queue. (unreliable)\n\n :param queue: The name of the key to work against\n :type queue: string\n :param timeout: The time to wait for a job if none are on the queue\n when the initial request is made. (seconds)\n :type timeout: int\n :return: The job\n :rtype: mixed\n\n \"\"\"\n\n cmd = '%s' % (queue)\n\n if timeout is not None:\n cmd = '%s/t=%d' % (cmd, timeout)\n\n return self.__memcache.get('%s' % (cmd))\n\n def next(self, queue, timeout=None):\n \"\"\"Marks the last job as compelete and gets the next one.\n\n :param queue: The name of the key to work against\n :type queue: string\n :param timeout: The time to wait for a job if none are on the queue\n when the initial request is made. (seconds)\n :type timeout: int\n :return: The job\n :rtype: mixed\n\n \"\"\"\n\n cmd = '%s/close' % (queue)\n\n if timeout is not None:\n cmd = '%s/t=%d' % (cmd, timeout)\n\n return self.__memcache.get('%s/open' % (cmd))\n\n def peek(self, queue, timeout=None):\n \"\"\"Copy a job from the queue, leaving the original in place.\n\n :param queue: The name of the key to work against\n :type queue: string\n :param timeout: The time to wait for a job if none are on the queue\n when the initial request is made. (seconds)\n :type timeout: int\n :return: The job\n :rtype: mixed\n\n \"\"\"\n\n cmd = '%s/peek' % (queue)\n\n if timeout is not None:\n cmd = '%s/t=%d' % (cmd, timeout)\n\n return self.__memcache.get(cmd)\n\n def abort(self, queue):\n \"\"\"Mark a job as incomplete, making it available to another client.\n\n :param queue: The name of the key to work against\n :type queue: string\n :return: True on success\n :rtype: boolean\n\n \"\"\"\n\n self.__memcache.get('%s/abort' % (queue))\n return True\n\n def finish(self, queue):\n \"\"\"Mark the last job read off the queue as complete on the server.\n\n :param queue: The name of the key to work against\n :type queue: string\n :return: True on success\n :rtype: bool\n\n \"\"\"\n\n self.__memcache.get('%s/close' % (queue))\n return True\n\n def delete(self, queue):\n \"\"\"Delete this queue from the kestrel server.\n\n :param queue: The name of the key to work against\n :type queue: string\n :return: True on success, False on error\n :rtype: bool\n\n \"\"\"\n\n ret = self.__memcache.delete(queue)\n\n # REMOVED: 12/1/2011 kestrel currently sends END instead of DELETED in response.\n # so we will ignore the response for now and assume all went correctly to plan\n # what could go wrong?\n #if ret == 0:\n # return False\n\n return True\n\n def close(self):\n \"\"\"Force the client to disconnect from the server.\n\n :return: True\n :rtype: bool\n\n \"\"\"\n\n self.__memcache.disconnect_all()\n return True\n\n def flush(self, queue):\n \"\"\"Clear out (remove all jobs) in the current queue.\n\n :param queue: The name of the key to work against\n :type queue: string\n :return: True\n :rtype: bool\n\n \"\"\"\n\n self.__memcache.flush(queue)\n return True\n\n def flush_all(self):\n \"\"\"Clears out all jobs in all the queues on this kestrel server.\n\n :return: True\n :rtype: bool\n\n \"\"\"\n\n self.__memcache.flush_all()\n return True\n\n def reload(self):\n \"\"\"Forces the kestrel server to reload the config.\n\n :return: True\n :rtype: bool\n\n \"\"\"\n\n self.__memcache.reload()\n return True\n\n def stats(self):\n \"\"\"Get the stats from the server and parse the results into a python\n dict.\n\n {\n '127.0.0.1:22133': {\n 'stats': {\n 'cmd_get': 10,\n ...\n },\n 'queues': {\n 'queue_name': {\n 'age': 30,\n ...\n }\n }\n }\n }\n \"\"\"\n\n server = None\n _sstats = {}\n _qstats = {}\n\n for server, stats in self.raw_stats():\n server = server.split(' ', 1)[0]\n for name, stat in stats.iteritems():\n if not name.startswith('queue_'):\n try:\n _sstats[name] = long(stat)\n except ValueError:\n _sstats[name] = stat\n\n for name, stats in re.findall('queue \\'(?P.*?)\\' \\{(?P.*?)\\}', self.raw_stats(True), re.DOTALL):\n _stats = {}\n for stat in [stat.strip() for stat in stats.split('\\n')]:\n if stat.count('='):\n (key, value) = stat.split('=')\n try:\n _stats[key] = long(value)\n except ValueError:\n _stats[key] = value\n _qstats[name] = _stats\n\n if server is None:\n return None\n\n return (server, dict([('server', _sstats), ('queues', _qstats)]))\n\n def raw_stats(self, pretty=None):\n \"\"\"Get statistics in either the pretty (kestrel) format or the\n standard memcache format.\n\n :param pretty: Set to True to generate the stats in the kestrel/pretty\n format.\n :type pretty: bool\n :return: The stats text blob, or the structed format from the\n underlying memcache library\n :rtype: string\n\n \"\"\"\n\n if pretty is True:\n return self.__memcache.pretty_stats()\n\n return self.__memcache.get_stats()\n\n def shutdown(self):\n \"\"\"Shutdown the kestrel server gracefully.\n\n :return: None\n :rtype: None\n\n \"\"\"\n\n return self.__memcache.shutdown()\n\n def version(self):\n \"\"\"Get the version for the kestrel server.\n\n :return: The kestrel server version. e.g. 1.2.3\n :rtype: string\n\n \"\"\"\n\n return self.__memcache.version()\n\n\nclass KestrelMemcacheClient(memcache.Client):\n \"\"\"Kestrel Memcache Client.\n\n Since kestrel has a few commands that are not part of the memcached\n protocol we add functions to support them.\n\n Specifically: RELOAD, FLUSH, DUMP_STATS, DUMP_CONFIG, SHUTDOWN\n\n Also the memcache.Client doesn't have support for the VERSION command\n so we have added that function as well.\n\n \"\"\"\n\n\n def reload(self):\n for s in self.servers:\n if not s.connect(): continue\n s.send_cmd('RELOAD')\n s.expect('OK')\n\n def flush(self, key):\n for s in self.servers:\n if not s.connect(): continue\n s.send_cmd('FLUSH %s' % (key))\n s.expect('OK')\n\n def pretty_stats(self):\n return self.__read_cmd('DUMP_STATS')\n\n def version(self):\n data = []\n for s in self.servers:\n if not s.connect(): continue\n s.send_cmd('VERSION')\n data.append(s.readline())\n\n return ('\\n').join(data).split(' ', 1)[1]\n\n def shutdown(self):\n for s in self.servers:\n if not s.connect(): continue\n s.send_cmd('SHUTDOWN')\n\n def __read_cmd(self, cmd):\n data = []\n for s in self.servers:\n if not s.connect(): continue\n s.send_cmd(cmd)\n data.append(self.__read_string(s))\n\n return ('\\n').join(data)\n\n def __read_string(self, s):\n data = []\n while True:\n line = s.readline()\n if not line or line.strip() == 'END': break\n data.append(line)\n\n return ('\\n').join(data)\n\n def _get_server(self, key):\n if isinstance(key, tuple):\n serverhash, key = key\n else:\n serverhash = random.randint(0, len(self.buckets))\n\n for i in xrange(memcache.Client._SERVER_RETRIES):\n server = self.buckets[serverhash % len(self.buckets)]\n if server.connect():\n return server, key\n serverhash = random.randint(0, len(self.buckets))\n return None, None\n\n","repo_name":"matterkkila/pykestrel","sub_path":"kestrel/client.py","file_name":"client.py","file_ext":"py","file_size_in_byte":9934,"program_lang":"python","lang":"en","doc_type":"code","stars":19,"dataset":"github-code","pt":"15"} +{"seq_id":"719768881","text":"from django.contrib import admin\nfrom django.contrib.auth.admin import UserAdmin as BaseUserAdmin\nfrom django.utils.translation import gettext as _\n\nfrom core import models\n\n\n# chnage for adding group start /..........\nfrom django import forms\nfrom django.contrib.auth import get_user_model\nfrom django.contrib.admin.widgets import FilteredSelectMultiple \nfrom django.contrib.auth.models import Group\n\n\nUser = get_user_model()\n\n# Create ModelForm based on the Group model.\nclass GroupAdminForm(forms.ModelForm):\n class Meta:\n model = Group\n exclude = []\n\n # Add the users field.\n users = forms.ModelMultipleChoiceField(\n queryset=User.objects.all(), \n required=False,\n # Use the pretty 'filter_horizontal widget'.\n widget=FilteredSelectMultiple('users', False)\n )\n\n def __init__(self, *args, **kwargs):\n # Do the normal form initialisation.\n super(GroupAdminForm, self).__init__(*args, **kwargs)\n # If it is an existing group (saved objects have a pk).\n if self.instance.pk:\n # Populate the users field with the current Group users.\n self.fields['users'].initial = self.instance.user_set.all()\n\n def save_m2m(self):\n # Add the users to the Group.\n self.instance.user_set.set(self.cleaned_data['users'])\n\n def save(self, *args, **kwargs):\n # Default save\n instance = super(GroupAdminForm, self).save()\n # Save many-to-many data\n self.save_m2m()\n return instance\n\n\n# change for adding group model end /..........\n\n\nclass UserAdmin(BaseUserAdmin):\n ordering = ['id']\n list_display = ['email', 'name', 'is_superuser','is_staff', 'is_active', 'is_customer']\n fieldsets = (\n (None, {'fields': ('email', 'password')}),\n (_('Personal Info'), {'fields': ('name',)}),\n (\n _(\"permissions\"),\n {'fields': ('is_active', 'is_staff', 'is_superuser', 'is_customer')}\n ),\n (_('Important dates'), {'fields': ('last_login',)})\n )\n add_fieldsets = (\n (None, {\n 'classes': ('wide',),\n 'fields': ('email', 'password1', 'password2')\n }),\n )\n\n# chnage of the view in the admin page\nclass RecipeAdmin(admin.ModelAdmin):\n list_display =['title', 'user', 'time_minutes', 'price', 'recipe_category']\n list_filter =['recipe_category']\n\n\nclass IngredientAdmin(admin.ModelAdmin):\n list_display =['name', 'user']\n list_filter =['user']\n\nclass RestaurantAdmin(admin.ModelAdmin):\n list_display =['name', 'user', 'location', 'rating', 'restaurant_grade']\n list_filter =['restaurant_grade']\n\n\nclass ReviewRestaurantAdmin(admin.ModelAdmin):\n list_display =['id', 'restaurant', 'recipe', 'user', 'rating', 'created_at']\n list_filter =['restaurant', 'user']\n\n\nclass BookingAdmin(admin.ModelAdmin):\n list_display =['id', 'restaurant', 'user', 'seats_number', 'is_active']\n list_filter =['restaurant', 'user', 'is_active']\n\nclass ConfigDataAdmin(admin.ModelAdmin):\n list_display =['config_name']\n\n\n# Unregister the original Group admin.\nadmin.site.unregister(Group)\n\n# Create a new Group admin.\nclass GroupAdmin(admin.ModelAdmin):\n # Use our custom form.\n form = GroupAdminForm\n # Filter permissions horizontal as well.\n filter_horizontal = ['permissions']\n\n# Register the new Group ModelAdmin.\nadmin.site.register(Group, GroupAdmin)\n\n\nadmin.site.register(models.User, UserAdmin)\nadmin.site.register(models.Tag)\n\n\nadmin.site.register(models.Ingredient, IngredientAdmin)\nadmin.site.register(models.Recipe, RecipeAdmin)\nadmin.site.register(models.Restaurant, RestaurantAdmin)\nadmin.site.register(models.ReviewRestaurant, ReviewRestaurantAdmin)\nadmin.site.register(models.Booking, BookingAdmin)\nadmin.site.register(models.ConfigData, ConfigDataAdmin)\n\n","repo_name":"shravands/django-restapi-recipe","sub_path":"app/core/admin.py","file_name":"admin.py","file_ext":"py","file_size_in_byte":3833,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"15"} +{"seq_id":"26227166639","text":"# Author: Hidir Sezgin, Mehmet A. Kir\n# Email : hidirsezgin@gmail.com, m.kir@student.unsw.edu.au\n# GitHub: /hidirsezgin, /mehmetalikir\n\n'''(Racing car) Write a program that simulates car racing, as shown in Figure\n11.17b–d. The car moves from left to right. When it reaches the right end, it restarts\nfrom the left and continues the same process. Let the user increase and decrease\nthe car’s speed by pressing the Up and Down arrow keys.'''\n\nfrom tkinter import * # Import tkinter\n\n\nclass RacingCar:\n def __init__(self):\n window = Tk() # Create a window\n window.title(\"Racing Car\") # Set a title\n self.width = 250 # Width of the self.canvas\n self.canvas = Canvas(window, bg=\"white\", width=200, height=200)\n self.canvas.pack()\n\n # Bind with event\n self.canvas.bind(\"\", self.processKeyEvent)\n self.canvas.focus_set()\n\n self.sleepTime = 100 # Set a sleep time\n self.x, self.y = 0, 110 # Starting x position\n\n # TO-DO -> Draw car object\n self.canvas.create_polygon(self.x + 10.0, self.y - 20.0, self.x + 20.0, self.y - 30.0, self.x + 30.0,\n self.y - 30.0, self.x + 40.0, self.y - 20.0, tags=\"car\")\n\n self.dx = 3\n self.isStopped = False\n self.animate()\n\n window.mainloop() # Create an event loop\n\n def processKeyEvent(self, event):\n if event.keysym == \"Up\": # Speed up the animation\n self.sleepTime -= 10\n if event.keysym == \"Down\":\n self.sleepTime += 10 # Slow down the animation\n\n def animate(self): # Move the message\n while not self.isStopped:\n self.canvas.move(\"car\", self.dx, 0) # Move text\n self.canvas.after(self.sleepTime) # Sleep\n self.canvas.update() # Update self.canvas\n if self.x < self.width:\n self.x += self.dx # Set new position\n else:\n self.x = 0 # Reset car position to the beginning\n self.canvas.delete(\"car\")\n # Redraw text at the beginning\n self.canvas.create_polygon(self.x + 10.0, self.y - 20.0, self.x + 20.0, self.y - 30.0, self.x + 30.0,\n self.y - 30.0, self.x + 40.0, self.y - 20.0, tags=\"car\")\n\n\nRacingCar() # Create GUI\n","repo_name":"mehmetalikir/Introduction-to-Python-Programming-and-Data-Structures-3rd-edition","sub_path":"chapter11/Exercise11_07.py","file_name":"Exercise11_07.py","file_ext":"py","file_size_in_byte":2346,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"15"} +{"seq_id":"22867394116","text":"#!/usr/bin/python\nimport os\nimport math\nimport numpy as np\nimport vip_hci as vip\nfrom photutils import CircularAperture as ca\nfrom photutils import aperture_photometry as ap\nfrom astropy.io import fits\nfrom astropy.stats import sigma_clip\nfrom scipy.ndimage.interpolation import rotate\nfrom scipy.ndimage.filters import gaussian_filter\nfrom vip_hci.preproc import cube_recenter_2dfit\nimport pickle\nimport matplotlib.pyplot as plt\n\nimport sys\nsys.path.insert(0,'/Users/Ryan/research/pipeline/')\nfrom utilities import data_opener\n\ndef nod_subtract(master_path,prefix,aux_path,start_frame_num,end_frame_num,return_path,progress_print,test_type='',luci=False):\n #We take data on different parts of the detector, and then subtract one set of images from the \n # median of the other set and vise versa. This eliminates the majority of bad pixels and background noise\n\n if os.path.isdir(return_path):\n print('Directory exists')\n else:\n os.mkdir(return_path)\n print('Making directory')\n nods = []\n fnames,fname_prefixes = data_opener(master_path,prefix,aux_path,start_frame_num,end_frame_num,test_type,progress_print,luci)\n for fname_prefix in fname_prefixes:\n if fits.open('{}raw_data/{}.fits'.format(master_path,fname_prefix))[0].header['FLAG'] == 'NOD_A':\n nods.append('NOD_A')\n #print(fname_prefix,'NOD_A')\n else: \n nods.append('NOD_B')\n #print(fname_prefix,'NOD_B')\n fnames_np = np.array(fnames, dtype=np.float)\n fname_prefixes_np = np.array(fname_prefixes)\n line = 0\n end = False\n while end == False:\n chnod = False\n chnod_2 = False\n fnames_nod_A = []\n fname_prefixes_nod_A = []\n while chnod == False:\n fnames_nod_A.append(fnames_np[line])\n fname_prefixes_nod_A.append(fname_prefixes_np[line])\n try:\n if nods[line+1] != nods[line]:\n chnod = True\n except:\n IndexError\n chnod = True\n line += 1\n fnames_nod_B = []\n fname_prefixes_nod_B = []\n while chnod_2 == False:\n fnames_nod_B.append(fnames_np[line])\n fname_prefixes_nod_B.append(fname_prefixes_np[line])\n try:\n if nods[line+1] != nods[line]:\n chnod_2 = True\n except:\n IndexError\n chnod_2 = True\n line += 1\n fnames_nod_A_med = np.median(fnames_nod_A,axis=0)\n fnames_nod_B_med = np.median(fnames_nod_B,axis=0)\n #print(len(fnames_nod_A),len(fnames_nod_B))\n for i in range(len(fnames_nod_A)):\n fname_sub_A = fnames_nod_A[i] - fnames_nod_B_med\n out_fits = fits.HDUList(fits.PrimaryHDU(fname_sub_A))\n out_fits.writeto('{}{}.fits'.format(return_path,fname_prefixes_nod_A[i]), overwrite = True)\n if progress_print == True:\n print ('{} sci subtracted'.format(fname_prefixes_nod_A[i]))\n for i in range(len(fnames_nod_B)):\n fname_sub_B = fnames_nod_B[i] - fnames_nod_A_med\n out_fits = fits.HDUList(fits.PrimaryHDU(fname_sub_B))\n out_fits.writeto('{}{}.fits'.format(return_path,fname_prefixes_nod_B[i]), overwrite = True)\n if progress_print == True:\n print ('{} sci subtracted'.format(fname_prefixes_nod_B[i]))\n if line == len(nods):\n end = True\n print('All frames nod subtracted')\n del fnames_nod_A\n del fname_prefixes_nod_A\n del fnames_nod_B\n del fname_prefixes_nod_B\n del fnames\n del fname_prefixes\n del nods\n del fnames_np\n del fname_prefixes_np\n\ndef star_center(master_path,prefix,aux_path,start_frame_num,end_frame_num,return_path,progress_print,star_location,crop_parameter,test_type=''):\n #Roughly centers star based on pixel coordinates of brightest pixel\n\n if os.path.isdir(return_path):\n print('Directory exists')\n else:\n os.mkdir(return_path)\n print('Making directory')\n nods = []\n fnames,fname_prefixes = data_opener(master_path,prefix,aux_path,start_frame_num,end_frame_num,test_type,progress_print)\n for fname_prefix in fname_prefixes:\n if fits.open('{}raw_data/{}.fits'.format(master_path,fname_prefix))[0].header['FLAG'] == 'NOD_A': #changed to fits.gz\n nods.append('NOD_A')\n else: \n nods.append('NOD_B')\n fnames_np = np.array(fnames, dtype=np.float)\n fname_prefixes_np = np.array(fname_prefixes)\n line = 0\n end = False\n while end == False:\n chnod = False\n fnames_nod = []\n fname_prefixes_nod = []\n while chnod == False:\n fnames_nod.append(fnames_np[line])\n fname_prefixes_nod.append(fname_prefixes_np[line])\n try:\n if nods[line+1] != nods[line]:\n chnod = True\n except:\n IndexError\n chnod = True\n line += 1\n fnames_med = np.median(fnames_nod,axis=0)\n #out_fits = fits.HDUList(fits.PrimaryHDU(fnames_med))\n #out_fits.writeto('{}nod_med_comp_{}.fits'.format(return_path,line), overwrite = True)\n fnames_blur = gaussian_filter(fnames_med, 7)\n star = np.unravel_index(np.argmax(fnames_blur), fnames_blur.shape)\n if star_location == True:\n print('star',star)\n for i in range(len(fnames_nod)):\n fname_crop = fnames_nod[i][star[0]-crop_parameter:star[0]+crop_parameter+1,star[1]-crop_parameter:star[1]+crop_parameter+1] \n out_fits = fits.HDUList(fits.PrimaryHDU(fname_crop))\n out_fits.writeto('{}{}.fits'.format(return_path,fname_prefixes_nod[i]), overwrite = True)\n if progress_print == True:\n print ('{} star centered'.format(fname_prefixes_nod[i]))\n if line == len(nods):\n end = True\n print('All frames star centered')\n del nods\n del fnames_np\n del fname_prefixes_np\n del fnames_nod\n del fname_prefixes_nod\n\ndef stripe_cleaner(master_path,prefix,aux_path,start_frame_num,end_frame_num,return_path,progress_print,test_type='',mask_size=6000,luci=False):\n #Cleans detector stripes in images by subtracting the meadian of the entire column from each pixel\n # in the column\n\n if os.path.isdir(return_path):\n print('Directory exists')\n else:\n os.mkdir(return_path)\n print('Making directory')\n for i in range(start_frame_num, end_frame_num, 1):\n fname_prefix = '%s%03d'%(prefix,i)\n try:\n if aux_path == 'raw_data':\n fname = fits.open('{}{}/{}.fits'.format(master_path,aux_path,fname_prefix))\n fname_float = fname[0].data.astype(float)\n else:\n fname = fits.open('{}reduced_data{}/{}/{}.fits'.format(master_path,test_type,aux_path,fname_prefix))\n fname_float = fname[0].data.astype(float)\n if progress_print == True:\n print('{} loaded'.format(fname_prefix))\n except:\n FileNotFoundError\n print('File Not Found Error')\n continue\n #fname_uncrcted = fname.copy()\n fname_star = fname_float.copy()\n y_dim,x_dim = fname_float.shape\n fname_blur = gaussian_filter(fname_float, 7)\n peak = np.unravel_index(np.argmax(fname_blur), fname_blur.shape) #finding star in blurred frame\n x = [i for i in range(x_dim)] #setting up mask\n y = [i for i in range(y_dim)]\n X,Y = np.meshgrid(x,y)\n x_0 = X[peak[0],peak[1]]\n y_0 = Y[peak[0],peak[1]]\n Mask = ((X-x_0)**2+(Y-y_0)**2)mask_size #area around star is masked out\n fname_float[Mask] = np.nan #star is replaced by nans\n fname_star[Mask_2] = np.nan #area surrounding stars replaced by nans\n one_d_array = np.nanmedian(fname_float, axis=0) #medians columns, ignoring nans\n two_d_array = np.tile(one_d_array,(y_dim,1))\n fname_stripe_crct = fname_float - two_d_array\n fname_star_stripe_crct = fname_star - two_d_array \n fname_stripe_crct[Mask] = fname_star_stripe_crct[Mask]\n out_fits = fits.HDUList(fits.PrimaryHDU(fname_stripe_crct))\n out_fits.writeto('{}{}.fits'.format(return_path,fname_prefix), overwrite = True)\n if progress_print == True:\n print('{} stripe corrected'.format(fname_prefix))\n del Mask\n del x\n del y\n fname.close()\n print('All frames stripe corrected')\n\ndef frame_filter(master_path,prefix,aux_path,start_frame_num,end_frame_num,return_path,progress_print,fwhm_tolerance,peak_tolerance,luci=False,test_type=''):\n #Filters frame based on FWHM size and peak brightness \n if os.path.isdir(return_path):\n print('Directory exists')\n else:\n os.mkdir(return_path)\n print('Making directory')\n try:\n os.remove('{}reduced_data/fwhm_median.txt'.format(master_path))\n except:\n FileNotFoundError\n cube,fname_prefixes = data_opener(master_path,prefix,aux_path,start_frame_num,end_frame_num,test_type,progress_print,luci)\n for fname_prefix in fname_prefixes: #Removing exsisting frames from directory might need this for functions called after frame filter\n try:\n os.remove('{}{}.fits'.format(return_path,fname_prefix))\n except:\n FileNotFoundError\n cube = np.array(cube,dtype=np.float)\n print('Pre-filter length = {}'.format(len(cube)))\n fname_prefixes = np.array(fname_prefixes)\n fwhms = []\n fname_prefixes_fwhm_filtered = []\n #Filtering frames based on fwhm size\n for fname,fname_prefix in zip(cube,fname_prefixes):\n fwhm = vip.var.fit_2dgaussian(fname, crop=True, cropsize=9, full_output=True, debug=False)\n fwhm_mean = np.mean([fwhm.loc[0,'fwhm_x'],fwhm.loc[0,'fwhm_y']])\n if progress_print == True:\n print('{} fwhm_mean = {}'.format(fname_prefix,fwhm_mean))\n fwhms.append(fwhm_mean)\n fwhms = np.array(fwhms)\n print(min(fwhms),max(fwhms))\n #Finding smallest fwhms \n if fwhm_tolerance == 100:\n g = len(cube)\n cube_fwhm_filtered = cube\n fname_prefixes_fwhm_filtered = fname_prefixes\n else:\n fwhm_tolerance = fwhm_tolerance*0.01\n g = int(np.ceil(len(cube)*fwhm_tolerance)) #np.ceil will round up the number of frames to pass filtering\n fwhm_filter = fwhms.argsort()[:g] #returns indicies of smallest fwhms\n cube_fwhm_filtered = cube[fwhm_filter]\n fname_prefixes_fwhm_filtered = fname_prefixes[fwhm_filter] #keeping track of prefixes\n if progress_print == True:\n print('{} frames within fwhm tolerance'.format(g))\n #Finding peak flux values in frames that passed fwhm filtering\n peak_list = []\n for fname,fname_prefix,fwhm in zip(cube_fwhm_filtered,fname_prefixes_fwhm_filtered,fwhms):\n image_center = int((fname.shape)[0]/2 + .5) #Finding image center\n flux = vip.metrics.aperture_flux(fname,[image_center],[image_center],fwhm=fwhm)\n peak_list.append(flux[0])\n if progress_print == True:\n print('{} peak = {}'.format(fname_prefix,flux[0]))\n peak_list = np.array(peak_list)\n #Finding frames with highest peaks\n if peak_tolerance == 100:\n k = len(cube_fwhm_filtered)\n cube_peak_filtered = cube_fwhm_filtered\n fname_prefixes_peak_filtered = fname_prefixes_fwhm_filtered\n else:\n peak_tolerance = peak_tolerance*0.01\n k = int(np.ceil((len(peak_list))*peak_tolerance))\n peak_filter = peak_list.argsort()[-k:] #returns indicies of largest peak values\n cube_peak_filtered = cube_fwhm_filtered[peak_filter]\n fname_prefixes_peak_filtered = fname_prefixes_fwhm_filtered[peak_filter]\n if progress_print == True:\n print('{} frames within peak tolerance'.format(k))\n #Frames are now peak filtered\n for fname,fname_prefix in zip(cube_peak_filtered,fname_prefixes_peak_filtered):\n out_fits = fits.HDUList(fits.PrimaryHDU(fname))\n out_fits.writeto('{}{}.fits'.format(return_path,fname_prefix), overwrite = True)\n print('{} frames passed filtering'.format(len(cube_peak_filtered)))\n \n del cube\n del peak_list\n del fname_prefixes\n del cube_peak_filtered\n del fname_prefixes_peak_filtered\n del cube_fwhm_filtered\n del fwhms\n del fname_prefixes_fwhm_filtered\n\ndef star_ultra_center(master_path,prefix,aux_path,start_frame_num,end_frame_num,return_path,progress_print,crop_parameter,luci=False,test_type=''):\n #Centers each image via interpolation\n if os.path.isdir(return_path):\n print('Deleting directory')\n else:\n os.mkdir(return_path)\n print('Making directory')\n filelist = [f for f in os.listdir(return_path) if f.endswith('.fits')]\n for f in filelist:\n os.remove(os.path.join(return_path,f))\n\n cube,fname_prefixes = data_opener(master_path,prefix,aux_path,start_frame_num,end_frame_num,test_type,progress_print,luci=luci)\n cube_np_array = np.array(cube, dtype=np.float)\n fnames_med = np.median(cube_np_array,axis=0)\n fwhm = vip.var.fit_2dgaussian(fnames_med, crop=True, full_output=True,debug=False)\n fwhm_mean = np.mean([fwhm.loc[0,'fwhm_x'],fwhm.loc[0,'fwhm_y']])\n print('FWHM = {}'.format(fwhm_mean))\n cube_ultra_center = cube_recenter_2dfit(cube_np_array, (crop_parameter+1,crop_parameter+1), fwhm = fwhm_mean, subi_size=20,debug=False)\n for fname_ultra_centered,fname_prefix_ultra_centered in zip(cube_ultra_center,fname_prefixes):\n out_fits = fits.HDUList(fits.PrimaryHDU(fname_ultra_centered))\n out_fits.writeto('{}{}.fits'.format(return_path,fname_prefix_ultra_centered), overwrite = True)\n if progress_print == True:\n print('{} ultra centered'.format(fname_prefix_ultra_centered))\n print('All frames ultra centered')\n del cube\n del fname_prefixes\n del cube_ultra_center\n\ndef llsg_psf_subtraction(master_path,prefix,aux_path,start_frame_num,end_frame_num,return_path,progress_print,frame_set,rank_input,thresh_input,max_iter_input,luci=False,test_type=''):\n #PSF subtraction based off LLSG algorithm published in Gonzalez et al 2018 (https://arxiv.org/pdf/1602.08381.pdf)\n if os.path.isdir(return_path):\n print('Directory exists')\n else:\n os.mkdir(return_path)\n print('Making directory')\n cube,fname_prefixes,parangs = data_opener(master_path,prefix,aux_path,start_frame_num,end_frame_num,test_type,progress_print,return_parang=True,luci=luci)\n cube_np_array = np.array(cube, dtype=np.float)\n fnames_med = np.median(cube_np_array,axis=0)\n fwhm = vip.var.fit_2dgaussian(fnames_med, crop=True, full_output=True,debug=False)\n fwhm_mean = np.mean([fwhm.loc[0,'fwhm_x'],fwhm.loc[0,'fwhm_y']])\n print('FWHM = {}'.format(fwhm_mean))\n\n parangs_np = np.array(parangs, dtype=np.float)\n psf_subtraction = vip.llsg.llsg(cube_np_array, parangs_np, fwhm_mean, rank=rank_input, thresh=thresh_input,max_iter=max_iter_input,random_seed=10,full_output=False)\n out_fits = fits.HDUList(fits.PrimaryHDU(psf_subtraction))\n out_fits.writeto('{}llsg_sub_{}{}.fits'.format(return_path,frame_set,rank_input), overwrite = True)\n print('Star evaluated using llsg method')\n del cube\n del parangs\n del fname_prefixes\n\ndef median_psf_subtraction(master_path,prefix,aux_path,start_frame_num,end_frame_num,return_path,progress_print,frame_set,wd,luci=False,test_type=''):\n #Conventional psf subtraction algorithm\n if os.path.isdir(return_path):\n print('Directory exists')\n else:\n os.mkdir(return_path)\n print('Making directory')\n cube,fname_prefixes,parangs = data_opener(master_path,prefix,aux_path,start_frame_num,end_frame_num,test_type,progress_print,return_parang=True,luci=luci)\n\n #a_frames = []\n #a_frames_pa = []\n #b_frames = []\n #b_frames_pa = []\n #for i,fname_prefix,parang in zip(cube,fname_prefixes,parangs):\n # if fits.open('{}raw_data/{}.fits'.format(master_path,fname_prefix))[0].header['FLAG'] == 'NOD_A':\n # a_frames.append(i)\n # a_frames_pa.append(parang)\n # print('a')\n # else:\n # b_frames.append(i)\n # b_frames_pa.append(parang)\n # print('b')\n #print(len(a_frames),len(b_frames))\n #a_frames_np = np.array(a_frames, dtype=np.float)\n #a_frames_pa_np = np.array(a_frames_pa, dtype=np.float)\n #b_frames_np = np.array(b_frames, dtype=np.float)\n #b_frames_pa_np =np.array(b_frames_pa, dtype=np.float)\n #fwhm_load = np.loadtxt('{}reduced_data{}/fwhm_median.txt'.format(master_path,test_type))\n#\n#\n #psf_subtraction_a = vip.medsub.median_sub(a_frames_np, a_frames_pa_np, fwhm=fwhm_load, mode='fullfr',full_output=False)\n #out_fits = fits.HDUList(fits.PrimaryHDU(psf_subtraction_a))\n #out_fits.writeto('{}median_sub_{}_a.fits'.format(return_path,frame_set), overwrite = True)\n#\n #psf_subtraction_b = vip.medsub.median_sub(b_frames_np, b_frames_pa_np, fwhm=fwhm_load, mode='fullfr',full_output=False)\n #out_fits = fits.HDUList(fits.PrimaryHDU(psf_subtraction_b))\n #out_fits.writeto('{}median_sub_{}_b.fits'.format(return_path,frame_set), overwrite = True)\n\n \n\n cube_np_array = np.array(cube, dtype=np.float)\n fnames_med = np.median(cube_np_array,axis=0)\n fwhm = vip.var.fit_2dgaussian(fnames_med, crop=True, full_output=True,debug=False)\n fwhm_mean = np.mean([fwhm.loc[0,'fwhm_x'],fwhm.loc[0,'fwhm_y']])\n print('FWHM = {}'.format(fwhm_mean))\n parangs_np = np.array(parangs, dtype=np.float)\n psf_subtraction = vip.medsub.median_sub(cube_np_array, parangs_np, fwhm=fwhm_mean, mode='fullfr',full_output=False)\n out_fits = fits.HDUList(fits.PrimaryHDU(psf_subtraction))\n out_fits.writeto('{}median_sub_{}.fits'.format(return_path,frame_set), overwrite = True)\n print('Star evaluated using median psf subtraction method')\n del cube\n del parangs\n del fname_prefixes\n\ndef psf_stacker(master_path,prefix,aux_path,start_frame_num,end_frame_num,return_path,progress_print,frame_set,wd,tag='',luci=False,test_type=''):\n #Median combines images together\n\n if os.path.isdir(return_path):\n print('Directory exists')\n else:\n os.mkdir(return_path)\n print('Making directory')\n fnames,fname_prefixes,parangs = data_opener(master_path,prefix,aux_path,start_frame_num,end_frame_num,test_type,progress_print,return_parang=True,luci=luci)\n fnames_median = np.median(fnames,axis=0)\n fnames_deroto = []\n for fname,parang,fname_prefix in zip(fnames,parangs,fname_prefixes):\n fname_deroto = rotate(fname, angle = -parang, cval = np.nan, reshape=False)\n if progress_print == True:\n print('{} derotated'.format(fname_prefix), parang)\n fnames_deroto.append(fname_deroto)\n fnames_median_deroto = np.median(fnames_deroto,axis=0)\n out_fits = fits.HDUList(fits.PrimaryHDU(fnames_median))\n out_fits.writeto('{}{}_no_deroto.fits'.format(return_path,frame_set), overwrite = True)\n out_fits = fits.HDUList(fits.PrimaryHDU(fnames_median_deroto))\n out_fits.writeto('{}{}_deroto.fits'.format(return_path,frame_set), overwrite = True)\n \n plt.figure()\n plt.plot(parangs,'o')\n #plt.legend(fontsize=10)\n plt.title('Parang per frame {}'.format(wd))\n plt.xlabel('Frame Number ({}+)'.format(prefix))\n plt.ylabel('Parallactic Angle')\n plt.savefig('{}reduced_data/parang_{}{}.png'.format(master_path,wd,tag))\n plt.show()\n\n print('Star median combined')\n print('Star derotated and median combined')\n del fnames\n del fname_prefixes\n del parangs\n\ndef contrast_curve_vip(master_path,prefix,aux_path,start_frame_num,end_frame_num,return_path,progress_print,method,wd,star_mag,rank='',luci=False,test_type='',tag=''):\n #Improved Contrast curve using algorithm from VIP\n\n if os.path.isdir(return_path):\n print('Directory exists')\n else:\n os.mkdir(return_path)\n print('Making directory')\n fnames,fname_prefixes,parangs = data_opener(master_path,prefix,aux_path,start_frame_num,end_frame_num,test_type,progress_print,return_parang=True,luci=luci)\n del fname_prefixes\n\n parangs = np.array(parangs,dtype=np.float)\n fnames_array = np.array(fnames,dtype=np.float)\n fnames_med = np.median(fnames_array,axis=0)\n fwhm = vip.var.fit_2dgaussian(fnames_med, crop=True, full_output=True,debug=False)\n fwhm_mean = np.mean([fwhm.loc[0,'fwhm_x'],fwhm.loc[0,'fwhm_y']])\n print('FWHM = {}'.format(fwhm_mean))\n\n image_center = int((fnames_med.shape)[0]/2 + .5) #Finding image center\n print('Image Center {}'.format(image_center))\n flux = vip.metrics.aperture_flux(fnames_med,[image_center],[image_center],fwhm=fwhm_mean)\n print('Star Flux {}'.format(flux[0]))\n\n if luci == True:\n plate_scale = 0.015\n else:\n plate_scale = 10.7/1000.\n print('Plate Scale {}'.format(plate_scale))\n\n path = '{}final/{}/contrast_curve{}.png'.format(master_path,method,tag)\n \n if method == 'median_psf_subtraction':\n data = vip.metrics.contrast_curve(fnames_array,parangs,fnames_med,fwhm_mean,plate_scale,flux[0],vip.medsub.median_sub,plot=True,save_plot=path,debug=False,full_output=True,object_name=wd)\n \n elif method == 'llsg_psf_subtraction':\n data = vip.metrics.contrast_curve(fnames_array,parangs,fnames_med,fwhm_mean,plate_scale,flux[0],vip.llsg.llsg,plot=True,save_plot=path,debug=False,full_output=True,object_name=wd,rank=rank,thresh=1,max_iter=10)\n #Saving CC data as Pandas dataframe\n data[0].to_csv('{}final/{}/{}_cc_data{}.csv'.format(master_path,method,wd,tag))\n\n #Plotting shifted magnitude plot. Adopting the convention from VIP source code\n cont_curve_samp = data[0]['sensitivity_gaussian']\n cont_curve_samp_corr = data[0]['sensitivity_student']\n dpi = 300\n figsize=(8, 4)\n rad_samp_arcsec = data[0]['distance_arcsec']\n rad_samp = data[0]['distance']\n pxscale=plate_scale\n label = ['Sensitivity (Gaussian)','Sensitivity (Student-t correction)']\n fig2 = plt.figure(figsize=figsize, dpi=dpi)\n ax3 = fig2.add_subplot(111)\n cc_mags = -2.5*np.log10(cont_curve_samp)+star_mag\n con4, = ax3.plot(rad_samp_arcsec, cc_mags, '-',\n alpha=0.2, lw=2, color='green')\n con5, = ax3.plot(rad_samp_arcsec, cc_mags, '.', alpha=0.2,\n color='green')\n cc_mags_corr = -2.5*np.log10(cont_curve_samp_corr)+star_mag\n con6, = ax3.plot(rad_samp_arcsec, cc_mags_corr, '-',\n alpha=0.4, lw=2, color='blue')\n con7, = ax3.plot(rad_samp_arcsec, cc_mags_corr, '.',\n alpha=0.4, color='blue')\n lege = [(con4, con5), (con6, con7)]\n plt.legend(lege, label, fancybox=True, fontsize='medium')\n plt.xlabel('Angular separation [arcsec]')\n plt.ylabel('Magnitude')\n plt.gca().invert_yaxis()\n plt.grid('on', which='both', alpha=0.2, linestyle='solid')\n ax3.set_xlim(0, np.max(rad_samp*pxscale))\n ax4 = ax3.twiny()\n ax4.set_xlabel('Distance [pixels]')\n ax4.plot(rad_samp, cc_mags, '', alpha=0.)\n ax4.set_xlim(0, np.max(rad_samp))\n magpath = '{}final/{}/mag_contrast_curve{}.png'.format(master_path,method,tag)\n plt.savefig(magpath)","repo_name":"ryanw3998/white-dwarfs","sub_path":"process.py","file_name":"process.py","file_ext":"py","file_size_in_byte":23376,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"15"} +{"seq_id":"37495560317","text":"import os,sys\nimport pandas as pd\nimport numpy as np\nfrom src.logger import logging\nfrom src.exception import CustomException\nfrom dataclasses import dataclass\nfrom sklearn.preprocessing import StandardScaler\nfrom sklearn.impute import SimpleImputer\nfrom sklearn.pipeline import Pipeline\nfrom sklearn.compose import ColumnTransformer\nfrom src.utils import save_object\n\n@dataclass\nclass DataTransformationConfig:\n preprocessor_path=os.path.join('artifacts','preprocessor.pkl')\n\nclass DataTransformation:\n def __init__(self):\n self.data_transformation_config=DataTransformationConfig()\n\n def get_preprocessor_file(self):\n try:\n logging.info(\"Pipeline preprocessor is initiated\")\n num_col=['mean texture',\n 'mean smoothness',\n 'mean compactness',\n 'mean concave points',\n 'mean symmetry',\n 'mean fractal dimension',\n 'texture error',\n 'area error',\n 'smoothness error',\n 'compactness error',\n 'concavity error',\n 'concave points error',\n 'symmetry error',\n 'fractal dimension error',\n 'worst texture',\n 'worst area',\n 'worst smoothness',\n 'worst compactness',\n 'worst concavity',\n 'worst concave points',\n 'worst symmetry',\n 'worst fractal dimension']\n num_pipeline=Pipeline(steps=\n [('Imputer',SimpleImputer(strategy='median')),\n ('Scaler',StandardScaler())])\n preprocessor=ColumnTransformer([('Numerical Pipeline',num_pipeline,num_col)])\n logging.info(\"prprocessor pipeline is completed\")\n return preprocessor\n except Exception as e:\n logging.info(\"Error occured while preprocessor pipeline\")\n raise CustomException(e,sys)\n \n def initiate_data_transform(self,train_path,test_path):\n try:\n logging.info(\"Preprocessor object creation is initiated\")\n train_df=pd.read_csv(train_path)\n test_df=pd.read_csv(test_path)\n train_df['target']=train_df['target'].map({'malignant':1,'benign':0})\n test_df['target']=test_df['target'].map({'malignant':1,'benign':0})\n target_col='target'\n drop_col=['mean radius',\n 'mean perimeter',\n 'mean area',\n 'mean concavity',\n 'radius error',\n 'perimeter error',\n 'worst radius',\n 'worst perimeter',target_col]\n \n train_feature_df=train_df.drop(drop_col,axis=1)\n train_target_df=train_df[target_col]\n\n test_feature_df=test_df.drop(drop_col,axis=1)\n test_target_df=test_df[target_col]\n logging.info(\"cleaned trained and test data is obtained\")\n preprocessor=self.get_preprocessor_file()\n train_feature_scaled=preprocessor.fit_transform(train_feature_df)\n test_feature_scaled=preprocessor.transform(test_feature_df)\n\n train_arr=np.c_[train_feature_scaled,np.array(train_target_df)]\n test_arr=np.c_[test_feature_scaled,np.array(test_target_df)]\n logging.info(\"preproessor object and array is created \")\n save_object(self.data_transformation_config.preprocessor_path,preprocessor)\n logging.info(\"preprocessor object is saved \")\n return(\n train_arr,test_arr\n )\n except Exception as e:\n logging.info(\"Error occured in getting preprocessor object\")\n raise CustomException(e,sys)\n\n","repo_name":"Abhishek3689/Breast_Cancer_Project","sub_path":"src/components/data_transformation.py","file_name":"data_transformation.py","file_ext":"py","file_size_in_byte":3928,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"15"} +{"seq_id":"72953899531","text":"import asyncio\n\nfrom got.broker import InMemoryBroker\nfrom got.got import Got\nfrom got.task import BasicHTTPTask\nimport random\n\ngot = Got(InMemoryBroker())\n\n\n@got.handle(\"basic\", 10)\nclass HTTPTask(BasicHTTPTask):\n\n def __init__(self, data):\n super().__init__(data)\n\n async def before(self):\n pass\n\n async def on_task(self):\n return await super().on_task()\n\n async def handle(self):\n await asyncio.sleep(random.randint(0, 5))\n return await super().handle()\n\n async def success(self):\n print(f\"doing {self.data}\")\n for i in range(random.randint(1, 3)):\n await got.new(\"basic\", f\"{self.data}.\")\n\n async def failure(self):\n return await super().failure()\n\n\ngot.serve_sync([\"basic\"])\n","repo_name":"Kilerd/got","sub_path":"example/basic.py","file_name":"basic.py","file_ext":"py","file_size_in_byte":765,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"15"} +{"seq_id":"10248356634","text":"from __future__ import absolute_import\n\n\nimport scapy.consts\nfrom scapy.config import conf\nfrom scapy.error import Scapy_Exception, warning\nfrom scapy.modules import six\nfrom scapy.utils import atol, ltoa, itom, plain_str, pretty_list\n\n\n##############################\n# Routing/Interfaces stuff #\n##############################\n\nclass Route:\n def __init__(self):\n self.resync()\n\n def invalidate_cache(self):\n self.cache = {}\n\n def resync(self):\n from scapy.arch import read_routes\n self.invalidate_cache()\n self.routes = read_routes()\n\n def __repr__(self):\n rtlst = []\n for net, msk, gw, iface, addr, metric in self.routes:\n rtlst.append((ltoa(net),\n ltoa(msk),\n gw,\n (iface.description if not isinstance(iface, six.string_types) else iface), # noqa: E501\n addr,\n str(metric)))\n\n return pretty_list(rtlst,\n [(\"Network\", \"Netmask\", \"Gateway\", \"Iface\", \"Output IP\", \"Metric\")]) # noqa: E501\n\n def make_route(self, host=None, net=None, gw=None, dev=None, metric=1):\n from scapy.arch import get_if_addr\n if host is not None:\n thenet, msk = host, 32\n elif net is not None:\n thenet, msk = net.split(\"/\")\n msk = int(msk)\n else:\n raise Scapy_Exception(\"make_route: Incorrect parameters. You should specify a host or a net\") # noqa: E501\n if gw is None:\n gw = \"0.0.0.0\"\n if dev is None:\n if gw:\n nhop = gw\n else:\n nhop = thenet\n dev, ifaddr, _ = self.route(nhop)\n else:\n ifaddr = get_if_addr(dev)\n return (atol(thenet), itom(msk), gw, dev, ifaddr, metric)\n\n def add(self, *args, **kargs):\n \"\"\"Ex:\n add(net=\"192.168.1.0/24\",gw=\"1.2.3.4\")\n \"\"\"\n self.invalidate_cache()\n self.routes.append(self.make_route(*args, **kargs))\n\n def delt(self, *args, **kargs):\n \"\"\"delt(host|net, gw|dev)\"\"\"\n self.invalidate_cache()\n route = self.make_route(*args, **kargs)\n try:\n i = self.routes.index(route)\n del(self.routes[i])\n except ValueError:\n warning(\"no matching route found\")\n\n def ifchange(self, iff, addr):\n self.invalidate_cache()\n the_addr, the_msk = (addr.split(\"/\") + [\"32\"])[:2]\n the_msk = itom(int(the_msk))\n the_rawaddr = atol(the_addr)\n the_net = the_rawaddr & the_msk\n\n for i, route in enumerate(self.routes):\n net, msk, gw, iface, addr, metric = route\n if scapy.consts.WINDOWS:\n if iff.guid != iface.guid:\n continue\n elif iff != iface:\n continue\n if gw == '0.0.0.0':\n self.routes[i] = (the_net, the_msk, gw, iface, the_addr, metric) # noqa: E501\n else:\n self.routes[i] = (net, msk, gw, iface, the_addr, metric)\n conf.netcache.flush()\n\n def ifdel(self, iff):\n self.invalidate_cache()\n new_routes = []\n for rt in self.routes:\n if scapy.consts.WINDOWS:\n if iff.guid == rt[3].guid:\n continue\n elif iff == rt[3]:\n continue\n new_routes.append(rt)\n self.routes = new_routes\n\n def ifadd(self, iff, addr):\n self.invalidate_cache()\n the_addr, the_msk = (addr.split(\"/\") + [\"32\"])[:2]\n the_msk = itom(int(the_msk))\n the_rawaddr = atol(the_addr)\n the_net = the_rawaddr & the_msk\n self.routes.append((the_net, the_msk, '0.0.0.0', iff, the_addr, 1))\n\n def route(self, dst=None, verbose=conf.verb):\n \"\"\"Returns the IPv4 routes to a host.\n parameters:\n - dst: the IPv4 of the destination host\n\n returns: (iface, output_ip, gateway_ip)\n - iface: the interface used to connect to the host\n - output_ip: the outgoing IP that will be used\n - gateway_ip: the gateway IP that will be used\n \"\"\"\n dst = dst or \"0.0.0.0\" # Enable route(None) to return default route\n if isinstance(dst, bytes):\n try:\n dst = plain_str(dst)\n except UnicodeDecodeError:\n raise TypeError(\"Unknown IP address input (bytes)\")\n if dst in self.cache:\n return self.cache[dst]\n # Transform \"192.168.*.1-5\" to one IP of the set\n _dst = dst.split(\"/\")[0].replace(\"*\", \"0\")\n while True:\n idx = _dst.find(\"-\")\n if idx < 0:\n break\n m = (_dst[idx:] + \".\").find(\".\")\n _dst = _dst[:idx] + _dst[idx + m:]\n\n atol_dst = atol(_dst)\n paths = []\n for d, m, gw, i, a, me in self.routes:\n if not a: # some interfaces may not currently be connected\n continue\n aa = atol(a)\n if aa == atol_dst:\n paths.append(\n (0xffffffff, 1, (scapy.consts.LOOPBACK_INTERFACE, a, \"0.0.0.0\")) # noqa: E501\n )\n if (atol_dst & m) == (d & m):\n paths.append((m, me, (i, a, gw)))\n\n if not paths:\n if verbose:\n warning(\"No route found (no default route?)\")\n return scapy.consts.LOOPBACK_INTERFACE, \"0.0.0.0\", \"0.0.0.0\"\n # Choose the more specific route\n # Sort by greatest netmask and use metrics as a tie-breaker\n paths.sort(key=lambda x: (-x[0], x[1]))\n # Return interface\n ret = paths[0][2]\n self.cache[dst] = ret\n return ret\n\n def get_if_bcast(self, iff):\n for net, msk, gw, iface, addr, metric in self.routes:\n if net == 0:\n continue\n if scapy.consts.WINDOWS:\n if iff.guid != iface.guid:\n continue\n elif iff != iface:\n continue\n bcast = atol(addr) | (~msk & 0xffffffff) # FIXME: check error in atol() # noqa: E501\n return ltoa(bcast)\n warning(\"No broadcast address found for iface %s\\n\", iff)\n\n\n# TRex Change - Set Route to None\n# conf.route = Route()\nconf.route = None\n\n# TRex Changes\n# iface = conf.route.route(None, verbose=0)[0]\niface = None\n\n# Warning: scapy.consts.LOOPBACK_INTERFACE must always be used statically, because it # noqa: E501\n# may be changed by scapy/arch/windows during execution\n\nif getattr(iface, \"name\", iface) == scapy.consts.LOOPBACK_INTERFACE:\n from scapy.arch import get_working_if\n conf.iface = get_working_if()\nelse:\n conf.iface = iface\n\ndel iface\n","repo_name":"cisco-system-traffic-generator/trex-core","sub_path":"scripts/external_libs/scapy-2.4.3/scapy/route.py","file_name":"route.py","file_ext":"py","file_size_in_byte":6772,"program_lang":"python","lang":"en","doc_type":"code","stars":1157,"dataset":"github-code","pt":"15"} +{"seq_id":"22356030679","text":"import os\nimport cv2\nfrom app.face_recognition import faceRecognitionPipeline\nfrom flask import render_template, request\nimport matplotlib.image as matimg\n\n\nUPLOAD_FOLDER = 'static/upload'\n\ndef index():\n return render_template('index.html')\n\n\ndef app():\n return render_template('app.html')\n\n\ndef genderapp():\n if request.method == 'POST':\n f = request.files['image_name']\n filename = f.filename\n # save our image in upload folder\n path = os.path.join(UPLOAD_FOLDER,filename)\n f.save(path) # save image into upload folder\n # get predictions\n pred_image, predictions = faceRecognitionPipeline(path)\n pred_filename = 'prediction_image.jpg'\n cv2.imwrite(f'./static/predict/{pred_filename}',pred_image)\n \n # generate report\n report = []\n for i , obj in enumerate(predictions):\n gray_image = obj['roi'] # grayscale image (array)\n eigen_image = obj['eig_img'].reshape(100,100) # eigen image (array)\n gender_name = obj['prediction_name'] # name \n score = round(obj['score']*100,2) # probability score\n \n # save grayscale and eigne in predict folder\n gray_image_name = f'roi_{i}.jpg'\n eig_image_name = f'eigen_{i}.jpg'\n matimg.imsave(f'./static/predict/{gray_image_name}',gray_image,cmap='gray')\n matimg.imsave(f'./static/predict/{eig_image_name}',eigen_image,cmap='gray')\n \n # save report \n report.append([gray_image_name,\n eig_image_name,\n gender_name,\n score])\n \n \n return render_template('gender.html',fileupload=True,report=report) # POST REQUEST\n \n \n \n return render_template('gender.html',fileupload=False) # GET REQUEST","repo_name":"manasakalaimalai/nora.ai","sub_path":"app/views.py","file_name":"views.py","file_ext":"py","file_size_in_byte":1884,"program_lang":"python","lang":"en","doc_type":"code","stars":3,"dataset":"github-code","pt":"15"} +{"seq_id":"38466784903","text":"#!/usr/bin/env python3 \n\nimport sys\nimport os \n\n\nfor nomeFicheiro in sys.argv[1:]:\n \n nomeFicheiro_fin = nomeFicheiro.replace('.txt', '')\n command = './linguakit mwe pt ' + nomeFicheiro + ' -mi > ' + nomeFicheiro_fin + '_output-mutualinformation.txt'\n os.system(command)\n\n command = './linguakit mwe pt ' + nomeFicheiro + ' -cooc > ' + nomeFicheiro_fin + '_output-ngrams.txt'\n os.system(command)\n\n","repo_name":"a16986/Projeto_16986","sub_path":"LinguaKit/execute_mwe.py","file_name":"execute_mwe.py","file_ext":"py","file_size_in_byte":437,"program_lang":"python","lang":"pt","doc_type":"code","stars":0,"dataset":"github-code","pt":"15"} +{"seq_id":"17479030901","text":"def calculateHandlen(hand):\r\n \"\"\"\r\n Returns the length (number of letters) in the current hand.\r\n\r\n hand: dictionary (string-> int)\r\n returns: integer\r\n \"\"\"\r\n handCount = 0\r\n for v in hand.values():\r\n handCount += v\r\n return(handCount)\r\n","repo_name":"Ericksmith/6.00.1x","sub_path":"pSet-4/pset4-4.py","file_name":"pset4-4.py","file_ext":"py","file_size_in_byte":268,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"15"} +{"seq_id":"41143550009","text":"#!/usr/bin/env python\n#\n# Simplified parsing of bind configuration, with include support and nested sections.\n\nfrom __future__ import print_function\n\nimport re\nimport string\n\n\nclass ConfigParseError(Exception):\n \"\"\"Generic error when parsing config file.\"\"\"\n\n def __init__(self, error=None, parent=None):\n # IOError on python3 includes path, on python2 it does not\n message = \"Cannot open the configuration file \\\"{path}\\\": {error}\".format(\n path=error.filename, error=str(error))\n if parent:\n message += \"; included from \\\"{0}\\\"\".format(parent)\n super(ConfigParseError, self).__init__(message)\n self.error = error\n self.parent = parent\n pass\n\n\nclass ConfigFile(object):\n \"\"\"Representation of single configuration file and its contents.\"\"\"\n def __init__(self, path):\n \"\"\"Load config file contents from path.\n\n :param path: Path to file\n \"\"\"\n self.path = path\n self.load(path)\n self.status = None\n\n def __str__(self):\n return self.buffer\n\n def __repr__(self):\n return 'ConfigFile {0} ({1})'.format(\n self.path, self.buffer)\n\n def load(self, path):\n with open(path, 'r') as f:\n self.buffer = self.original = f.read()\n\n def is_modified(self):\n return self.original == self.buffer\n\n def root_section(self):\n return ConfigSection(self, None, 0, len(self.buffer))\n\n\nclass MockConfig(ConfigFile):\n \"\"\"Configuration file with contents defined on constructor.\n\n Intended for testing the library.\n \"\"\"\n DEFAULT_PATH = '/etc/named/mock.conf'\n\n def __init__(self, contents, path=DEFAULT_PATH):\n self.original = contents\n super(MockConfig, self).__init__(path)\n\n def load(self, path):\n self.buffer = self.original\n\n\nclass ConfigSection(object):\n \"\"\"Representation of section or key inside single configuration file.\n\n Section means statement, block, quoted string or any similar.\"\"\"\n\n TYPE_BARE = 1\n TYPE_QSTRING = 2\n TYPE_BLOCK = 3\n TYPE_IGNORED = 4 # comments and whitespaces\n\n def __init__(self, config, name=None, start=None, end=None, kind=None, parser=None):\n \"\"\"\n :param config: config file inside which is this section\n :type config: ConfigFile\n :param kind: type of this section\n \"\"\"\n self.config = config\n self.name = name\n self.start = start\n self.end = end\n self.ctext = self.original_value() # a copy for modification\n self.parser = parser\n if kind is None:\n if self.config.buffer.startswith('{', self.start):\n self.kind = self.TYPE_BLOCK\n elif self.config.buffer.startswith('\"', self.start):\n self.kind = self.TYPE_QSTRING\n else:\n self.kind = self.TYPE_BARE\n else:\n self.kind = kind\n self.statements = []\n\n def __repr__(self):\n text = self.value()\n path = self.config.path\n return 'ConfigSection#{kind}({path}:{start}-{end}: \"{text}\")'.format(\n path=path, start=self.start, end=self.end,\n text=text, kind=self.kind\n )\n\n def __str__(self):\n return self.value()\n\n def copy(self):\n return ConfigSection(self.config, self.name, self.start, self.end, self.kind)\n\n def type(self):\n return self.kind\n\n def value(self):\n return self.ctext\n\n def original_value(self):\n return self.config.buffer[self.start:self.end+1]\n\n def invalue(self):\n \"\"\"Return just inside value of blocks and quoted strings.\"\"\"\n t = self.type()\n if t in (self.TYPE_QSTRING, self.TYPE_BLOCK):\n return self.ctext[1:-1]\n return self.value()\n\n def children(self, comments=False):\n \"\"\"Return list of items inside this section.\"\"\"\n start = self.start\n if self.type() == self.TYPE_BLOCK:\n start += 1\n return list(IscIterator(self.parser, self, comments, start))\n\n def serialize(self):\n return self.value()\n\n\nclass IscIterator(object):\n \"\"\"Iterator for walking over parsed configuration.\n\n Creates sequence of ConfigSection objects for a given file.\n That means a stream of objects.\n \"\"\"\n\n def __init__(self, parser, section, comments=False, start=None):\n \"\"\"Create iterator.\n\n :param comments: Include comments and whitespaces\n :param start: Index for starting, None means beginning of section\n \"\"\"\n self.parser = parser\n self.section = section\n self.current = None\n self.key_wanted = True\n self.comments = comments\n self.waiting = None\n if start is None:\n start = section.start\n self.start = start\n\n def __iter__(self):\n self.current = None\n self.key_wanted = True\n self.waiting = None\n return self\n\n def __next__(self):\n index = self.start\n cfg = self.section.config\n if self.waiting:\n self.current = self.waiting\n self.waiting = None\n return self.current\n if self.current is not None:\n index = self.current.end+1\n if self.key_wanted:\n val = self.parser.find_next_key(cfg, index, self.section.end)\n self.key_wanted = False\n else:\n val = self.parser.find_next_val(cfg, None, index, self.section.end, end_report=True)\n if val is not None and val.value() in self.parser.CHAR_DELIM:\n self.key_wanted = True\n if val is None:\n if self.current is not None and self.current.end < self.section.end and self.comments:\n self.current = ConfigSection(self.section.config, None,\n index, self.section.end, ConfigSection.TYPE_IGNORED)\n return self.current\n raise StopIteration\n if index != val.start and self.comments:\n # Include comments and spaces as ignored section\n self.waiting = val\n val = ConfigSection(val.config, None, index, val.start-1, ConfigSection.TYPE_IGNORED)\n\n self.current = val\n return val\n\n next = __next__ # Python2 compat\n\n\nclass IscVarIterator(object):\n \"\"\"Iterator for walking over parsed configuration.\n\n Creates sequence of ConfigVariableSection objects for a given\n file or section.\n \"\"\"\n\n def __init__(self, parser, section, comments=False, start=None):\n \"\"\"Create iterator.\"\"\"\n self.parser = parser\n self.section = section\n self.iter = IscIterator(parser, section, comments, start)\n\n def __iter__(self):\n return self\n\n def __next__(self):\n vl = []\n try:\n statement = next(self.iter)\n while statement:\n vl.append(statement)\n if self.parser.is_terminal(statement):\n return ConfigVariableSection(vl, None, parent=self.section)\n statement = next(self.iter)\n except StopIteration:\n if vl:\n return ConfigVariableSection(vl, None, parent=self.section)\n raise StopIteration\n\n next = __next__ # Python2 compat\n\n\nclass ConfigVariableSection(ConfigSection):\n \"\"\"Representation for key and values of variable length.\n\n Intended for view and zone.\n \"\"\"\n\n def __init__(self, sectionlist, name, zone_class=None, parent=None, parser=None):\n \"\"\"Creates variable block for zone or view.\n\n :param sectionlist: list of ConfigSection, obtained from IscConfigParser.find_values()\n \"\"\"\n last = next(reversed(sectionlist))\n first = sectionlist[0]\n self.values = sectionlist\n super(ConfigVariableSection, self).__init__(\n first.config, name, start=first.start, end=last.end, parser=parser\n )\n if name is None:\n try:\n self.name = self.var(1).invalue()\n except IndexError:\n pass\n # For optional dns class, like IN or CH\n self.zone_class = zone_class\n self.parent = parent\n\n def key(self):\n if self.zone_class is None:\n return self.name\n return self.zone_class + '_' + self.name\n\n def firstblock(self):\n \"\"\"Return first block section in this tool.\"\"\"\n return self.vartype(0, self.TYPE_BLOCK)\n\n def var(self, i):\n \"\"\"Return value by index, ignore spaces.\"\"\"\n n = 0\n for v in self.values:\n if v.type() != ConfigSection.TYPE_IGNORED:\n if n == i:\n return v\n n += 1\n raise IndexError\n\n def vartype(self, i, vtype):\n n = 0\n for v in self.values:\n if v.type() == vtype:\n if n == i:\n return v\n n += 1\n raise IndexError\n\n def serialize(self):\n s = ''\n for v in self.values:\n s += v.serialize()\n return s\n\n def serialize_skip(self, replace_ignored=None):\n \"\"\"\n Create single string from section, but skip whitespace on start.\n\n :type section: ConfigVariableSection\n :param replace_ignored: Specify replaced text for whitespace\n\n Allows normalizing with replace ignored sections.\n Is intended to strip possible comments between parts.\n \"\"\"\n s = ''\n nonwhite = None\n for v in self.values:\n if nonwhite is None:\n if v.type() != self.TYPE_IGNORED:\n nonwhite = v\n s += v.serialize()\n elif replace_ignored is not None and v.type() == self.TYPE_IGNORED:\n s += replace_ignored\n else:\n s += v.serialize()\n return s\n\n\nclass ModifyState(object):\n \"\"\"Object keeping state of modifications when walking configuration file statements.\n\n It would keep modified configuration file and position of last found statement.\n \"\"\"\n\n def __init__(self):\n self.value = ''\n self.lastpos = 0\n\n def append_before(self, section):\n \"\"\"Appends content from last seen section to beginning of current one.\n\n It adds also whitespace on beginning of statement,\n which is usually not interesting for any changes.\n\n :type section: ConfigVariableSection\n \"\"\"\n\n end = section.start\n first = section.values[0]\n if first.type() == first.TYPE_IGNORED:\n end = first.end\n cfg = section.config.buffer\n self.value += cfg[self.lastpos:end+1]\n self.lastpos = end+1\n\n def move_after(self, section):\n \"\"\"Set position to the end of section.\"\"\"\n self.lastpos = section.end+1\n\n def finish(self, section):\n \"\"\"Append remaining part of file to modified state.\"\"\"\n if self.lastpos < section.end:\n self.value += section.config.buffer[self.lastpos:section.end+1]\n self.lastpos = section.end\n\n def content(self):\n \"\"\"Get content of (modified) section.\n\n Would be valid after finish() was called.\n \"\"\"\n return self.value\n\n @staticmethod\n def callback_comment_out(section, state):\n \"\"\"parser.walk callback for commenting out the section.\"\"\"\n state.append_before(section)\n state.value += '/* ' + section.serialize_skip(' ') + ' */'\n state.move_after(section)\n\n @staticmethod\n def callback_remove(section, state):\n \"\"\"parser.walk callback for skipping a section.\"\"\"\n state.append_before(section)\n state.move_after(section)\n\n\n# Main parser class\nclass IscConfigParser(object):\n \"\"\"Parser file with support of included files.\n\n Reads ISC BIND configuration file and tries to skip commented blocks, nested sections and similar stuff.\n Imitates what isccfg does in native code, but without any use of native code.\n \"\"\"\n\n CONFIG_FILE = \"/etc/named.conf\"\n FILES_TO_CHECK = []\n\n CHAR_DELIM = \";\" # Must be single character\n CHAR_CLOSING = CHAR_DELIM + \"})]\"\n CHAR_CLOSING_WHITESPACE = CHAR_CLOSING + string.whitespace\n CHAR_KEYWORD = string.ascii_letters + string.digits + '-_.:'\n CHAR_STR_OPEN = '\"'\n\n def __init__(self, config=None):\n \"\"\"Construct parser.\n\n :param config: path to file or already loaded ConfigFile instance\n\n Initialize contents from path to real config or already loaded ConfigFile class.\n \"\"\"\n if isinstance(config, ConfigFile):\n self.FILES_TO_CHECK = [config]\n self.load_included_files()\n elif config is not None:\n self.load_config(config)\n\n #\n # function for parsing of config files\n #\n def is_comment_start(self, istr, index=0):\n if istr[index] == \"#\" or (\n index+1 < len(istr) and istr[index:index+2] in [\"//\", \"/*\"]):\n return True\n return False\n\n def _find_end_of_comment(self, istr, index=0):\n \"\"\"Returns index where the comment ends.\n\n :param istr: input string\n :param index: begin search from the index; from the start by default\n\n Support usual comments till the end of line (//, #) and block comment\n like (/* comment */). In case that index is outside of the string or end\n of the comment is not found, return -1.\n\n In case of block comment, returned index is position of slash after star.\n \"\"\"\n length = len(istr)\n\n if index >= length or index < 0:\n return -1\n\n if istr[index] == \"#\" or istr[index:].startswith(\"//\"):\n return istr.find(\"\\n\", index)\n\n if index+2 < length and istr[index:index+2] == \"/*\":\n res = istr.find(\"*/\", index+2)\n if res != -1:\n return res + 1\n\n return -1\n\n def is_opening_char(self, c):\n return c in \"\\\"'{([\"\n\n def _remove_comments(self, istr, space_replace=False):\n \"\"\"Removes all comments from the given string.\n\n :param istr: input string\n :param space_replace When true, replace comments with spaces. Skip them by default.\n :return: istr without comments\n \"\"\"\n\n ostr = \"\"\n\n length = len(istr)\n index = 0\n\n while index < length:\n if self.is_comment_start(istr, index):\n index = self._find_end_of_comment(istr, index)\n if index == -1:\n index = length\n if space_replace:\n ostr = ostr.ljust(index)\n if index < length and istr[index] == \"\\n\":\n ostr += \"\\n\"\n elif istr[index] in self.CHAR_STR_OPEN:\n end_str = self._find_closing_char(istr, index)\n if end_str == -1:\n ostr += istr[index:]\n break\n ostr += istr[index:end_str+1]\n index = end_str\n else:\n ostr += istr[index]\n index += 1\n\n return ostr\n\n def _replace_comments(self, istr):\n \"\"\"Replaces all comments by spaces in the given string.\n\n :param istr: input string\n :returns: string of the same length with comments replaced\n \"\"\"\n return self._remove_comments(istr, True)\n\n def find_next_token(self, istr, index=0, end_index=-1, end_report=False):\n \"\"\"\n Return index of another interesting token or -1 when there is not next.\n\n :param istr: input string\n :param index: begin search from the index; from the start by default\n :param end_index: stop searching at the end_index or end of the string\n\n In case that initial index contains already some token, skip to another.\n But when searching starts on whitespace or beginning of the comment,\n choose the first one.\n\n The function would be confusing in case of brackets, but content between\n brackets is not evaluated as new tokens.\n E.g.:\n\n \"find { me };\" : 5\n \" me\" : 1\n \"find /* me */ me \" : 13\n \"/* me */ me\" : 9\n \"me;\" : 2\n \"{ me }; me\" : 6\n \"{ me } me\" : 8\n \"me } me\" : 3\n \"}} me\" : 1\n \"me\" : -1\n \"{ me } \" : -1\n \"\"\"\n length = len(istr)\n if length < end_index or end_index < 0:\n end_index = length\n\n if index >= end_index or index < 0:\n return -1\n\n # skip to the end of the current token\n if istr[index] == '\\\\':\n index += 2\n elif self.is_opening_char(istr[index]):\n index = self._find_closing_char(istr, index, end_index)\n if index != -1:\n index += 1\n elif self.is_comment_start(istr, index):\n index = self._find_end_of_comment(istr, index)\n if index != -1:\n index += 1\n elif istr[index] not in self.CHAR_CLOSING_WHITESPACE:\n # so we have to skip to the end of the current token\n index += 1\n while index < end_index:\n if (istr[index] in self.CHAR_CLOSING_WHITESPACE\n or self.is_comment_start(istr, index)\n or self.is_opening_char(istr[index])):\n break\n index += 1\n elif end_report and istr[index] in self.CHAR_DELIM:\n # Found end of statement. Report delimiter\n return index\n elif istr[index] in self.CHAR_CLOSING:\n index += 1\n\n # find next token (can be already under the current index)\n while 0 <= index < end_index:\n if istr[index] == '\\\\':\n index += 2\n continue\n if self.is_comment_start(istr, index):\n index = self._find_end_of_comment(istr, index)\n if index == -1:\n break\n elif self.is_opening_char(istr[index]) or istr[index] not in string.whitespace:\n return index\n index += 1\n return -1\n\n def _find_closing_char(self, istr, index=0, end_index=-1):\n \"\"\"\n Returns index of equivalent closing character.\n\n :param istr: input string\n\n It's similar to the \"find\" method that returns index of the first character\n of the searched character or -1. But in this function the corresponding\n closing character is looked up, ignoring characters inside strings\n and comments. E.g. for\n \"(hello (world) /* ) */ ), he would say\"\n index of the third \")\" is returned.\n \"\"\"\n important_chars = { # TODO: should be that rather global var?\n \"{\": \"}\",\n \"(\": \")\",\n \"[\": \"]\",\n \"\\\"\": \"\\\"\",\n self.CHAR_DELIM: None,\n }\n length = len(istr)\n if 0 <= end_index < length:\n length = end_index\n\n if length < 2:\n return -1\n\n if index >= length or index < 0:\n return -1\n\n closing_char = important_chars.get(istr[index], self.CHAR_DELIM)\n if closing_char is None:\n return -1\n\n isString = istr[index] in \"\\\"\"\n index += 1\n curr_c = \"\"\n while index < length:\n curr_c = istr[index]\n if curr_c == '//':\n index += 2\n elif self.is_comment_start(istr, index) and not isString:\n index = self._find_end_of_comment(istr, index)\n if index == -1:\n return -1\n elif not isString and self.is_opening_char(curr_c):\n deep_close = self._find_closing_char(istr[index:])\n if deep_close == -1:\n break\n index += deep_close\n elif curr_c == closing_char:\n if curr_c == self.CHAR_DELIM:\n index -= 1\n return index\n index += 1\n\n return -1\n\n def find_key(self, istr, key, index=0, end_index=-1, only_first=True):\n \"\"\"\n Return index of the key or -1.\n\n :param istr: input string; it could be whole file or content of a section\n :param key: name of the searched key in the current scope\n :param index: start searching from the index\n :param end_index: stop searching at the end_index or end of the string\n\n Function is not recursive. Searched key has to be in the current scope.\n Attention:\n\n In case that input string contains data outside of section by mistake,\n the closing character is ignored and the key outside of scope could be\n found. Example of such wrong input could be:\n key1 \"val\"\n key2 { key-ignored \"val-ignored\" };\n };\n controls { ... };\n In this case, the key \"controls\" is outside of original scope. But for this\n cases you can set end_index to value, where searching should end. In case\n you set end_index higher then length of the string, end_index will be\n automatically corrected to the end of the input string.\n \"\"\"\n length = len(istr)\n keylen = len(key)\n\n if length < end_index or end_index < 0:\n end_index = length\n\n if index >= end_index or index < 0:\n return -1\n\n while index != -1:\n if istr.startswith(key, index):\n if index+keylen < end_index and istr[index+keylen] not in self.CHAR_KEYWORD:\n # key has been found\n return index\n\n while not only_first and index != -1 and istr[index] != self.CHAR_DELIM:\n index = self.find_next_token(istr, index)\n index = self.find_next_token(istr, index)\n\n return -1\n\n def find_next_key(self, cfg, index=0, end_index=-1, end_report=False):\n \"\"\"Modernized variant of find_key.\n\n :type cfg: ConfigFile\n :param index: Where to start search\n :rtype: ConfigSection\n\n Searches for first place of bare keyword, without quotes or block.\n \"\"\"\n istr = cfg.buffer\n length = len(istr)\n\n if length < end_index or end_index < 0:\n end_index = length\n\n if index > end_index or index < 0:\n raise IndexError(\"Invalid cfg index\")\n\n while index != -1:\n keystart = index\n while index < end_index and istr[index] in self.CHAR_KEYWORD:\n index += 1\n\n if index >= end_index:\n break\n\n if keystart < index <= end_index and istr[index] not in self.CHAR_KEYWORD:\n # key has been found\n return ConfigSection(cfg, istr[keystart:index], keystart, index-1)\n if istr[index] in self.CHAR_DELIM:\n return ConfigSection(cfg, istr[index], index, index)\n\n index = self.find_next_token(istr, index, end_index, end_report)\n\n return None\n\n def find_next_val(self, cfg, key=None, index=0, end_index=-1, end_report=False):\n \"\"\"Find following token.\n\n :param cfg: input token\n :type cfg: ConfigFile\n :returns: ConfigSection object or None\n :rtype: ConfigSection\n \"\"\"\n start = self.find_next_token(cfg.buffer, index, end_index, end_report)\n if start < 0:\n return None\n if end_index < 0:\n end_index = len(cfg.buffer)\n # remains = cfg.buffer[start:end_index]\n if not self.is_opening_char(cfg.buffer[start]):\n return self.find_next_key(cfg, start, end_index, end_report)\n\n end = self._find_closing_char(cfg.buffer, start, end_index)\n if end == -1 or (0 < end_index < end):\n return None\n return ConfigSection(cfg, key, start, end)\n\n def find_val(self, cfg, key, index=0, end_index=-1):\n \"\"\"Find value of keyword specified by key.\n\n :param cfg: ConfigFile\n :param key: name of searched key (str)\n :param index: start of search in cfg (int)\n :param end_index: end of search in cfg (int)\n :returns: ConfigSection object or None\n :rtype: ConfigSection\n \"\"\"\n if not isinstance(cfg, ConfigFile):\n raise TypeError(\"cfg must be ConfigFile parameter\")\n\n if end_index < 0:\n end_index = len(cfg.buffer)\n key_start = self.find_key(cfg.buffer, key, index, end_index)\n if key_start < 0 or key_start+len(key) >= end_index:\n return None\n return self.find_next_val(cfg, key, key_start+len(key), end_index)\n\n def find_val_section(self, section, key):\n \"\"\"Find value of keyword in section.\n\n :param section: section object returned from find_val\n\n Section is object found by previous find_val call.\n \"\"\"\n if not isinstance(section, ConfigSection):\n raise TypeError(\"section must be ConfigSection\")\n return self.find_val(section.config, key, section.start+1, section.end)\n\n def find_values(self, section, key):\n \"\"\"Find key in section and list variable parameters.\n\n :param key: Name to statement to find\n :returns: List of all found values in form of ConfigSection. First is key itself.\n\n Returns all sections of keyname. They can be mix of \"quoted strings\", {nested blocks}\n or just bare keywords. First key is section of key itself, final section includes ';'.\n Makes it possible to comment out whole section including terminal character.\n \"\"\"\n\n if isinstance(section, ConfigFile):\n cfg = section\n index = 0\n end_index = len(cfg.buffer)\n elif isinstance(section, ConfigSection):\n cfg = section.config\n index = section.start+1\n end_index = section.end\n if end_index > index:\n end_index -= 1\n else:\n raise TypeError('Unexpected type')\n\n if key is None:\n v = self.find_next_key(cfg, index, end_index)\n else:\n key_start = self.find_key(cfg.buffer, key, index, end_index)\n key_end = key_start+len(key)-1\n if key_start < 0 or key_end >= end_index:\n return None\n # First value is always just keyword\n v = ConfigSection(cfg, key, key_start, key_end)\n\n values = []\n while isinstance(v, ConfigSection):\n values.append(v)\n if v.value() == self.CHAR_DELIM:\n break\n v = self.find_next_val(cfg, key, v.end+1, end_index, end_report=True)\n return values\n\n def find(self, key_string, cfg=None, delimiter='.'):\n \"\"\"Helper searching for values under requested sections.\n\n Search for statement under some sections. It is inspired by xpath style paths,\n but searches section in bind configuration.\n\n :param key_string: keywords delimited by dots. For example options.dnssec-lookaside\n :type key_string: str\n :param cfg: Search only in given config file\n :type cfg: ConfigFile\n :returns: list of ConfigVariableSection\n \"\"\"\n keys = key_string.split(delimiter)\n if cfg is not None:\n return self._find_values_simple(cfg.root_section(), keys)\n\n items = []\n for cfgs in self.FILES_TO_CHECK:\n items.extend(self._find_values_simple(cfgs.root_section(), keys))\n return items\n\n def is_terminal(self, section):\n \"\"\".Returns true when section is final character of one statement.\"\"\"\n return section.value() in self.CHAR_DELIM\n\n def _variable_section(self, vl, parent=None, offset=1):\n \"\"\"Create ConfigVariableSection with a name and optionally class.\n\n Intended for view and zone in bind.\n :returns: ConfigVariableSection\n \"\"\"\n vname = self._list_value(vl, 1).invalue()\n vclass = None\n v = self._list_value(vl, 2)\n if v.type() != ConfigSection.TYPE_BLOCK and self._list_value(vl, 2):\n vclass = v.value()\n return ConfigVariableSection(vl, vname, vclass, parent)\n\n def _list_value(self, vl, i):\n n = 0\n for v in vl:\n if v.type() != ConfigSection.TYPE_IGNORED:\n if n == i:\n return v\n n += 1\n raise IndexError\n\n def _find_values_simple(self, section, keys):\n found_values = []\n sect = section.copy()\n\n while sect is not None:\n vl = self.find_values(sect, keys[0])\n if vl is None:\n break\n if len(keys) <= 1:\n variable = self._variable_section(vl, section)\n found_values.append(variable)\n sect.start = variable.end+1\n else:\n for v in vl:\n if v.type() == ConfigSection.TYPE_BLOCK:\n vl2 = self._find_values_simple(v, keys[1:])\n if vl2 is not None:\n found_values.extend(vl2)\n sect.start = vl[-1].end+1\n\n return found_values\n\n def walk(self, section, callbacks, state=None, parent=None, start=0):\n \"\"\"Walk over section also with nested blocks.\n\n :param section: Section to iterate, usually ConfigFile.root_section()\n :param callbacks: Set of callbacks with name: f(section, state) parameters, indexed by statement name\n :param start: Offset from beginning of section\n\n Call specified actions specified in callbacks, which can react on desired statements.\n Pass state and matching section to callback.\n \"\"\"\n if start == 0 and section.type() == ConfigSection.TYPE_BLOCK:\n start = 1\n it = IscVarIterator(self, section, True, start=section.start+start)\n for statement in it:\n try:\n name = statement.var(0).value()\n if name in callbacks:\n f = callbacks[name]\n f(statement, state)\n except IndexError:\n pass\n for child in statement.values:\n if child.type() == ConfigSection.TYPE_BLOCK:\n self.walk(child, callbacks, state, parent=statement)\n return state\n\n #\n # CONFIGURATION fixes PART - END\n #\n\n def is_file_loaded(self, path=\"\"):\n \"\"\"\n Checks if the file with a given 'path' is already loaded in FILES_TO_CHECK.\n \"\"\"\n for f in self.FILES_TO_CHECK:\n if f.path == path:\n return True\n return False\n\n def new_config(self, path, parent=None):\n config = ConfigFile(path)\n self.FILES_TO_CHECK.append(config)\n return config\n\n def on_include_error(self, e):\n \"\"\"Handle IO errors on file reading.\n\n Override to create custom error handling.\"\"\"\n raise e\n\n def load_included_files(self):\n \"\"\"Add included list to parser.\n\n Finds the configuration files that are included in some configuration\n file, reads it, closes and adds into the FILES_TO_CHECK list.\n \"\"\"\n # TODO: use parser instead of regexp\n pattern = re.compile(r'include\\s*\"(.+?)\"\\s*;')\n # find includes in all files\n for ch_file in self.FILES_TO_CHECK:\n nocomments = self._remove_comments(ch_file.buffer)\n includes = re.findall(pattern, nocomments)\n for include in includes:\n # don't include already loaded files -> prevent loops\n if self.is_file_loaded(include):\n continue\n try:\n self.new_config(include)\n except IOError as e:\n self.on_include_error(ConfigParseError(e, include))\n\n def load_main_config(self):\n \"\"\"Loads main CONFIG_FILE.\"\"\"\n try:\n self.new_config(self.CONFIG_FILE)\n except IOError as e:\n raise ConfigParseError(e)\n\n def load_config(self, path=None):\n \"\"\"Loads main config file with all included files.\"\"\"\n if path is not None:\n self.CONFIG_FILE = path\n self.load_main_config()\n self.load_included_files()\n pass\n\n\nif __name__ == '__main__':\n \"\"\"Run parser to default path or path in the first argument.\n\n Additional parameters are statements or blocks to print.\n Defaults to options and zone.\n \"\"\"\n\n from sys import argv\n\n def print_cb(section, state):\n print(section)\n\n cfgpath = IscConfigParser.CONFIG_FILE\n if len(argv) > 1:\n cfgpath = argv[1]\n if len(argv) > 2:\n cb = {}\n for key in argv[2:]:\n cb[key] = print_cb\n else:\n cb = {'options': print_cb, 'zone': print_cb}\n\n parser = IscConfigParser(cfgpath)\n for section in parser.FILES_TO_CHECK:\n print(\"# Walking file '{}'\".format(section.path))\n parser.walk(section.root_section(), cb)\n","repo_name":"oamg/leapp-repository","sub_path":"repos/system_upgrade/el7toel8/libraries/isccfg.py","file_name":"isccfg.py","file_ext":"py","file_size_in_byte":33065,"program_lang":"python","lang":"en","doc_type":"code","stars":37,"dataset":"github-code","pt":"15"} +{"seq_id":"15730872534","text":"# author: mofhu@github\n# A. NIT orz!\n\nncase = int(input())\n\nfor case in range(1, ncase+1):\n n, z = [int(s) for s in input().split(' ')]\n a = [int(s) for s in input().split(' ')]\n ans = 0\n for ai in a:\n t = ai | z\n if t > ans:\n ans = t\n print(f'{ans}')\n","repo_name":"organization-lab/codejam","sub_path":"codeforces/GlobalRound21/a.py","file_name":"a.py","file_ext":"py","file_size_in_byte":292,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"15"} +{"seq_id":"13277471671","text":"# -*- coding: utf-8 -*-\r\n\"\"\"\r\nCreated on Fri Nov 19 11:57:21 2021\r\n\r\n@author: guojinhe\r\n\"\"\"\r\n#import\r\nimport tkinter as tk\r\nimport cv2\r\nimport glob #img scanner\r\n\r\n##Converter\r\n\r\ndef convert(start_folder_path,end_folder_path):\r\n\r\n # img name scan\r\n dirPathPattern = start_folder_path + r'\\*.png'\r\n scan_result = glob.glob(dirPathPattern)\r\n\r\n\r\n for f in scan_result:\r\n # Load .png image\r\n img = cv2.imread(f)\r\n \r\n # Get img name(without path)\r\n f_e = [0]*(len(f)-len(start_folder_path)-5)\r\n\r\n for i in range(len(start_folder_path)+1, len(f)-4):\r\n f_e[i-len(start_folder_path)-1] = f[i]\r\n \r\n #f_e to img_name (conv to string)\r\n img_name = str(f_e[0])\r\n for i in range(1,len(f_e)):\r\n img_name += str(f_e[i])\r\n \r\n #set path to end folder\r\n f = end_folder_path + '\\\\' + img_name\r\n # Save .jpg image\r\n cv2.imwrite(f + '.jpg', img)\r\n\r\n##DoneButton funtion\r\ndef DoneButton_event():\r\n \r\n start_folder_path = var1.get()\r\n end_folder_path = var2.get()\r\n print(start_folder_path)\r\n print(end_folder_path)\r\n convert(start_folder_path,end_folder_path)\r\n tk.messagebox.showinfo('message',\"Success\")\r\n\"\"\"if(start_folder_path == 'awa'):\r\n tk.messagebox.showinfo('message',\"Success\")\r\n else:\r\n tk.messagebox.showinfo('message',\"SomeThingWrong\")\"\"\"\r\n \r\n##background\r\nroot = tk.Tk()\r\nroot.title('ImageFormatConverter')\r\nroot.geometry('400x300')\r\n\r\n##text\r\nToplabel_1 = tk.Label(root, text='ImageFormatConverter',font=('Arial', 18))\r\nToplabel_1.pack()\r\n\r\nToplabel_2 = tk.Label(root, text='made by PotatoCraft',font=('Arial', 9))\r\nToplabel_2.pack()\r\n\r\n##input start folder and end folder \r\nvar1 = tk.StringVar()\r\nvar2 = tk.StringVar()\r\n\r\nInputlabel_1 = tk.Label(root, text='Picture(.png) from:',font=('Arial', 12))\r\nInputlabel_1.pack()\r\nPicFrom = tk.Entry(root, textvariable=var1)\r\nPicFrom.pack()\r\n\r\nInputlabel_2 = tk.Label(root, text='Picture(.jpg) to:',font=('Arial', 12))\r\nInputlabel_2.pack()\r\nPicTo = tk.Entry(root, textvariable=var2 )\r\nPicTo.pack()\r\n\r\n\r\n\r\n##setting done button\r\nDoneButton= tk.Button(root, text='button', command=DoneButton_event)\r\nDoneButton.pack()\r\n\r\nroot.mainloop()","repo_name":"guojinhe/ImageConverter","sub_path":"main/0.x/0.1/python/ImageConverter_0.1.py","file_name":"ImageConverter_0.1.py","file_ext":"py","file_size_in_byte":2248,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"15"} +{"seq_id":"16431273210","text":"import cv2\n\nstream = cv2.VideoCapture(0)\nstream.set(3, 640)\nstream.set(4, 480)\nstream.set(10, 100)\n\nwhile True:\n success, img = stream.read()\n cv2.imshow(\"Video\", img)\n if cv2.waitKey(1) & 0xFF ==ord('q'):\n break\n\n\n\n","repo_name":"Kid67/OpencvPython","sub_path":"chapter1.py","file_name":"chapter1.py","file_ext":"py","file_size_in_byte":232,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"15"} +{"seq_id":"8262934883","text":"from django.core.cache import cache\n\nCACHE_KEY_FUNC_GET_USER_INFOS_BY_IDS = {\n\t'cache_prefix': 'user_infos_by_ids.%s',\n\t'expiry_time': 10 * 60,\n\t'cache_key_converter': lambda prefix, user_ids: prefix % user_ids\n}\n\ndef simple_cache_data(cache_key_converter, cache_prefix, expiry_time=60):\n\tdef _cache_data(func):\n\t\tdef _func(*args, **kwargs):\n\t\t\tcache_key = cache_key_converter(cache_prefix, *args)\n\t\t\tdata = cache.get(cache_key)\n\t\t\tforce_query = kwargs.get(\"force_query\", False)\n\t\t\tif force_query or not data:\n\t\t\t\tdata = func(*args)\n\t\t\t\tcache.set(cache_key, data, expiry_time)\n\t\t\treturn data\n\t\treturn _func\n\treturn _cache_data\n","repo_name":"nmtien2007/TechBaseVN","sub_path":"TechBaseVN_Lib/manager/cache_manager.py","file_name":"cache_manager.py","file_ext":"py","file_size_in_byte":627,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"15"} +{"seq_id":"17631053753","text":"from __future__ import annotations\n\nimport argparse\nfrom pathlib import Path\nfrom typing import Callable\n\nfrom rich.console import Console\n\nfrom options import defaults\n\nconsole = Console()\n\n\n# def is_dicomdir(path: Path) -> bool:\n# \"\"\"A directory is a dicom if it contains a 'DICOMDIR' file.\"\"\"\n# return \"DICOMDIR\" in [item.name for item in path.iterdir()]\n#\n#\n# def is_original_dir(path: Path) -> bool:\n# \"\"\"A directory is a dicom if it contains a 'DICOMDIR' file.\"\"\"\n# return all(\n# f\"original_phase_{phase}.nii.gz\" in [item.name for item in path.iterdir()]\n# for phase in [\"b\", \"a\", \"v\", \"t\"]\n# )\n#\n#\n# def is_case_dir(case_path: Path, segmented: bool):\n# if not case_path.is_dir():\n# return False\n# files = [path.name for path in case_path.iterdir()]\n# case_respect_segmented = (\n# (\"segmentation.nii.gz\" in files)\n# or not segmented\n# )\n# case_respect_multiphase = all(\n# f\"registered_phase_{phase}.nii.gz\" in files\n# for phase in [\"b\", \"a\", \"v\", \"t\"]\n# )\n# return case_respect_multiphase and case_respect_segmented\n#\n#\n# def discover_dicomdirs(path: Path, relative_to_path: Path | None = None) -> list[Path]:\n# \"\"\"Collects paths of all dicom sub-folders.\"\"\"\n# if relative_to_path is None:\n# relative_to_path = path\n# if path.is_dir():\n# if is_dicomdir(path):\n# return [path.relative_to(relative_to_path)]\n# else:\n# return [\n# subdir\n# for subpath in path.iterdir()\n# for subdir in discover_dicomdirs(subpath, relative_to_path)\n# ]\n# else:\n# return []\n#\n#\n# def discover_original_dirs(path: Path, relative_to_path: Path | None = None) -> list[Path]:\n# \"\"\"Collects paths of all sub-folders containing original nifti.\"\"\"\n# if relative_to_path is None:\n# relative_to_path = path\n# if path.is_dir():\n# if is_original_dir(path):\n# return [path.relative_to(relative_to_path)]\n# else:\n# return [\n# subdir\n# for subpath in path.iterdir()\n# for subdir in discover_original_dirs(subpath, relative_to_path)\n# ]\n# else:\n# return []\n#\n#\n# def discover_cases_dirs(path: Path, segmented: bool, relative_to_path: Path | None = None) -> list[Path]:\n# \"\"\"Collects paths of all sub-folders containing cases.\"\"\"\n# if relative_to_path is None:\n# relative_to_path = path\n# if path.is_dir():\n# if is_case_dir(path, segmented):\n# return [path.relative_to(relative_to_path)]\n# else:\n# return [\n# subdir\n# for subpath in path.iterdir()\n# for subdir in discover_cases_dirs(subpath, segmented, relative_to_path)\n# ]\n# else:\n# return []\n#\n#\n# def is_case(case_path: Path):\n# if case_path.is_dir():\n# files = [file_path.name for file_path in case_path.iterdir()]\n# return all(\n# f\"registered_phase_{phase}.nii.gz\" in files\n# for phase in [\"b\", \"a\", \"v\", \"t\"]\n# )\n# else:\n# return False\n#\n#\n# def is_segmented_case(case_path: Path):\n# if case_path.is_dir():\n# files = [file_path.name for file_path in case_path.iterdir()]\n# case_respect_segmented = \"segmentation.nii.gz\" in files\n# case_respect_multiphase = all(\n# f\"registered_phase_{phase}.nii.gz\" in files\n# for phase in [\"b\", \"a\", \"v\", \"t\"]\n# )\n# return case_respect_multiphase and case_respect_segmented\n# else:\n# return False\n#\n#\n# def is_windowed_case(case_path: Path):\n# if case_path.is_dir():\n# files = [file_path.name for file_path in case_path.iterdir()]\n# case_respect_multiphase = all(\n# f\"registered_phase_{phase}.nii.gz\" in files\n# for phase in [\"b\", \"a\", \"v\", \"t\"]\n# )\n# case_respect_windowed = \"zwindow.pt\" in files\n# return case_respect_multiphase and case_respect_windowed\n# else:\n# return False\n#\n#\n# def is_segmented_windowed_case(case_path: Path):\n# if case_path.is_dir():\n# files = [file_path.name for file_path in case_path.iterdir()]\n# case_respect_segmented = \"segmentation.nii.gz\" in files\n# case_respect_multiphase = all(\n# f\"registered_phase_{phase}.nii.gz\" in files\n# for phase in [\"b\", \"a\", \"v\", \"t\"]\n# )\n# case_respect_windowed = \"zwindow.pt\" in files\n# return case_respect_multiphase and case_respect_segmented and case_respect_windowed\n# else:\n# return False\n\n\ndef get_criterion(\n dicom: bool = False,\n original: bool = False,\n registered: bool = False,\n segmented: bool = False,\n predicted: bool = False,\n windowed: bool = False\n) -> Callable[[Path], bool]:\n \"\"\"Make a callable to identify folders.\"\"\"\n def criterion(case_path: Path) -> bool:\n if case_path.is_dir():\n files = [file_path.name for file_path in case_path.iterdir()]\n\n # Every condition is checked only if specified\n is_dicom = not dicom or \"DICOMDIR\" in files\n is_original = not original or all(\n f\"original_phase_{phase}.nii.gz\" in files\n for phase in [\"b\", \"a\", \"v\", \"t\"]\n )\n is_registered = not registered or all(\n f\"registered_phase_{phase}.nii.gz\" in files\n for phase in [\"b\", \"a\", \"v\", \"t\"]\n )\n is_segmented = not segmented or \"segmentation.nii.gz\" in files\n is_predicted = not predicted or \"prediction.nii.gz\" in files\n is_windowed = not windowed or \"zwindow.pt\" in files\n return is_dicom and is_original and is_registered and is_segmented and is_predicted and is_windowed\n else:\n return False\n\n return criterion\n\n\ndef discover(path: Path | str, select_dir: Callable) -> list[Path]:\n \"\"\"Recursively list dirs in `path` that respect `select_dir` criterion.\"\"\"\n path = Path(path).resolve()\n unexplored_paths = [path]\n selected_paths = []\n while len(unexplored_paths) > 0:\n new_path = unexplored_paths.pop(0)\n if select_dir(new_path):\n selected_paths.append(new_path.resolve().relative_to(path))\n elif new_path.is_dir():\n unexplored_paths.extend(new_path.iterdir())\n return selected_paths\n\n\ndef get_args():\n parser = argparse.ArgumentParser()\n return dict(defaults, **vars(parser.parse_args()))\n\n\nif __name__ == \"__main__\":\n opts = get_args()\n console.print(f\"In the given path ({opts['sources']}) there are these dicom dirs:\")\n for path in discover(opts[\"sources\"], get_criterion(dicom=True)):\n console.print(\" \", Path(\"...\") / path)\n","repo_name":"yamatteo/liver","sub_path":"path_explorer.py","file_name":"path_explorer.py","file_ext":"py","file_size_in_byte":6924,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"15"} +{"seq_id":"13122384915","text":"from django.conf.urls import patterns, include, url\nfrom notebookapp.views import *\n# Uncomment the next two lines to enable the admin:\nfrom django.contrib import admin\nfrom django.views.generic import DetailView, ListView, UpdateView\nadmin.autodiscover()\nfrom notebookapp.views import APIBrandList, APIBrandDetail, APIModelList, APIModelDetail, APIComponentList, APIComponentDetail, APISpecificationList, APISpecificationDetail\nfrom django.conf.urls.defaults import *\n\nurlpatterns = patterns('',\n # Examples:\n # url(r'^$', 'notebookcompare.views.home', name='home'),\n # url(r'^notebookcompare/', include('notebookcompare.foo.urls')),\n\n # Uncomment the admin/doc line below to enable admin documentation:\n # url(r'^admin/doc/', include('django.contrib.admindocs.urls')),\n\n # Uncomment the next line to enable the admin:\n url(r'^admin/', include(admin.site.urls)),\n url(r'^$', mainpage, name='home'),\n\t#BRANDS\n url(r'^brands/$', brands , name='brands'),\n url(r'^brands/view/(?P\\w+)/$', brand_detail , name='brand detail'),\n url(r'^brands/view/(?P\\w+)/models/$', brand_models , name='brand models'),\n url(r'^brands/add/$', brands_add , name='add brand'),\n\n\n\t#MODELS\n url(r'^models/$', models , name='models'),\n url(r'^models/view/(?P\\d+)/$', model_detail , name='model detail'),\n url(r'^models/add/$', model_add , name='add model'),\n url(r'^models/edit/(?P\\d+)/$',UpdateView.as_view(model = Model,template_name = 'add_form_user.html',form_class = ModelFormEdit, success_url=\"/userpanel/my-laptops/\"),name='laptop edit'),\n url(r'^models/delete/(?P\\d+)/$', models_delete , name='delete model'),\n\n\t#COMPONENTS\n url(r'^components/$', components , name='components'),\n url(r'^components/view/(?P\\d+)/$', component_detail , name='Component Detail'),\n url(r'^components/add/$', components_add , name='add component'),\n url(r'^components/edit/(?P\\d+)/$',UpdateView.as_view(model = Component,template_name = 'add_form.html',form_class = EditComponent,success_url=\"/components/\"),name='Component Edit'),\n\n\n\t#Specifications\n url(r'^specifications/$', specifications_detail_all , name='Specification Detail all'),\n url(r'^specifications/view/(?P\\w+)/$', specifications_list , name='specifications list'),\n url(r'^specifications/add/$', specifications_add , name='add specification'),\n url(r'^specifications/edit/(?P\\d+)/$',UpdateView.as_view(model = Specification,template_name = 'add_form.html',form_class = EditSpecification,success_url=\"/specifications/\"),name='Specifications Edit'),\n\n\t#login user\n\n\n url(r'^login/$', 'django.contrib.auth.views.login'),\n url(r'^logout/$', logout_view),\n url(r'^register/$',register),\n url(r'^userpanel/$',userpanel),\n url(r'^userpanel/my-reviews/$',myreviews),\n url(r'^userpanel/my-laptops/$',mylaptops),\n\n\t#web 2.0\n#reviews\n url(r'^review/$', review , name='review',),\n url(r'^review/(?P\\d)/view/$', review_model_view , name='view list of reviews'),\n url(r'^review/view/(?P\\d)/$', review_view , name='view review'),\n url(r'^review/(?P\\d)/add/$', review_model_add , name='review model'),\n url(r'^review/edit/(?P\\d+)/$',UpdateView.as_view(model = Review,template_name = 'add_form_user.html',form_class = ReviewFormEdit, success_url=\"/userpanel/my-reviews/\"),name='review edit'),\n url(r'^review/delete/(?P\\d+)/$', review_delete , name='delete review'),\n\n)\n\n#RESTful\nurlpatterns += patterns('',\n url(r'^api/brands/$', APIBrandList.as_view(), name='brand-list'),\n url(r'^api/brands/(?P\\d+)/$', APIBrandDetail.as_view(), name='brand-detail'),\n url(r'^api/models/$', APIModelList.as_view(), name='model-list'),\n url(r'^api/models/(?P\\d+)/$', APIModelDetail.as_view(), name='model-detail'),\n url(r'^api/components/$', APIComponentList.as_view(), name='component-list'),\n url(r'^api/components/(?P\\d+)/$', APIComponentDetail.as_view(), name='component-detail'),\n url(r'^api/specifications/$', APISpecificationList.as_view(), name='specification-list'),\n url(r'^api/specifications/(?P\\d+)/$', APISpecificationDetail.as_view(), name='specification-detail'),\n)\n\n\n\n","repo_name":"eduardmiro/notebookcompare","sub_path":"notebookcompare/notebookcompare/urls.py","file_name":"urls.py","file_ext":"py","file_size_in_byte":4224,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"15"} +{"seq_id":"71065608331","text":"#!/usr/bin/python3\n# -*- coding:utf-8 -*-\n\"\"\"\n@author: tianwen\n@file: 持续输入要加密的字符串.py\n@time: 2020/8/28 13:56\n@desc: 持续输入要加密的字符串\n\"\"\"\n# 导入加密算法\nimport hashlib\ncount = 0\nloop = 0\n\nwhile count == 0:\n key = input(\"请输入要加密的md5:\")\n # 初始化加密模板\n input_name = hashlib.md5()\n # 添加要加密的字节\n input_name.update(key.encode(\"utf-8\"))\n # 进行加密\n m = input_name.hexdigest()\n loop += 1\n print(\"第\", loop, \"次:\\n\", key, \" ----> \", m)\n print(\"-\" * 30)\n\n","repo_name":"Hadoop-redis/TestMysql","sub_path":"加密/md5/持续输入要加密的字符串.py","file_name":"持续输入要加密的字符串.py","file_ext":"py","file_size_in_byte":566,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"15"} +{"seq_id":"75165098251","text":"import re\n\n\ndef read_file():\n sensors = tuple()\n beacons = tuple()\n min_x = 0\n max_x = 0\n min_y = 0\n max_y = 0\n with open(\"app/days/day15/input.txt\", \"r\") as file:\n for line in file:\n coordinates = re.findall(r\"(\\-*[0-9]+)\", line.strip())\n sensor_x = int(coordinates[0])\n sensor_y = int(coordinates[1])\n beacon_x = int(coordinates[2])\n beacon_y = int(coordinates[3])\n if max(sensor_y, beacon_y) > max_y:\n max_y = max(sensor_y, beacon_y)\n if min(sensor_y, beacon_y) < min_y:\n min_y = min(sensor_y, beacon_y)\n if max(sensor_x, beacon_x) > max_x:\n max_x = max(sensor_x, beacon_x)\n if min(sensor_x, beacon_x) < min_x:\n min_x = min(sensor_x, beacon_x)\n sensors = sensors + ((sensor_x, sensor_y),)\n beacons = beacons + ((beacon_x, beacon_y),)\n return sensors, beacons, [min_x, max_x, min_y, max_y]\n\n\ndef calculate_distance(sensor: tuple[int, int], beacon: tuple[int, int]):\n return abs(beacon[0] - sensor[0]) + abs(beacon[1] - sensor[1])\n\n\ndef calculate_edges(sensor: tuple[int, int], distance: int):\n sensor_x = sensor[0]\n sensor_y = sensor[1]\n edge: list[tuple[int, int]] = []\n for x in range(distance + 1):\n y = distance + 1 - x\n edge.append((sensor_x + x, sensor_y + y))\n edge.append((sensor_x - x, sensor_y + y))\n edge.append((sensor_x + x, sensor_y - y))\n edge.append((sensor_x - x, sensor_y - y))\n return tuple(edge)\n\n\ndef intersection(lst1, lst2):\n return list(set(lst1) & set(lst2))\n\n\ndef first_part():\n sensors: tuple[tuple[int, int]]\n beacons: tuple[tuple[int, int]]\n min_x: int\n max_x: int\n min_y: int\n max_y: int\n target_line = 2000000\n # target_line = 10\n (sensors, beacons, [min_x, max_x, min_y, max_y]) = read_file()\n distances = []\n unique_beacons = tuple(beacon for beacon in set(beacons))\n for index, sensor in enumerate(sensors):\n sensor_beacon_distance = calculate_distance(sensor, beacons[index])\n distances.append(sensor_beacon_distance)\n tot = 0\n j = target_line\n sensors_beacons = sum([1 for sensor in sensors if sensor[1] == j]) + sum(\n [1 for beacon in unique_beacons if beacon[1] == j])\n for i in range(min_x, max_x + 1):\n max_distance = -1\n for sensor_index, sensor in enumerate(sensors):\n distance = distances[sensor_index] - calculate_distance(sensor, (i, j))\n if distance > max_distance:\n max_distance = distance\n if max_distance >= 0:\n if i == min_x or i == max_x:\n tot += 1 + max_distance\n else:\n tot += 1\n tot -= sensors_beacons\n return tot\n\n\ndef second_part():\n sensors: tuple[tuple[int, int]]\n beacons: tuple[tuple[int, int]]\n min_x: int\n max_x: int\n min_y: int\n max_y: int\n allowed_min_x = 0\n allowed_max_x = 4000000\n # allowed_max_x = 20\n allowed_min_y = 0\n allowed_max_y = 4000000\n # allowed_max_y = 20\n (sensors, beacons, [min_x, max_x, min_y, max_y]) = read_file()\n distances = []\n edges = []\n intersections = []\n for index, sensor in enumerate(sensors):\n sensor_beacon_distance = calculate_distance(sensor, beacons[index])\n distances.append(sensor_beacon_distance)\n edges.append(calculate_edges(sensor, sensor_beacon_distance))\n\n for index, sensor in enumerate(sensors):\n for i in range(index + 1, len(sensors)):\n intersected = intersection(edges[index], edges[i])\n intersections.extend(intersected) if intersected else None\n\n for intersect in intersections:\n found = False\n for index, sensor in enumerate(sensors):\n if calculate_distance(sensor, intersect) <= distances[index]:\n found = False\n break\n else:\n found = True\n continue\n if found:\n if (allowed_min_x <= intersect[0] <= allowed_max_x and\n allowed_min_y <= intersect[1] <= allowed_max_y):\n return intersect[0] * 4000000 + intersect[1]\n","repo_name":"Diffeomorphisme/AOC-22","sub_path":"app/days/day15/day15.py","file_name":"day15.py","file_ext":"py","file_size_in_byte":4228,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"15"} +{"seq_id":"43761132708","text":"# Name: Jack Robins\n# Contact: jacko8967@gmail.com\n# Version: 1.0\n\n\n# assings the user's input to strings\nname = input(\"Enter your name: \")\nreg = input(\"Enter your car's registration number: \")\ncarColor = input(\"Enter the color of your car: \")\n\n# prints the message to ask users for input\nprint()\n\n# the function to print each statement on new line\nline = \"\\n\"\n\n# print the users input to statements in an output\nprint(\"Your name is: \", name, line, \"Your car's registration number is: \", reg, line, \"The color of your car is: \", carColor, sep=\"\")","repo_name":"jacko8967/python2021","sub_path":"Work/Tasks/HO3/Input01.py","file_name":"Input01.py","file_ext":"py","file_size_in_byte":546,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"15"} +{"seq_id":"6507992431","text":"import os\nimport argparse\nimport logging\nimport numpy as np\nimport torch\nimport torch.nn as nn\nfrom torch.utils.data import DataLoader\nimport torchvision.datasets as datasets\nimport torchvision.transforms as transforms\nfrom torch.autograd import grad, Variable\nimport time\nimport copy\nfrom model.PDE_solver import EntireNet, PDE_solver\nfrom utils.utils import RunningAverageMeter, Flatten, learning_rate_with_decay, one_hot, count_parameters, norm, norm_\nfrom data_loader import get_mnist_loaders, inf_generator\nimport torchvision\nimport pandas as pd\n\n\nparser = argparse.ArgumentParser()\nparser.add_argument('--nepochs', type=int, default=160)\nparser.add_argument('--data_aug', type=eval, default=True, choices=[True, False])\nparser.add_argument('--lr', type=float, default=0.0003)\nparser.add_argument('--batch_size', type=int, default=128)\nparser.add_argument('--test_batch_size', type=int, default=1000)\nparser.add_argument('--save', type=str, default='./experiment1')\nparser.add_argument('--debug', action='store_true')\nparser.add_argument('--gpu', type=int, default=0)\nargs = parser.parse_args()\n\n# GPU Setting\nos.environ[\"CUDA_DEVICE_ORDER\"] = \"PCI_BUS_ID\"\nos.environ[\"CUDA_VISIBLE_DEVICES\"] = \"0\"\n\ndevice = torch.device('cuda' if torch.cuda.is_available() else 'cpu')\n\nif __name__ == '__main__':\n if not os.path.exists(args.save):\n os.makedirs(args.save)\n\n func = ConvODEF(64)\n ode = NeuralODE(func)\n model = ContinuousNeuralMNISTClassifier(ode).to(device)\n\n print(model.parameters)\n print(\"=================================================\")\n print(model_fe.parameters)\n\n # Data Loader\n img_std = 0.3081\n img_mean = 0.1307\n\n batch_size = 32\n train_loader = torch.utils.data.DataLoader(\n torchvision.datasets.MNIST(\"data/mnist\", train=True, download=True,\n transform=torchvision.transforms.Compose([\n torchvision.transforms.ToTensor(),\n torchvision.transforms.Normalize((img_mean,), (img_std,))\n ])\n ),\n batch_size=batch_size, shuffle=True\n )\n\n test_loader = torch.utils.data.DataLoader(\n torchvision.datasets.MNIST(\"data/mnist\", train=False, download=True,\n transform=torchvision.transforms.Compose([\n torchvision.transforms.ToTensor(),\n torchvision.transforms.Normalize((img_mean,), (img_std,))\n ])\n ),\n batch_size=128, shuffle=True\n )\n\n # Loss Fn\n criterion = nn.CrossEntropyLoss().to(device)\n\n # Data Loader\n train_loader, test_loader, train_eval_loader = get_mnist_loaders(args.data_aug, args.batch_size,\n args.test_batch_size)\n\n data_gen = inf_generator(train_loader)\n batches_per_epoch = len(train_loader)\n\n print(\"Train Data: {}, Test Data: {}, Train_Eval Data: {}\".format(len(train_loader), len(test_loader),\n len(train_eval_loader)))\n\n # Evaluation - Accuracy\n best_acc = 0\n batch_time_meter = RunningAverageMeter()\n f_nfe_meter = RunningAverageMeter()\n b_nfe_meter = RunningAverageMeter()\n end = time.time()\n\n # Learning Rate Scheduler\n lr_fn = learning_rate_with_decay(args, batch_denom=128, batches_per_epoch=batches_per_epoch,\n boundary_epochs=[60, 100, 140],\n decay_rates=[1, 0.1, 0.01, 0.001]\n )\n # parameter\n down_pixel_size = 6\n\n # Optimizer\n optimizer = torch.optim.Adam(model.parameters(), lr=args.lr)\n print(('Number of parameters: {}'.format(count_parameters(model))))\n\n start_time = time.time()\n\n num_items = 0\n train_losses = []\n\n for epoch in range(args.nepochs):\n # -------------------------------- Train Dataset --------------------------------\n model.train()\n criterion = nn.CrossEntropyLoss()\n print(f\"Training Epoch {epoch}...\")\n for batch_idx, (data, target) in tqdm(enumerate(train_loader), total=len(train_loader)):\n if use_cuda:\n data = data.cuda()\n target = target.cuda()\n optimizer.zero_grad()\n output = model(data)\n loss = criterion(output, target)\n loss.backward()\n optimizer.step()\n\n train_losses += [loss.item()]\n num_items += data.shape[0]\n print('Train loss: {:.5f}'.format(np.mean(train_losses)))\n\n # -------------------------------- Validation Dataset --------------------------------\n accuracy = 0.0\n num_items = 0\n\n model.eval()\n criterion = nn.CrossEntropyLoss()\n print(f\"Testing...\")\n with torch.no_grad():\n for batch_idx, (data, target) in tqdm(enumerate(test_loader), total=len(test_loader)):\n if use_cuda:\n data = data.cuda()\n target = target.cuda()\n output = model(data)\n accuracy += torch.sum(torch.argmax(output, dim=1) == target).item()\n num_items += data.shape[0]\n accuracy = accuracy * 100 / num_items\n print(\"Test Accuracy: {:.3f}%\".format(accuracy))\n\n if val_acc > best_acc:\n torch.save({'state_dict': model.state_dict(), 'args': args, 'a_00': a_00, 'a_10': a_10, 'a_20': a_20,\n 'a_30': a_30, 'a_01': a_01, 'a_11': a_11, 'a_21': a_21, 'a_31': a_31, 'a_02': a_02,\n 'a_12': a_12,\n 'a_22': a_22, 'a_32': a_32, 'b01': a_b01, 'b11': a_b11, 'b21': a_b21, 'b31': a_b31,\n 'b02': a_b02,\n 'b12': a_b12, 'b22': a_b22, 'b32': a_b32, 'rand_x_index': rand_x_index,\n 'rand_x_index2': rand_x_index2, 'rand_t_index': rand_t_index},\n os.path.join(args.save, 'model_pde_%s_normalization.pth' % args.rectifier)) #\n torch.save({'state_dict': model.state_dict(), 'args': args},\n os.path.join(args.save, 'model_pde_only_dict_%s_normalization.pth' % args.rectifier))\n best_acc = val_acc\n\n print(\"Epoch {:04d} | Train Acc {:.4f} | Test Acc {:.4f}\".format(epoch + 1, train_acc, val_acc))\n print(rand_x_index, rand_t_index, down_logits.sum(0).sum(0).sum(0).sum(0), torch.abs(u-u_init).sum(0).sum(0).sum(0).sum(0))\n\n n_epochs = 5\n test()\n train_losses = []\n for epoch in range(1, n_epochs + 1):\n train_losses += train(epoch)\n test()\n\n\n\nplt.figure(figsize=(9, 5))\nhistory = pd.DataFrame({\"loss\": train_losses})\nhistory[\"cum_data\"] = history.index * batch_size\nhistory[\"smooth_loss\"] = history.loss.ewm(halflife=10).mean()\nhistory.plot(x=\"cum_data\", y=\"smooth_loss\", figsize=(12, 5), title=\"train error\")","repo_name":"seunghyunni/NeuralPDE","sub_path":"neuralODE/test.py","file_name":"test.py","file_ext":"py","file_size_in_byte":7119,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"15"} +{"seq_id":"22100873332","text":"\n# File: um6_registers.py\n# Purpose: CHR-UM6 register/bit definitions for \"creghead\" header generator\n# Author: Tobias Simon, Ilmenau University of Technology\n#\n# This program is free software; you can redistribute it and/or modify\n# it under the terms of the GNU General Public License as published by\n# the Free Software Foundation; either version 2 of the License, or\n# (at your option) any later version.\n#\n# This program is distributed in the hope that it will be useful,\n# but WITHOUT ANY WARRANTY; without even the implied warranty of\n# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the\n# GNU General Public License for more details.\n#\n# You should have received a copy of the GNU General Public License\n# along with this program; if not, write to the Free Software\n# Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA\n\n\nprefix = 'UM6'\nregs = [\n # UM6 CONFIGURATION REGISTERS:\n ('COMM', 0x00, 32, 'communication settings',\n [\n ('BC_RATE', 8, 'packet broadcast frequency; freq = (280 / 255) * broadcast_rate + 20'),\n ('BAUD_RATE', 3, 'serial port baudrate; 000: 9600, 001: 14400, 010: 19200, 011 -> 38400, 100 -> 57600, 101 -> 115200'),\n ('GPS_BAUD', 3, 'GPS baudrate see BAUD_RATE for details'),\n None,\n ('SAT', 'detailed satellite status transmission'),\n ('SUM', 'satellite summary transmission'),\n ('VEL', 'GPS course and velocity transmission'),\n ('REL', 'GPS relative position transmission'),\n ('POS', 'GPS position transmission'),\n ('TEMP', 'temperature transmission'),\n ('COV', 'covariance matrix transmission'),\n ('EU', 'euler angles transmission'),\n ('QT', 'quaternion transmission'),\n ('MP', 'processed magnetometer transmission'),\n ('AP', 'processed accelerometer transmission'),\n ('GP', 'processed gyroscope transmission'),\n ('MR', 'raw magnetometer transmission'),\n ('AR', 'raw accelerometer transmission'),\n ('GR', 'raw gyroscope transmission'),\n ('BEN', 'broadcast mode'),\n None\n ]\n ),\n ('MISC_CONFIG', 0x01, 32, 'miscellaneous configuration options',\n [\n (None, 27),\n ('PPS', 'PPS timing enabled'),\n ('QUAT', 'quaterion estimation enabled'),\n ('CAL', 'start-up gyroscope calibration enabled'),\n ('AUE', 'EKF accelerometer updated enabled'),\n ('MUE', 'EKF magnetometer updates enabled')\n ]\n ),\n ('MAG_REF_X', 0x02, 32),\n ('MAG_REF_Y', 0x03, 32),\n ('MAG_REF_Z', 0x04, 32),\n ('ACC_REF_X', 0x05, 32),\n ('ACC_REF_Y', 0x06, 32),\n ('ACC_REF_Z', 0x07, 32),\n ('EKF_MAG_VAR', 0x08, 32),\n ('EKF_ACC_VAR', 0x09, 32),\n ('EKF_PROC_VAR', 0x0A, 32),\n ('GYRO_BIAS1', 0x0B, 32,\n [\n ('X', 16),\n ('Y', 16)\n ]\n ),\n ('GYRO_BIAS2', 0x0C, 32,\n [\n ('Z', 16),\n (None, 16)\n ]\n ),\n ('ACC_BIAS1', 0x0D, 32,\n [\n ('X', 16),\n ('Y', 16)\n ]\n ),\n ('ACC_BIAS2', 0x0E, 32,\n [\n ('Z', 16),\n (None, 16)\n ]\n ),\n ('MAG_BIAS1', 0x0F, 32,\n [\n ('X', 16),\n ('Y', 16)\n ]\n ),\n ('MAG_BIAS2', 0x10, 32,\n [\n ('Z', 16),\n (None, 16)\n ]\n ),\n ('ACC_CAL_00', 0x11, 32),\n ('ACC_CAL_01', 0x12, 32),\n ('ACC_CAL_02', 0x13, 32),\n ('ACC_CAL_11', 0x14, 32),\n ('ACC_CAL_12', 0x15, 32),\n ('ACC_CAL_13', 0x16, 32),\n ('ACC_CAL_21', 0x16, 32),\n ('ACC_CAL_22', 0x18, 32),\n ('ACC_CAL_23', 0x19, 32),\n ('GYRO_CAL_00', 0x1A, 32),\n ('GYRO_CAL_01', 0x1B, 32),\n ('GYRO_CAL_02', 0x1C, 32),\n ('GYRO_CAL_11', 0x1D, 32),\n ('GYRO_CAL_12', 0x1E, 32),\n ('GYRO_CAL_13', 0x1F, 32),\n ('GYRO_CAL_21', 0x20, 32),\n ('GYRO_CAL_22', 0x21, 32),\n ('GYRO_CAL_23', 0x22, 32),\n ('MAG_CAL_00', 0x23, 32),\n ('MAG_CAL_01', 0x24, 32),\n ('MAG_CAL_02', 0x25, 32),\n ('MAG_CAL_11', 0x26, 32),\n ('MAG_CAL_12', 0x27, 32),\n ('MAG_CAL_13', 0x28, 32),\n ('MAG_CAL_21', 0x29, 32),\n ('MAG_CAL_22', 0x2A, 32),\n ('MAG_CAL_23', 0x2B, 32),\n ('GYROX_BIAS_C0', 0x2C, 32),\n ('GYROX_BIAS_C1', 0x2D, 32),\n ('GYROX_BIAS_C2', 0x2E, 32),\n ('GYROX_BIAS_C3', 0x2F, 32),\n ('GYROY_BIAS_C0', 0x30, 32),\n ('GYROY_BIAS_C1', 0x31, 32),\n ('GYROY_BIAS_C2', 0x32, 32),\n ('GYROY_BIAS_C3', 0x33, 32),\n ('GYROZ_BIAS_C0', 0x34, 32),\n ('GYROZ_BIAS_C1', 0x35, 32),\n ('GYROZ_BIAS_C2', 0x36, 32),\n ('GYROZ_BIAS_C3', 0x37, 32),\n # UM6 DATA REGISTERS:\n ('STATUS', 0x55, 32, 'status',\n [\n ('ST', 'self-test complete'),\n (None, 12),\n ('MAG_DEL', 'magnetometer data delay'),\n ('ACC_DEL', 'accelerometer date delay'),\n ('GYR_DEL', 'gyroscope data delay'),\n ('EKF_DIV', 'extended kalman filter diverged'),\n ('BUS_MAG', 'magnetometer bus error'),\n ('BUS_ACC', 'accelerometer bus error'),\n ('BUS_GYR', 'gyroscope bus error'),\n ('ST_MZ', 'self-test failed for magnetometer z axis'),\n ('ST_MY', 'self-test failed for magnetometer y axis'),\n ('ST_MX', 'self-test failed for magnetometer x axis'),\n ('ST_AZ', 'self-test failed for accelerometer z axis'),\n ('ST_AY', 'self-test failed for accelerometer y axis'),\n ('ST_AX', 'self-test failed for accelerometer x axis'),\n ('ST_GZ', 'self-test failed for gyroscope z axis'),\n ('ST_GY', 'self-test failed for gyroscope y axis'),\n ('ST_GX', 'self-test failed for gyroscope x axis'),\n ('GYR_INI', 'gyroscope init failed'),\n ('ACC_INI', 'accelerometer init failed'),\n ('MAG_INI', 'magnetometer init failed')\n ]\n ),\n ('GYRO_RAW1', 0x56, 32,\n [\n ('Y', 16),\n ('X', 16)\n ]\n ),\n ('GYRO_RAW2', 0x57, 32,\n [\n (None, 16),\n ('Z', 16)\n ]\n ),\n ('ACC_RAW1', 0x58, 32,\n [\n ('Y', 16),\n ('X', 16)\n ]\n ),\n ('ACC_RAW2', 0x59, 32,\n [\n (None, 16),\n ('Z', 16)\n ]\n ),\n ('MAG_RAW1', 0x5A, 32,\n [\n ('Y', 16),\n ('X', 16)\n ]\n ),\n ('MAG_RAW2', 0x5B, 32,\n [\n (None, 16),\n ('Z', 16)\n ]\n ),\n ('GYRO_PROC1', 0x5C, 32,\n [\n ('Y', 16),\n ('X', 16)\n ]\n ),\n ('GYRO_PROC2', 0x5D, 32,\n [\n (None, 16),\n ('Z', 16)\n ]\n ),\n ('ACC_PROC1', 0x5E, 32,\n [\n ('Y', 16),\n ('X', 16)\n ]\n ),\n ('ACC_PROC2', 0x5F, 32,\n [\n (None, 16),\n ('Z', 16)\n ]\n ),\n ('MAG_PROC1', 0x60, 32,\n [\n ('Y', 16),\n ('X', 16)\n ]\n ),\n ('MAG_PROC2', 0x61, 32,\n [\n (None, 16),\n ('Z', 16)\n ]\n ),\n ('EULER1', 0x62, 32,\n [\n ('THETA', 16),\n ('PHI', 16)\n ]\n ),\n ('EULER2', 0x63, 32,\n [\n (None, 16),\n ('PSI', 16)\n ]\n ),\n\n\n ('QUAT1', 0x64, 32,\n [\n ('B', 16),\n ('A', 16)\n ]\n ),\n ('QUAT2', 0x65, 32,\n [\n ('D', 16),\n ('C', 16)\n ]\n ),\n ('ERROR_COV_00', 0x66, 32),\n ('ERROR_COV_01', 0x67, 32),\n ('ERROR_COV_02', 0x68, 32),\n ('ERROR_COV_03', 0x69, 32),\n ('ERROR_COV_10', 0x6A, 32),\n ('ERROR_COV_11', 0x6B, 32),\n ('ERROR_COV_12', 0x6C, 32),\n ('ERROR_COV_13', 0x6D, 32),\n ('ERROR_COV_20', 0x6E, 32),\n ('ERROR_COV_21', 0x6F, 32),\n ('ERROR_COV_22', 0x70, 32),\n ('ERROR_COV_23', 0x71, 32),\n ('ERROR_COV_30', 0x72, 32),\n ('ERROR_COV_31', 0x73, 32),\n ('ERROR_COV_32', 0x74, 32),\n ('ERROR_COV_33', 0x75, 32),\n ('TEMPERATURE', 0x76, 32),\n ('GPS_LONGITUDE', 0x77, 32),\n ('GPS_LATITUDE', 0x78, 32),\n ('GPS_ALTITUDE', 0x79, 32),\n ('GPS_POS_NORTH', 0x7A, 32),\n ('GPS_POS_EAST', 0x7B, 32),\n ('GPS_POS_HEIGHT', 0x7C, 32),\n ('GPS_COURSE_SPEED', 0x7D, 32,\n [\n ('SPEED', 16),\n ('COURSE', 16)\n ]\n ),\n ('GPS_SAT_SUMMARY', 0x7E, 32, 'status',\n [\n (None, 6),\n ('VDOP', 10, 'vertical dillusion of precision'),\n ('HDOP', 10, 'horizontal dillusion of precision'),\n ('SAT_COUNT', 4, 'satellite count'),\n ('MODE', 2, 'fix mode')\n ]\n ),\n ('GPS_SAT_XY_0', 0x7F, 32,\n [\n ('Y_ID', 8),\n ('Y_SNR', 8),\n ('X_ID', 8),\n ('X_SNR', 8)\n ]\n ),\n ('GPS_SAT_XY_1', 0x80, 32,\n [\n ('Y_ID', 8),\n ('Y_SNR', 8),\n ('X_ID', 8),\n ('X_SNR', 8)\n ]\n ),\n ('GPS_SAT_XY_2', 0x81, 32,\n [\n ('Y_ID', 8),\n ('Y_SNR', 8),\n ('X_ID', 8),\n ('X_SNR', 8)\n ]\n ),\n ('GPS_SAT_XY_3', 0x82, 32,\n [\n ('Y_ID', 8),\n ('Y_SNR', 8),\n ('X_ID', 8),\n ('X_SNR', 8)\n ]\n ),\n ('GPS_SAT_XY_4', 0x83, 32,\n [\n ('Y_ID', 8),\n ('Y_SNR', 8),\n ('X_ID', 8),\n ('X_SNR', 8)\n ]\n ),\n ('GPS_SAT_XY_5', 0x84, 32,\n [\n ('Y_ID', 8),\n ('Y_SNR', 8),\n ('X_ID', 8),\n ('X_SNR', 8)\n ]\n ),\n ('GET_FW_VERSION', 0xAA, 0),\n ('FLASH_COMMIT', 0xAB, 0),\n ('ZERO_GYROS', 0xAC, 0),\n ('RESET_EKF', 0xAD, 0),\n ('GET_DATA', 0xAE, 0),\n ('SET_ACC_REF', 0xAF, 0),\n ('SET_MAG_REF', 0xB0, 0),\n ('RESET_TO_FACTORY', 0xB1, 0),\n ('SET_HOME_POS', 0xB3, 0),\n ('BAD_CHECKSUM', 0xFD, 0),\n ('UNKNOWN_ADDRESS', 0xFE, 0),\n ('INVALID_BATCH_SIZE', 0xFF, 0),\n]\n\n","repo_name":"TobiasSimon/chr-um6","sub_path":"regs/um6_regs.py","file_name":"um6_regs.py","file_ext":"py","file_size_in_byte":9462,"program_lang":"python","lang":"en","doc_type":"code","stars":2,"dataset":"github-code","pt":"15"} +{"seq_id":"29052032391","text":"import logging\nimport time\n\nfrom aea.skills.base import Task\n\nlogger = logging.getLogger(\"aea.echo_skill\")\nfrom numpy import genfromtxt\nfrom sklearn.linear_model import LogisticRegression\n\nimport os\nimport time\n\nfrom squid_py import (\n Ocean,\n ConfigProvider,\n Config\n)\n\n\n\n\n\nclass SubmarineTask(Task):\n \"\"\"Submarine task.\"\"\"\n\n def __init__(self, **kwargs):\n \"\"\"Initialize the task.\"\"\"\n super().__init__(**kwargs)\n logger.info(\"SubmarineTask.__init__: arguments: {}\".format(kwargs))\n\n def setup(self) -> None:\n \"\"\"Set up the task.\"\"\"\n logger.info(\"Submarine Task: setup method called.\")\n self.query_txn = None\n self.model = LogisticRegression()\n\n def execute(self, contract, query, nonce) -> None:\n \"\"\"Execute the task.\"\"\"\n #logger.info(\"Submarine Task: execute method called.\")\n if not self.query_txn:\n response = self.create_ocean_request(query)\n result = self.process_response(query, response)\n updateQuery = contract.functions.updateQuery(query[\"contract\"], result)\n \n self.query_txn = self.prepare_tx(updateQuery, nonce)\n #self.query_txn = None\n \n\n def teardown(self) -> None:\n \"\"\"Teardown the task.\"\"\"\n logger.info(\"Submarine Task: teardown method called.\")\n\n def create_ocean_request(self, query) -> None:\n ConfigProvider.set_config(Config('../../ocean/config.ini'))\n # Make a new instance of Ocean\n ocean = Ocean() # or Ocean(Config('config.ini'))\n config = ocean.config\n # make account instance, assuming the ethereum account and password are set \n # in the config file `config.ini`\n account = ocean.accounts.list()[0]\n filename = '../../ocean/bitcoin_2017.csv'\n did = query['did']\n my_data = genfromtxt(filename, delimiter=',')\n #print('data at', filename, my_data)\n return my_data\n\n \n\n \n\n #did = 'did:op:71fae96b1d9a4651ba0d3946603fb4c11deb724685f64780985ce32ea2dfe517'\n service_agreement_id = ocean.assets.order(did, 0, account)\n\n # after a short wait (seconds to minutes) the asset data files should be available in the `downloads.path` defined in config\n # wait a bit to let things happen\n\n print(service_agreement_id)\n time.sleep(20)\n\n # Asset files are saved in a folder named after the asset id\n dataset_dir = os.path.join(ocean.config.downloads_path, f'datafile.{asset_ddo.asset_id}.0')\n if os.path.exists(dataset_dir):\n print('asset files downloaded: {}'.format(os.listdir(dataset_dir)))\n\n\n\n\n def process_response(self, query, response) -> None:\n X = [response[i][:-1] for i in range(350)]\n y = [response[i][-1] for i in range(350)]\n\n self.model.fit(X, y)\n y_test = self.model.predict_proba([response[i][:-1] for i in range(301,363)])[:,1]\n mse = ((y_test-[response[i][-1] for i in range(301,363)])**2).mean()\n print(y_test.tolist()[:5], [mse]*5)\n\n if query[\"command\"] == 'mean':\n return [int(100000*mse) for x in range(5)]\n return [int(100000*x) for x in y_test.tolist()[:5]]\n\n def prepare_tx(self, updateQuery, nonce):\n \n query_txn = updateQuery.buildTransaction({\n 'gas': 300000,\n 'nonce': nonce\n })\n return query_txn\n\n \n","repo_name":"diffusioncon/Captain-Nemo-Fetch.AI-Ocean-Protocol","sub_path":"agent/nemo/skills/submarine/tasks.py","file_name":"tasks.py","file_ext":"py","file_size_in_byte":3439,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"15"} +{"seq_id":"72321984012","text":"import numpy as np\nimport matplotlib.pyplot as plt\nimport matplotlib.animation as animation\nimport matplotlib.patches as patches\nfrom matplotlib.patches import Rectangle\nfrom matplotlib import animation\nimport time\nfrom numba import njit\n\n\n\"\"\"\nL'algorithme utilisé provient du pdf du professeur 'Mecanique_des_Materiaux_Granulaires_16_17.pdf'\n\nHypothèses persos:\n- Les grains sont des sphères de même masse et de même rayon\n- On est dans le vide\n\"\"\"\n\ndef trajectoire(POSITION, nb_grains, paroiGauche, paroiDroite):\n \"\"\"\n Affiche la trajectoire des grains dans un graphe matplotlib.\n\n Paramètres\n ==========\n POSITION : np.array, tableau des positions\n hauteur_silo : float, hauteur du silo\n largeur_silo : float, largeur du silo\n nb_grains : int, nombre de grains\n\n Retour\n ======\n rien\n \"\"\"\n print(\"Affichage de la trajectoire...\")\n\n fig, ax = plt.subplots()\n ax.set_aspect('equal')\n\n #dessin du silo dans le tableau graphique matplot\n X1 = np.linspace(-0.5, -0.02, 100)\n X2 = np.linspace(0.02, 0.5, 100)\n plt.plot(X1, paroiGauche(X1), color='black')\n plt.plot(X2, paroiDroite(X2), color='black')\n \n for grain in range(nb_grains):\n ax.plot(POSITION[:, grain, 0], POSITION[:, grain, 1], label=\"grain {}\".format(grain))\n\n plt.grid()\n plt.legend()\n plt.show()\n\ndef grain_anime(POSITION, nb_grains, rayon, paroiGauche, paroiDroite):\n \"\"\"\n Fait une animation de la chute des grains dans le silo.\n\n Paramètres\n ==========\n POSITION : np.array, tableau des positions\n hauteur_silo : float, hauteur du silo\n largeur_silo : float, largeur du silo\n nb_grains : int, nombre de grains\n rayon : float, rayon des grains\n\n Retour\n ======\n rien \n \"\"\"\n print(\"Animation en cours...\")\n\n fig, ax = plt.subplots()\n ax.set_aspect('equal')\n \n #dessin du silo dans le tableau graphique matplot\n X1 = np.linspace(-0.5, -0.02, 100)\n X2 = np.linspace(0.02, 0.5, 100)\n plt.plot(X1, paroiGauche(X1), color='black')\n plt.plot(X2, paroiDroite(X2), color='black')\n \n #dessin des grains dans le tableau graphique matplot\n grains = []\n texts = []\n for grain in range(nb_grains):\n grains.append(ax.add_patch(patches.Circle((POSITION[0, grain, 0], POSITION[0, grain, 1]), radius=rayon, fill=True, color='black')))\n texts.append(ax.text(POSITION[0, grain, 0], POSITION[0, grain, 1], str(grain), ha='center', va='center', fontsize=8, color='white'))\n \n time_text = ax.text(0.05, 0.99, '', transform=ax.transAxes, verticalalignment='top', fontsize=12)\n def animate(i):\n #Affiche l'indice du temps en haut a gauche de l'écran\n for grain in range(nb_grains):\n grains[grain].center = (POSITION[i, grain, 0], POSITION[i, grain, 1])\n texts[grain].set_position((POSITION[i, grain, 0], POSITION[i, grain, 1]))\n return grains + texts + [time_text]\n \n ani = animation.FuncAnimation(fig, animate, frames=int(POSITION.shape[0]/1e0), interval=1, blit=True)\n plt.show()\n\n\n\ndef calcul_allongement_normal(vitesse_i, vitesse_j, position_i, position_j, rayon_i, rayon_j):\n \"\"\"\n Calcul de l'allongement/distance normal à partir de l'équation\n Paramètres\n ==========\n vitesse_i : np.array, vitesse du grain i\n vitesse_j : np.array, vitesse du grain j\n position_i : np.array, position du grain i\n position_j : np.array, position du grain j\n rayon_i : float, rayon du grain i\n rayon_j : float, rayon du grain j\n\n Retour\n ======\n allongement_normal : float, allongement normal entre les grains i et j\n \"\"\"\n return np.linalg.norm(position_i - position_j) - (rayon_i + rayon_j)\n\ndef calcul_allongement_tangentiel(i, j, indice_temps, pas_de_temps, VITESSE, POSITION):\n \"\"\"\n Calcul de l'allongement tangentielle à partir de l'équation\n\n Paramètres\n ==========\n i : int, indice du grain i\n j : int, indice du grain j\n indice_temps : int, indice du temps actuel\n pas_de_temps : float, pas de temps\n VITESSE : np.array, tableau des vitesses\n POSITION : np.array, tableau des positions\n\n Retour\n ======\n allongement_tangentiel : float, allongement tangentiel entre les grains i et j\n \"\"\"\n #print(\"Contact!\")\n #(4.8): d/dt(delta_t) = (vitesse_i - vitesse_j)*tangente \n # C'est le produit vectorielle de la différence de vitesse sur la tangente du contact entre les deux grains i et j\n #C'est cette formule (4.8) qu'il faut intégrer temporellement en utilisant les données des vitesses(tableaux numpy)\n #On calcul ensuite l'allongement tangentielle via la formule (4.8)\n #Pour ca on cherche le moment d'impact:\n #On cherche le moment d'impact en cherchant le moment ou la distance normal est nulle\n k = 0 # car on sait que c'est déjà le cas\n while calcul_allongement_normal(vitesse_i=VITESSE[indice_temps-k, i],\n vitesse_j=VITESSE[indice_temps-k, j],\n position_i=POSITION[indice_temps-k, i],\n position_j=POSITION[indice_temps-k, j],\n rayon_i=rayon,\n rayon_j=rayon) < 0 and k < indice_temps:\n k += 1\n #On a donc trouvé le moment d'impact avec moment = indice_temps-k, NB: si k = 0 alors impact a lieu à indice_temps\n impact = indice_temps - k\n #On peut calculer le tableau des vitesses tangentielles:\n produit_scalaire_array = np.zeros(indice_temps+1) #tableau 1D car projection sur la tangente, \n #indice_temps+1, parce que plus lisible pour les indices,\n #autrement dit on aura que des zeros jusqu'a l'indice indice_temps-impact \n for tps_actuel in range(impact, indice_temps+1):\n vecteur_normal = (POSITION[tps_actuel,i] - POSITION[tps_actuel,j])/np.linalg.norm(POSITION[tps_actuel,i] - POSITION[tps_actuel,j])\n #On veut connaître le sens du vecteur tangent qui doit être dans la même direction que la vitesse absolue\n vecteur_tangent = np.array([-vecteur_normal[1], vecteur_normal[0]])\n if np.dot(vecteur_tangent, VITESSE[tps_actuel,i]) < 0:\n vecteur_tangent = -vecteur_tangent\n vitesse_relative = VITESSE[tps_actuel,i] - VITESSE[tps_actuel,j]\n produit_scalaire = np.dot(vitesse_relative, vecteur_tangent)\n produit_scalaire_array[tps_actuel] = produit_scalaire\n \n #On doit maintenant intégrer la valeur de la vitesse tangentielle sur le temps\n allongement_tangentiel = 0\n for i in range(len(produit_scalaire_array)):\n allongement_tangentiel += produit_scalaire_array[i]\n allongement_tangentiel *= pas_de_temps\n return allongement_tangentiel\n\ndef application_efforts_distance(masse):\n \"\"\"\n Application des efforts à distance (par exemple la pesanteur).\n\n Paramètres\n ==========\n masse : float, masse du grain\n\n Retour\n ======\n forces : np.array, forces appliquée au grain\n \"\"\"\n return np.array([0, -masse*9.81])\n \n\ndef voisinage(i, POSITION, GRILLE, c, indice_temps):\n \"\"\"\n Détermine la liste de voisinage du grain i\n\n Paramètres\n ==========\n i : int, indice du grain i\n POSITION : np.array, tableau des positions\n GRILLE : dict, grille de voisinage\n c : float, pas d'espace\n indice_temps : int, indice du temps\n\n Retour\n ======\n grains_voisins : np.array, tableau des indices des grains en contact avec le grain i\n \"\"\"\n x = int(POSITION[indice_temps,i,0]/c)\n y = int(POSITION[indice_temps,i,1]/c)\n voisinage = []\n for voisin in GRILLE[x, y]:\n if voisin != i:\n voisinage.append(voisin)\n\n for j in range(-1, 2):\n for k in range(-1, 2):\n if not(j == 0 and k == 0):\n case_voisine_x, case_voisine_y = int(POSITION[indice_temps,i,0]/c)+j, int(POSITION[indice_temps,i,1]/c)+k\n if (case_voisine_x, case_voisine_y) in GRILLE.keys():\n voisinage += GRILLE[case_voisine_x, case_voisine_y]\n\n return voisinage\n\n\n\n\n\n\n\n\n\n\ndef algoprincipal(POSITION, VITESSE, ACCELERATION, VITESSE_DEMI_PAS, nb_grains, raideur_normale, nb_temps, pas_de_temps, rayon, masse, raideur_tangentielle, indice_temps, temps, hauteur_silo_haut, hauteur_silo_bas, largeur_silo_droite, largeur_silo_gauche, raideur_mur, paroiDroite, paroiGauche, coefficient_de_frottement):\n \"\"\"\n Algorithme principal\n \n Paramètres\n ==========\n POSITION : np.array, tableau des positions\n VITESSE : np.array, tableau des vitesses\n ACCELERATION : np.array, tableau des accélérations\n VITESSE_DEMI_PAS : np.array, tableau des vitesses à demi pas\n nb_grains : int, nombre de grains\n nb_temps : int, nombre de pas de temps\n pas_de_temps : float, pas de temps\n rayon : float, rayon des grainsX1 = np.linspace(-0.5, -0.1, 100)\n X2 = np.linspace(0.1, 0.5, 100)\n masse : float, masse des grains\n raideur_tangentielle : float, raideur tangentielle\n indice_temps : int, indice du temps\n temps : float, temps\n hauteur_silo : float, hauteur du silo\n largeur_silo : float, largeur du silo\n raideur_mur : float, raideur des murs\n paroiDroite : lambda, fonction de la paroi droite\n paroiGauche : lambda, fonction de la paroi gauche\n\n Retour\n ======\n rien\n \"\"\"\n\n\n start_time = time.time()\n\n while indice_temps < nb_temps-1:\n #Actualisation du temps\n temps += pas_de_temps\n indice_temps += 1\n if indice_temps % 1000 == 0:\n print(\"indice_temps \", indice_temps, \"/\", nb_temps)\n print(\"temps:\", temps)\n \n # Mise a jour des tableaux de position et vitesse à temps k\n for grain in range(nb_grains):\n #Calcul de la nouvelle position du grain\n POSITION[indice_temps, grain, :] = POSITION[indice_temps-1, grain, :] + VITESSE_DEMI_PAS[indice_temps-1, grain, :]*pas_de_temps\n \n \n #Calcul de la vitesse du grain\n VITESSE[indice_temps, grain, :] = VITESSE_DEMI_PAS[indice_temps-1, grain, :] + ACCELERATION[indice_temps-1, grain, :]*pas_de_temps/2\n\n #On définit une grille pour discrétiser l'espace selon le pas d'espace c, a chaque case on met la liste des grains qui sont dans cette case\n c = 3*rayon #taille de la case\n GRILLE = {(i,j):[] for i in range(int(largeur_silo_gauche/c)-1, int(largeur_silo_droite/c)+2) for j in range(int(hauteur_silo_bas/c)-1, int(hauteur_silo_haut/c)+2)}\n\n\n #On associe à chaque case de la grille les grains qui sont dans cette case\n for i in range(nb_grains):\n try:\n pos_case = (int(POSITION[indice_temps,i,0]/c), int(POSITION[indice_temps,i,1]/c))\n GRILLE[pos_case[0], pos_case[1]].append(i)\n except:\n print(\"problème avec le grain\", i)\n print(\"position:\", POSITION[indice_temps,i,0], POSITION[indice_temps,i,1])\n print(\"pos_case:\", pos_case)\n print(\"indice_temps:\", indice_temps)\n trajectoire(POSITION, nb_grains, paroiDroite=paroiDroite, paroiGauche=paroiGauche)\n grain_anime(POSITION, nb_grains, rayon, paroiDroite=paroiDroite, paroiGauche=paroiGauche)\n exit()\n condition_arret = POSITION[indice_temps, grain, 1] < 0.0\n if condition_arret:\n POSITION[indice_temps, grain, 0] = -0.05*grain\n POSITION[indice_temps, grain, 1] = -0.1\n VITESSE[indice_temps, grain, 1] = 0.0\n VITESSE[indice_temps, grain, 0] = 0.0\n ACCELERATION[indice_temps, grain, 1] = 0.0\n ACCELERATION[indice_temps, grain, 0] = 0.0\n VITESSE_DEMI_PAS[indice_temps, grain, 1] = 0.0\n VITESSE_DEMI_PAS[indice_temps, grain, 0] = 0.0\n\n \n # Calcul des efforts de contact pour mise à jour des vitesses à temps k+1/2 et accélérations à temps k\n for grain1 in range(nb_grains):\n #Force à distance = gravité\n force_resultante = np.array([0.0, 0.0])\n force_resultante += application_efforts_distance(masse)\n\n #Rencontre avec une paroi du silo ?\n vecteur_directeur_paroi_gauche = np.array([1.0, -1/0.34])\n vecteur_orthogonal_paroi_gauche = np.array([1/0.34, 1.0]) / np.sqrt(1 + (1/0.34)**2)\n\n vecteur_directeur_paroi_droite = np.array([1.0, 1/0.34])\n vecteur_orthogonal_paroi_droite = np.array([-1/0.34, 1.0]) / np.sqrt(1 + (1/0.34)**2)\n\n A = 1/0.34\n B = 1\n C = -0.5\n distance_a_la_gauche = abs(A * POSITION[indice_temps, grain1, 0] + B * POSITION[indice_temps, grain1, 1] + C) / np.sqrt(A**2 + B**2)\n\n A = -1/0.34\n B = 1\n C = -0.5\n distance_a_la_droite = abs(A * POSITION[indice_temps, grain1, 0] + B * POSITION[indice_temps, grain1, 1] + C) / np.sqrt(A**2 + B**2)\n\n penetration_gauche = distance_a_la_gauche - rayon\n penetration_droite = distance_a_la_droite - rayon\n\n if penetration_gauche < 0:\n force_resultante += -raideur_mur * penetration_gauche * vecteur_orthogonal_paroi_gauche\n\n elif penetration_droite < 0:\n force_resultante += -raideur_mur * penetration_droite * vecteur_orthogonal_paroi_droite\n\n voisins = voisinage(i=grain1, POSITION=POSITION, c=c, GRILLE=GRILLE, indice_temps=indice_temps)\n for grain2 in voisins:\n if grain1 != grain2:\n #On définit la force de contact entre les deux grains:\n force_contact = 0\n\n allongement_normal = calcul_allongement_normal(vitesse_i=VITESSE[indice_temps, grain1,:],\n vitesse_j=VITESSE[indice_temps, grain2, :],\n position_i=POSITION[indice_temps, grain1, :],\n position_j=POSITION[indice_temps, grain2, :],\n rayon_i=rayon,\n rayon_j=rayon)\n #Effort normal\n if allongement_normal < 0:\n vecteur_normal = (POSITION[indice_temps, grain1, :] - POSITION[indice_temps, grain2, :])/np.linalg.norm(POSITION[indice_temps, grain1, :] - POSITION[indice_temps, grain2, :])\n force_contact += -raideur_normale * allongement_normal * vecteur_normal\n\n #Effort tangentiel\n allongement_tangentiel = calcul_allongement_tangentiel(grain1, grain2, indice_temps, pas_de_temps, VITESSE, POSITION)\n vecteur_normal = (POSITION[indice_temps, grain1, :] - POSITION[indice_temps, grain2, :])/np.linalg.norm(POSITION[indice_temps, grain1, :] - POSITION[indice_temps, grain2, :])\n vecteur_tangentiel = np.array([-vecteur_normal[1], vecteur_normal[0]])\n if np.dot(vecteur_tangentiel, VITESSE[indice_temps,grain1]) < 0:\n vecteur_tangentiel = -vecteur_tangentiel\n force_contact += -raideur_tangentielle * allongement_tangentiel * vecteur_tangentiel\n \n # 17. Mise à jour de la résultante des forces sur grain1\n force_resultante += force_contact\n \n frotemment = -coefficient_de_frottement * VITESSE[indice_temps, grain1, :]\n force_resultante += frotemment\n\n # Calcul de l'accélération du grain à partir de l'équation (4.1)\n ACCELERATION[indice_temps][grain1] = force_resultante / masse\n \n # Calcul de la vitesse de demi-pas à k+1/2 à partir de l'équation (4.19)\n VITESSE_DEMI_PAS[indice_temps][grain1] = VITESSE_DEMI_PAS[indice_temps-1][grain1] + ACCELERATION[indice_temps][grain1] * pas_de_temps / 2\n\n\n # Fin de la boucle principale\n print(\"Fin de la simulation\")\n print(\"Temps de calcul: \", time.time() - start_time, \"secondes\")\n\n #Affichage:\n trajectoire(POSITION, nb_grains, paroiGauche, paroiDroite)\n grain_anime(POSITION, nb_grains, rayon, paroiGauche, paroiDroite)\n\n\n\n\nif __name__ == \"__main__\":\n #Définition grain\n nb_grains = 10\n masse = 1e-3 #kg \n rayon = 1e-2 #m\n raideur_normale = 100 #N/m\n raideur_tangentielle = 50 #N/m\n coefficient_de_frottement = 0.0005 #N/m\n #Pour le roulement trop compliqué, on utilise leur rotation\n\n #Définition du silo\n hauteur_silo_bas = -0.5 #m\n hauteur_silo_haut = 2.5 #m\n largeur_silo_gauche = -0.5 #m\n largeur_silo_droite = 0.5 #m\n raideur_mur = 100 #N/m\n paroiGauche = lambda x : -1/0.34*x+0.5\n paroiDroite = lambda x : 1/0.34*x+0.5\n\n #Définition du temps\n temps = 0\n indice_temps = 0\n pas_de_temps = 1e-3 #s\n duree_simulation = 5\n nb_temps = int(duree_simulation/pas_de_temps)\n\n #ON PLACE LE REPERE EN BAS A GAUCHE (0,0) DU SILO COIN BAS GAUCHE Y VERS LE HAUT.\n #TABLEAUX NUMPY\n POSITION = np.zeros((nb_temps, nb_grains, 2)) \n for grain in range(nb_grains):\n POSITION[0, grain, 0] = rayon*grain + rayon\n POSITION[0, grain, 1] = 1.5\n print(POSITION[0])\n VITESSE = np.zeros((nb_temps, nb_grains, 2))\n VITESSE[0,:,:] = 0 # pas défini au début, on commece à 1 pour la vitesse et à 0 pour la vitessse de demi pas\n VITESSE_DEMI_PAS = np.zeros((nb_temps, nb_grains, 2))\n VITESSE_DEMI_PAS[0] = np.random.uniform(low=-0.005, high=0.005, size=(nb_grains, 2)) #RAPPEL: Le silo fait un metre par un metre...\n ACCELERATION = np.zeros((nb_temps, nb_grains, 2))\n ACCELERATION[0,:,:] = 0\n\n\n\n start = int(input(\"Start ou pas? entrez 1 ou 0\"))\n if start:\n algoprincipal(POSITION=POSITION, VITESSE=VITESSE, VITESSE_DEMI_PAS=VITESSE_DEMI_PAS, ACCELERATION=ACCELERATION, nb_grains=nb_grains, rayon=rayon, masse=masse, raideur_normale=raideur_normale, raideur_tangentielle=raideur_tangentielle, coefficient_de_frottement=coefficient_de_frottement, paroiGauche=paroiGauche, paroiDroite=paroiDroite, raideur_mur=raideur_mur, pas_de_temps=pas_de_temps, nb_temps=nb_temps, indice_temps=indice_temps, hauteur_silo_bas=hauteur_silo_bas, hauteur_silo_haut=hauteur_silo_haut, largeur_silo_gauche=largeur_silo_gauche, largeur_silo_droite=largeur_silo_droite, temps=temps)","repo_name":"Shaunerie/P2i","sub_path":"projet_final/v03_sans_debug copy.py","file_name":"v03_sans_debug copy.py","file_ext":"py","file_size_in_byte":18633,"program_lang":"python","lang":"fr","doc_type":"code","stars":0,"dataset":"github-code","pt":"15"} +{"seq_id":"3037601812","text":"\"\"\"\nImport as:\n\nimport im_v2.talos.utils as imv2tauti\n\"\"\"\nimport base64\nimport datetime\nimport hashlib\nimport hmac\nimport logging\nfrom typing import Dict, List, Optional\n\nimport pandas as pd\n\nimport helpers.hdatetime as hdateti\nimport helpers.hdbg as hdbg\nimport helpers.hsecrets as hsecret\n\n_LOG = logging.getLogger(__name__)\n_TALOS_HOST = \"talostrading.com\"\n\n\ndef timestamp_to_talos_iso_8601(timestamp: pd.Timestamp) -> str:\n \"\"\"\n Transform Timestamp into a string in the format accepted by Talos API.\n\n Example:\n 2019-10-20T15:00:00.000000Z\n\n Note: microseconds must be included.\n \"\"\"\n\n hdateti.dassert_has_UTC_tz(timestamp)\n # Timestamp converter.\n timestamp_iso_8601 = timestamp.strftime(\"%Y-%m-%dT%H:%M:%S.000000Z\")\n return timestamp_iso_8601 # type: ignore\n\n\ndef get_talos_current_utc_timestamp() -> str:\n \"\"\"\n Return the current UTC timestamp in the format acceptable by Talos.\n\n Example: 2019-10-20T15:00:00.000000Z\n \"\"\"\n utc_datetime = datetime.datetime.utcnow().strftime(\n \"%Y-%m-%dT%H:%M:%S.000000Z\"\n )\n return utc_datetime\n\n\nclass TalosApiBuilder:\n \"\"\"\n Base class containing the methods for Talos API access.\n \"\"\"\n\n def __init__(self, account: str):\n \"\"\"\n Initialize TalosApiBuilder.\n\n :param account: acceptable values `trading`, `sandbox`\n \"\"\"\n self._account = account\n self._api_keys = hsecret.get_secret(f\"talos.preprod.{self._account}.1\")\n # Talos request endpoint.\n self._endpoint = self.get_endpoint()\n\n @staticmethod\n def calculate_signature(secret_key: str, parts: List[str]) -> str:\n \"\"\"\n Encode the request using secret key.\n\n Requires parts of the API request provided as a list, e.g.:\n\n ```\n [\n \"POST\",\n str(utc_datetime),\n \"tal-87.sandbox.talostrading.com\",\n \"/v1/orders\",\n ]\n ```\n\n :param secret_key: secret key used for encoding\n :param parts: parts of the GET or POST request\n :return: an encoded string\n \"\"\"\n payload = \"\\n\".join(parts)\n hash = hmac.new(\n secret_key.encode(\"ascii\"),\n payload.encode(\"ascii\"),\n hashlib.sha256,\n )\n hash.hexdigest()\n signature = base64.urlsafe_b64encode(hash.digest()).decode()\n return signature\n\n def build_parts(\n self, request_type: str, wall_clock_timestamp: str, path: str\n ) -> List[str]:\n \"\"\"\n Combine initial parts of a GET or POST request.\n\n The parts include a timestamp, endpoint and path, e.g.:\n\n ```\n [\n \"GET\",\n \"2019-10-20T15:00:00.000000Z\",\n \"sandbox.talostrading.com\",\n \"/v1/orders\"\n ]\n ```\n\n :param request_type: GET or POST\n :param wall_clock_timestamp: time of request creation\n :param path: part of url after endpoint, e.g. \"/v1/orders\"\n :return parts: parts of request\n \"\"\"\n hdbg.dassert_in(\n request_type, [\"GET\", \"POST\"], msg=\"Incorrect request type\"\n )\n parts = [request_type, wall_clock_timestamp, self._endpoint, path]\n return parts\n\n def build_headers(\n self, parts: Optional[List[str]], wall_clock_timestamp: Optional[str]\n ) -> Dict[str, str]:\n \"\"\"\n Build parts of the request metadata.\n\n This includes providing public key and encoding request\n with secret key for Talos authorization.\n\n :param parts: parts of request\n :param wall_clock_timestamp: time of request submission\n :return: headers for Talos request\n \"\"\"\n headers = {\"TALOS-KEY\": self._api_keys[\"apiKey\"]}\n if parts:\n signature = self.calculate_signature(\n self._api_keys[\"secretKey\"], parts\n )\n headers[\"TALOS-SIGN\"] = signature\n if wall_clock_timestamp:\n headers[\"TALOS-TS\"] = wall_clock_timestamp\n return headers\n\n def get_endpoint(self) -> str:\n \"\"\"\n Get entrypoint to Talos. The only environment we currently support is\n `sandbox`.\n\n :return: Talos endpoint, e.g. \"sandbox.talostrading.com\"\n \"\"\"\n if self._account == \"sandbox\":\n endpoint = f\"sandbox.{_TALOS_HOST}\"\n else:\n hdbg.dfatal(\n \"Incorrect account type. Supported environments: 'sandbox'.\"\n )\n return endpoint\n","repo_name":"sorrentum/sorrentum","sub_path":"im_v2/talos/utils.py","file_name":"utils.py","file_ext":"py","file_size_in_byte":4484,"program_lang":"python","lang":"en","doc_type":"code","stars":60,"dataset":"github-code","pt":"15"} +{"seq_id":"32790562109","text":"from os import system, name\nsystem('cls' if name == 'nt' else 'clear')\n\ndsc = ('''DESAFIO 007:\nDesenvolva um programa que leia as duas notas de um aluno,\ncalcule e mostre a sua média.\n''')\n\nn1 = float(input('Digite a primeira nota: '))\nn2 = float(input('Digite a segunda nota: '))\nprint('a média é: {}'.format((n1 + n2) / 2))\n","repo_name":"tseiiti/curso_em_video","sub_path":"mundo_1/ex007.py","file_name":"ex007.py","file_ext":"py","file_size_in_byte":329,"program_lang":"python","lang":"pt","doc_type":"code","stars":0,"dataset":"github-code","pt":"15"} +{"seq_id":"1022684403","text":"class Author:\n # books = []\n\n def __init__(self, name):\n self.name = name\n self.books = [] # empty book list\n\n def publish(self, title): # append the title of the book to the list\n if title in self.books:\n print('oops, looks like this book is currently on the list')\n return\n else:\n return self.books.append(title)\n\n def __str__(self): # returns a string with the author's name, and their book's titles\n book_list = ', '.join(self.books) or 'No published books'\n return f'Author name: {self.name}\\nBooks Published: {book_list}'\n\n\ndef main():\n book1 = Author('Theodore Taylor')\n book1.publish('The Cay')\n book1.publish('The Cay')\n print(book1)\n\n book2 = Author('Lois Lowry')\n book2.publish('The Giver')\n book2.publish('The Giver')\n\n print(book2)\n\n\n# **Note**\n# '__main__' = scope in which top-level code executes\n# A __name__,\nif __name__ == '__main__':\n main() # only run if script is executing when invoked directly\nelse:\n # __name__ = imported module\n print('script is getting imported by other module')\n","repo_name":"saida93522/PythonBasic","sub_path":"author.py","file_name":"author.py","file_ext":"py","file_size_in_byte":1131,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"15"} +{"seq_id":"17943195973","text":"#!/usr/bin/env python3\n# -*- coding: utf-8 -*-\n\nimport os\nimport urllib.request as req\nfrom bs4 import BeautifulSoup\nfrom urllib.parse import urljoin\nfrom progressbar import ProgressBar\nfrom pathlib import Path\n\nwith open(\"./oglethorpe?view=lineup\") as f:\n soup = BeautifulSoup(f.read())\n\n# Discovered by staring at HTML.\nstats_table = soup.find_all(\"table\")[4]\n\n# The first row is just abbreviations, so toss it. Likewise, the last two are\n# totals, so toss them.\nrows = stats_table.find_all(\"tr\")[1:-2]\n\nPLAYER_DIR = \"./player_pages\"\n\nif not os.path.exists(PLAYER_DIR):\n os.makedirs(PLAYER_DIR)\n\nplayer_bar = ProgressBar()\n\nfor row in player_bar(rows):\n player_link = row.a\n player_name = player_link.text.strip().replace(\" \", \"-\")\n\n dir_name = PLAYER_DIR + \"/\" + player_name\n if not os.path.exists(dir_name):\n os.makedirs(dir_name)\n\n # Check to see if we should update this player.\n if os.path.exists(dir_name + \"/\" + \".updated\"):\n continue\n\n print(\"\\nGetting:\", player_name)\n\n # Get career stats for every year.\n base_player_url = urljoin(\"http://gopetrels.com/\", player_link[\"href\"])\n player_url = base_player_url + \"?view=career\"\n\n career_text = req.urlopen(player_url).read().decode(\"utf8\")\n print(\"Got request...\")\n\n player_soup = BeautifulSoup(career_text)\n print(\"Soupified...\")\n\n # Found by staring at HTML.\n career_table = player_soup.find_all(\"table\")[3]\n print(\"Found table...\")\n\n # Get rid of the header and the totals row.\n career_rows = career_table.find_all(\"tr\")[1:-1]\n\n for year_row in career_rows:\n year_link = year_row.a\n year_name = year_link.text\n\n # The year_link initially has \"?view=profile\", but we don't want that.\n base_year_url = urljoin(player_url, year_link[\"href\"])\n stop = base_year_url.find(\"?\")\n base_year_url = base_year_url[:stop]\n year_url = base_year_url + \"?view=gamelog\"\n\n year_page = req.urlopen(year_url).read().decode(\"utf8\")\n with open(\"{}/{}.html\".format(dir_name, year_name), \"w\") as f:\n f.write(year_page)\n print(\"Wrote {}...\".format(year_name))\n\n # Create the file to signify that we don't need to update this player.\n Path(dir_name + \"/\" + \".updated\").touch()\n","repo_name":"rwbogl/voul","sub_path":"get_players.py","file_name":"get_players.py","file_ext":"py","file_size_in_byte":2283,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"15"} +{"seq_id":"4100280937","text":"# Definition for a binary tree node.\n# class TreeNode:\n# def __init__(self, x):\n# self.val = x\n# self.left = None\n# self.right = None\n\nclass Solution:\n def flipMatchVoyage(self, root, voyage):\n res = []\n self.i = 0\n def dfs(node):\n if not node: return True\n if node.val != voyage[self.i]:\n return False\n self.i += 1\n if node.left and node.left.val != voyage[self.i]:\n node.left, node.right = node.right, node.left\n res.append(node.val)\n return dfs(node.left) and dfs(node.right)\n return res if dfs(root) else [-1]","repo_name":"cnkyrpsgl/leetcode","sub_path":"solutions/python3/971.py","file_name":"971.py","file_ext":"py","file_size_in_byte":672,"program_lang":"python","lang":"en","doc_type":"code","stars":215,"dataset":"github-code","pt":"15"} +{"seq_id":"2598860122","text":"# author : LJM - Jeson\n# Email : 878665865@qq.com\n# coding : utf - 8\n'''\n日志文件���\n 。什么是日志文件?当我们的项目上线后,就不能用 print了,print适用于我们在开发阶段的时候往外打印。\n 。比如,用户登录出现错误的时候,错误信息就会存放在日志文件里。\n\n 。日志级别:\n _nameToLevel = {\n 'CRITICAL': CRITICAL, # 严重警告\n 'FATAL': FATAL, # 致命的\n 'ERROR': ERROR, # 错误\n 'WARN': WARNING, # 警告\n 'WARNING': WARNING, # 警告\n 'INFO': INFO,\n 'DEBUG': DEBUG,\n 'NOTSET': NOTSET, # 不管设置\n\n\n\n\n\n }\n\n 。程序员写代码,最关注的就是日志文件了,因为里面能够看出来很多的信息。\n'''\nimport logging\n'''\n可以认为logger是一个大总管[大哥],它的下面可以管理很多个hander[小弟]\n'''\n# 1. 创建日志对象 --- getLogger()\nlogger = logging.getLogger() # 可认为是日志管理员\n\n# 2. 设置日志对象级别\nlogger.setLevel(logging.ERROR) # 参数必须为整型或者字符串类型\n\n# 3. 创建一个handler对象 [处理者]\nfile = 'log.txt'\nhandler = logging.FileHandler(file)\nhandler.setLevel(logging.ERROR)\n\n# 4. 设置格式化程序,即创建一个Formatter对象\nfmt = logging.Formatter('%(asctime)s-%(module)s-%(filename)s[%(lineno)d]-%(levelname)s:%(message)s')\nhandler.setFormatter(fmt)\n\n# 5. 将hander对象交给logger对象管理\nlogger.addHandler(handler)\n# logger.addHandler(handler1) # 如果再有handler,则再加入logger对象即可\n\ndef func():\n try:\n number = int(input('请输入一个数字:'))\n for i in range(number):\n print('----> ', i)\n except: # 如出错,则有logger对象管理\n logger.error('输入的不是一个数字!')\n finally:\n print('-------over-------')\n\nfunc()\n'''\n当输入:dafdg\nlog.txt文件出现:\n2021-11-18 23:06:11,962-23 日志文件logging-23 日志文件logging.py[50]-ERROR:输入的不是一个数字!\n'''","repo_name":"soyisou/python-tutorial","sub_path":"05 模块和文件/23 日志文件logging.py","file_name":"23 日志文件logging.py","file_ext":"py","file_size_in_byte":2049,"program_lang":"python","lang":"zh","doc_type":"code","stars":0,"dataset":"github-code","pt":"15"} +{"seq_id":"22121726210","text":"# https://www.coursera.org/learn/python-osnovy-programmirovaniya/programming/LtjxX/rodoslovnaia-podschiet-urovniei\r\n\r\n# Родословная: подсчет уровней\r\n\r\n# В генеалогическом древе у каждого человека, кроме родоначальника, есть ровно\r\n# один родитель. Каждом элементу дерева сопоставляется целое неотрицательное\r\n# число, называемое высотой. У родоначальника высота равна 0, у любого\r\n# другого элемента высота на 1 больше, чем у его родителя.Вам дано\r\n# генеалогическое древо, определите высоту всех его элементов.\r\n\r\n# Примечания:\r\n# Эта задача имеет решение сложности O(n), но вам достаточнонаписать решение\r\n# сложности O(n²) (не считая сложности обращенияк элементам словаря)\r\n# Так вот - это по-видимому таки O(n²) версия!!!\r\n\r\nparentage_dict = {}\r\nall_parents = set()\r\n\r\nwith open('input.txt', 'r') as finput:\r\n n = int(finput.readline())\r\n for line in finput:\r\n child, parent = line.split()\r\n parentage_dict[child] = parent\r\n all_parents.add(parent)\r\n\r\n# В генеалогическом древе у каждого человека,\r\n# кроме родоначальника, есть ровно один родитель,\r\n# т.е. patriarch - это 'родоначальник'\r\nfor parent in all_parents:\r\n if parent not in parentage_dict.keys():\r\n patriarch = parent\r\n break\r\n\r\ngen_depth_dict = {}\r\nfor person in parentage_dict.keys():\r\n depth = 0\r\n child = person\r\n while True:\r\n parent = parentage_dict[child]\r\n depth += 1\r\n if parent == patriarch:\r\n break\r\n child = parent\r\n gen_depth_dict[person] = depth\r\n\r\ngen_depth_dict[patriarch] = 0\r\n\r\nfor person in sorted(gen_depth_dict.keys()):\r\n print(person, gen_depth_dict[person])\r\n","repo_name":"paalso/hse_python_course","sub_path":"7/7-24.py","file_name":"7-24.py","file_ext":"py","file_size_in_byte":2210,"program_lang":"python","lang":"ru","doc_type":"code","stars":0,"dataset":"github-code","pt":"15"} +{"seq_id":"34248601190","text":"import random\n\nimport frappe\nimport jwt\nfrom frappe import _\nfrom frappe.auth import LoginManager\nfrom frappe.utils import cint, get_url, get_datetime\nfrom frappe.utils.password import check_password, passlibctx, update_password\n\n\n\ndef get_linked_user(id_type, id):\n \"\"\"\n Returns the user associated with the details\n :param id_type: either 'mobile' or 'email'\n :param id: the email/mobile\n \"\"\"\n if id_type not in (\"mobile\", \"sms\", \"email\"):\n frappe.throw(f\"Invalid id_type: {id_type}\")\n\n if id_type in (\"mobile\", \"sms\"):\n id_type = \"mobaile_no\"\n\n return frappe.db.get_value(\"User\", {id_type: id})\n\n\n\n\n\n@frappe.whitelist(allow_guest=True)\ndef get_token(user, pwd, expires_in=3600, expire_on=None, device=None):\n \"\"\"\n Get the JWT Token\n :param user: The user in ctx\n :param pwd: Pwd to auth\n :param expires_in: number of seconds till expiry\n :param expire_on: yyyy-mm-dd HH:mm:ss to specify the expiry (deprecated)\n :param device: The device in ctx\n \"\"\"\n if not frappe.db.exists(\"User\", user):\n raise frappe.ValidationError(_(\"Invalide User\"))\n\n from frappe.sessions import clear_sessions\n login = LoginManager()\n login.check_if_enabled(user)\n if not check_password(user, pwd):\n login.fail('Incorrect password', user=user)\n login.login_as(user)\n login.resume = False\n login.run_trigger('on_session_creation')\n _expires_in = 3600\n if cint(expires_in):\n _expires_in = cint(expires_in)\n elif expire_on:\n _expires_in = (get_datetime(expire_on) - get_datetime()).total_seconds()\n\n\n token = get_bearer_token(\n user=user,\n expires_in=_expires_in\n )\n frappe.local.response[\"token\"] = token[\"access_token\"]\n frappe.local.response.update(token)\n\n\ndef get_oath_client():\n client = frappe.db.get_value(\"OAuth Client\", {})\n if not client:\n # Make one auto\n client = frappe.get_doc(frappe._dict(\n doctype=\"OAuth Client\",\n app_name=\"default\",\n scopes=\"all openid\",\n redirect_urls=get_url(),\n default_redirect_uri=get_url(),\n grant_type=\"Implicit\",\n response_type=\"Token\"\n ))\n client.insert(ignore_permissions=True)\n else:\n client = frappe.get_doc(\"OAuth Client\", client)\n\n return client\n\n\ndef get_bearer_token(user, expires_in=3600):\n import hashlib\n import jwt\n import frappe.oauth\n from oauthlib.oauth2.rfc6749.tokens import random_token_generator, OAuth2Token\n\n client = get_oath_client()\n token = frappe._dict({\n 'access_token': random_token_generator(None),\n 'expires_in': expires_in,\n 'token_type': 'Bearer',\n 'scopes': client.scopes,\n 'refresh_token': random_token_generator(None)\n })\n bearer_token = frappe.new_doc(\"OAuth Bearer Token\")\n bearer_token.client = client.name\n bearer_token.scopes = token['scopes']\n bearer_token.access_token = token['access_token']\n bearer_token.refresh_token = token.get('refresh_token')\n bearer_token.expires_in = token['expires_in'] or 3600\n bearer_token.user = user\n bearer_token.save(ignore_permissions=True)\n frappe.db.commit()\n\n # ID Token\n id_token_header = {\n \"typ\": \"jwt\",\n \"alg\": \"HS256\"\n }\n id_token = {\n \"aud\": \"token_client\",\n \"exp\": int((frappe.db.get_value(\"OAuth Bearer Token\", token.access_token, \"expiration_time\") - frappe.utils.datetime.datetime(1970, 1, 1)).total_seconds()),\n \"sub\": frappe.db.get_value(\"User Social Login\", {\"parent\": bearer_token.user, \"provider\": \"frappe\"}, \"userid\"),\n \"iss\": \"frappe_server_url\",\n \"at_hash\": frappe.oauth.calculate_at_hash(token.access_token, hashlib.sha256)\n }\n id_token_encoded = jwt.encode(\n id_token, \"client_secret\", algorithm='HS256', headers=id_token_header)\n id_token_encoded = frappe.safe_decode(id_token_encoded)\n token.id_token = id_token_encoded\n frappe.flags.jwt = id_token_encoded\n return token\n\n\n@frappe.whitelist()\ndef get_jwt_token():\n \"\"\"\n Get jwt token for the active user\n \"\"\"\n return get_bearer_token(\n user=frappe.session.user, expires_in=86400\n )[\"access_token\"]\n","repo_name":"anvilerp/jwt_frappe","sub_path":"jwt_frappe/utils/auth.py","file_name":"auth.py","file_ext":"py","file_size_in_byte":3992,"program_lang":"python","lang":"en","doc_type":"code","stars":6,"dataset":"github-code","pt":"15"} +{"seq_id":"7498506921","text":"# -*- coding: utf-8 -*-\n\nimport requests\nimport icalendar\nfrom datetime import datetime\nfrom datetime import date\nfrom datetime import timedelta\n\n\nclass Client(object):\n\n def __init__(self, url, charset=None):\n self.url = url\n self.charset = charset\n self.events = []\n self.timeout = 60\n self.__load()\n\n def __load(self):\n r = requests.get(self.url, timeout=self.timeout)\n r.raise_for_status()\n\n # requests normally uses encoding returned by \"Content-type\" header.\n # If charset is set, this overwrites the detected character encoding.\n if self.charset is not None:\n r.encoding = self.charset\n\n cal = icalendar.Calendar.from_ical(r.text)\n self.events = []\n\n for event in cal.walk('vevent'):\n title = None\n if \"SUMMARY\" in event:\n title = event[\"SUMMARY\"]\n dtstart = event[\"DTSTART\"].dt\n dtend = event[\"DTEND\"].dt\n self.events.append({\n \"title\": title,\n \"start\": dtstart,\n \"end\": dtend,\n })\n\n # sort events by start datetime\n def getdatetime(event):\n if isinstance(event[\"start\"], date):\n return datetime.combine(event[\"start\"], datetime.min.time())\n return event[\"start\"]\n self.events = sorted(self.events, key=getdatetime)\n\n def next_events(self, num=10):\n \"\"\"\n Returns the next num events from the calendar\n \"\"\"\n now = datetime.utcnow() + timedelta(hours=5)\n out = []\n for event in self.events:\n end = event[\"end\"]\n if isinstance(end, date):\n end = datetime.combine(end, datetime.min.time())\n if end > now:\n out.append(event)\n if len(out) >= num:\n break\n return out\n","repo_name":"netzbegruenung/schaufenster","sub_path":"service/api/events.py","file_name":"events.py","file_ext":"py","file_size_in_byte":1901,"program_lang":"python","lang":"en","doc_type":"code","stars":3,"dataset":"github-code","pt":"15"} +{"seq_id":"13922934292","text":"# x Open for exclusive creation, failing if the file already exists.\n# file = open(\"text-x.txt\", \"x\")\n\n\n# w Creates a new file for writing. Overwrites the file if the file exists.\n# file = open(\"text-w.txt\", \"w\")\n\n\ndef write_to_file(file_path, mode, text):\n file = open(file_path, mode)\n file.write(text)\n file.close()\n\n\nwrite_to_file(\"numbers.txt\", \"w\", \"\"\"1\n2\n3\n4\n5\n6\n\"\"\")\n\n\n# a Creates a new file - if the file does not exist, or append to exist.\n# file = open(\"text-a.txt\", \"a\")\n\ndef write_to_file(file_path, mode, text):\n with open(file_path, mode) as file:\n file.write(text)\n\n\ndata = 'I just created my first file!'\nwrite_to_file(\"my_first_file.txt\", \"a\", data)\n\n\n","repo_name":"Andon-ov/Python-Advanced","sub_path":"13_file_handling_lab/file_writer.py","file_name":"file_writer.py","file_ext":"py","file_size_in_byte":691,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"15"} +{"seq_id":"40385263226","text":"class Army:\n def __init__(self):\n self.detachments = []\n self.points = 0\n self.power = 0\n \n def addDetachment(self, Detachment):\n self.detachments.append(Detachment)\n self.points += Detachment.pointsCost\n self.power += Detachment.powerCost\n \nclass Detachment:\n def __init__(self):\n self.HQs = []\n self.troops = []\n self.elites = []\n self.fastAttacks = []\n self.heavySupports = []\n self.flyers = []\n self.transports = []\n self.pointsCost = 0\n self.powerCost = 0\n \n def addHQ(self, Unit):\n if Unit.role == \"HQ\":\n self.HQs.append(Unit)\n self.pointsCost += Unit.totalPoints()\n self.powerCost += Unit.powerCost\n \n def addTroop(self, Unit):\n if Unit.role == \"Troop\":\n self.HQs.append(Unit)\n self.pointsCost += Unit.totalPoints()\n self.powerCost += Unit.powerCost\n \n def addElites(self, Unit):\n if Unit.role == \"Elite\":\n self.HQs.append(Unit)\n self.pointsCost += Unit.totalPoints()\n self.powerCost += Unit.powerCost\n \n def addFastAttack(self, Unit):\n if Unit.role == \"Fast Attack\":\n self.HQs.append(Unit)\n self.pointsCost += Unit.totalPoints()\n self.powerCost += Unit.powerCost\n \n def addHeavySupport(self, Unit):\n if Unit.role == \"Heavy Support\":\n self.HQs.append(Unit)\n self.pointsCost += Unit.totalPoints()\n self.powerCost += Unit.powerCost\n \n def addFlyer(self, Unit):\n if Unit.role == \"Flyer\":\n self.HQs.append(Unit)\n self.pointsCost += Unit.totalPoints()\n self.powerCost += Unit.powerCost\n \n def addTransports(self, Unit):\n if Unit.role == \"Transport\":\n self.HQs.append(Unit)\n self.pointsCost += Unit.totalPoints()\n self.powerCost += Unit.powerCost\n \n def removeHQ(self, Unit):\n self.HQs.remove(Unit)\n self.pointsCost -= Unit.totalPoints()\n self.powerCost -= Unit.powerCost\n \n def removeTroop(self, Unit):\n self.troops.remove(Unit)\n self.pointsCost -= Unit.totalPoints()\n self.powerCost -= Unit.powerCost\n \n def removeElites(self, Unit):\n self.elites.remove(Unit)\n self.pointsCost -= Unit.totalPoints()\n self.powerCost -= Unit.powerCost\n \n def removeFastAttack(self, Unit):\n self.fastAttacks.remove(Unit)\n self.pointsCost -= Unit.totalPoints()\n self.powerCost -= Unit.powerCost\n \n def removeHeavySupport(self, Unit):\n self.heavySupports.remove(Unit)\n self.pointsCost -= Unit.totalPoints()\n self.powerCost -= Unit.powerCost\n \n def removeFlyer(self, Unit):\n self.flyers.remove(Unit)\n self.pointsCost -= Unit.totalPoints()\n self.powerCost -= Unit.powerCost\n \n def removeTransports(self, Unit):\n self.transports.remove(Unit)\n self.pointsCost -= Unit.totalPoints()\n self.powerCost -= Unit.powerCost\n \n def isLegal(self):\n return ((len(self.HQs) <= self.HQsBounds[1] \n and len(self.HQs) >= self.HQsBounds[0]) \n and (len(self.troops) <= self.troopsBounds[1] \n and len(self.troops) >= self.troopsBounds[0])\n and (len(self.elites) <= self.elitesBounds[1]\n and len(self.elites) >= self.elitesBounds[0])\n and (len(self.fastAttacks) <= self.fastAttacksBounds[1]\n and len(self.fastAttacks) >= self.fastAttacksBounds[0])\n and (len(self.heavySupports) <= self.heavySupportsBounds[1]\n and len(self.heavySupports) >= self.heavySupportsBounds[0])\n and (len(self.flyers) <= self.flyersBounds[1]\n and len(self.flyers) >= self.flyersBounds[0]))\n \nclass Patrol(Detachment):\n def __init__(self):\n super().__init__()\n self.HQsBounds = (1,2)\n self.troopsBounds = (1,3)\n self.elitesBounds = (0,2)\n self.fastAttacksBounds = (0,2)\n self.heavySupportsBounds = (0,2)\n self.flyersBounds = (0,2)\n self.commandCost = 2\n\nclass Battalion(Detachment):\n def __init__(self):\n super().__init__()\n self.HQsBounds = (2,3)\n self.troopsBounds = (3,6)\n self.elitesBounds = (0,6)\n self.fastAttacksBounds = (0,3)\n self.heavySupportsBounds = (0,3)\n self.flyersBounds = (0,2)\n self.commandCost = 3\n \nclass Brigade(Detachment):\n def __init__(self):\n super().__init__()\n self.HQsBounds = (3,5)\n self.troopsBounds = (6,12)\n self.elitesBounds = (3,8)\n self.fastAttacksBounds = (3,5)\n self.heavySupportsBounds = (3,5)\n self.flyersBounds = (0,2)\n self.commandCost = 4\n \nclass Vanguard(Detachment):\n def __init__(self):\n super().__init__()\n self.HQsBounds = (1,2)\n self.troopsBounds = (0,3)\n self.elitesBounds = (3,6)\n self.fastAttacksBounds = (0,2)\n self.heavySupportsBounds = (0,2)\n self.flyersBounds = (0,2) \n self.commandCost = 3\n\nclass Spearhead(Detachment):\n def __init__(self):\n super().__init__()\n self.HQsBounds = (1,2)\n self.troopsBounds = (0,3)\n self.elitesBounds = (0,2)\n self.fastAttacksBounds = (0,2)\n self.heavySupportsBounds = (3,6)\n self.flyersBounds = (0,2)\n self.commandCost = 3\n \nclass Outrider(Detachment):\n def __init__(self):\n super().__init__()\n self.HQsBounds = (1,2)\n self.troopsBounds = (0,3)\n self.elitesBounds = (0,2)\n self.fastAttacksBounds = (3,6)\n self.heavySupportsBounds = (0,2)\n self.flyersBounds = (0,2)\n self.commandCost = 3\n","repo_name":"JordanFoss/Warhammer40K-Simulation","sub_path":"Army.py","file_name":"Army.py","file_ext":"py","file_size_in_byte":5965,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"15"} +{"seq_id":"6927164275","text":"from unicodedata import normalize, combining\nfrom sys import argv\nfrom bs4 import BeautifulSoup as bs\nfrom requests import get, status_codes, codes, utils, exceptions\n\nlist_with_initial_args = argv\nbase_url = 'https://www.vagalume.com.br/'\n\n#A intensão da normalize_arg é fazer a conversão de caracteres com acentuação para sem acentuação. Ex.: 'ã' se torna 'a'\ndef normalize_arg(arg):\n #faço a conversão dos caracteres especiais e converto para string\n convert_to_normalized = normalize('NFKD', str(arg))\n #cria a string sem a acentuação fazendo a combinação dos carcteres convertidos.\n band_s_name_without_accents = ''.join([char for char in convert_to_normalized if not combining(char)])\n return band_s_name_without_accents\n\n#Para controlar o argumento da banda e o -top5\ndef check_amount_args(band_s_name):\n if '-top5' in list_with_initial_args:\n #faço uma cópia da lista original porque vou utilizar ela para fazer outros controles\n modified_list_arg = list_with_initial_args[:]\n modified_list_arg.remove('-top5')\n band_s_name = '-'.join(modified_list_arg[1:]).lower()\n return normalize_arg(band_s_name)\n else:\n band_s_name = '-'.join(list_with_initial_args[1:]).lower()\n return normalize_arg(band_s_name)\n\nband_s_name\t= check_amount_args(list_with_initial_args)\n\npage_band = base_url + band_s_name\n\n#Checagem para identificar se não foi informado a banda ou o nome está errado e exibir um pequeno help para o uso correto.\ndef check_args_is_ok(page_band):\n if page_band == base_url:\n print('''\nNão foi informado o nome da banda. Siga o exemplo de uso: python crawler.py Zé do Caroço -top5\nVocê pode usar o comando -top5 para exibir as 5 músicas mais conhecidas da banda.\nPor padrão serão exibidas as 25 primeiras músicas em ordem alfabética''')\n if get(page_band).status_code == codes['not_found']:\n print('\\nNão foi localizada essa banda. Verifique a ortografia.')\n print('''\nDicas: \n* Bandas que possuem acento nas letras (Ex.: Titãs) você pode escrever com o acento.\n* Bandas que tem caracteres especias como apóstrofo ( ' ), crifrão ( $ ), 'e comercial'\n ( & ) e outros, você deve escrever o nome da banda sem o carácter especial.\n- Ex1.: para Gun's n Roses utilize Guns n Roses;\n- Ex2.: para Eddy B & Tim Gunter utilize Eddy B Tim Gunter\n- Ex2.: para Ca$h Out utilize Cah Out''')\n\n#Aqui vou gerar as músicas de acordo com as opções passadas\ndef mount_list_of_music(page_band):\n check_args_is_ok(page_band)\n try:\n get_page_band = get(page_band)\n #Quando fiz o teste usando o VS Code do Windows, a página veio no encoding ISO-8859-1 então fiz uma conversão explicita\n get_page_band.encoding = 'utf-8'\n html_page = bs(get_page_band.text, 'html.parser')\n all_musics = html_page.find_all('div', {'class': 'lineColLeft'})\n list_with_everything = list()\n for music in all_musics:\n music_name = music.find('a').text\n list_with_everything.append(music_name)\n #Tratamento para organizar melhor a lista com as músicas \n clean_list_with_musics = list(dict.fromkeys(list_with_everything))\n if len(list_with_initial_args) >= 3:\n if '-top5' in list_with_initial_args:\n for music in clean_list_with_musics[0:5]:\n print(music)\n else:\n sorted_list = sorted(clean_list_with_musics)\n for music in sorted_list[0:25]:\n print(music)\n else:\n sorted_list = sorted(clean_list_with_musics)\n for music in sorted_list[0:25]:\n print(music)\n except exceptions.RequestException:\n print('Não foi possível acessar o site. Verifique a sua internet ou tente mais tarde.')\n\nmount_list_of_music(page_band)","repo_name":"jairtontf/Crawler","sub_path":"crawler.py","file_name":"crawler.py","file_ext":"py","file_size_in_byte":3882,"program_lang":"python","lang":"pt","doc_type":"code","stars":0,"dataset":"github-code","pt":"15"} +{"seq_id":"25765142907","text":"#!/usr/bin/env python\nimport rospy\nfrom std_msgs.msg import Header\nfrom std_msgs.msg import String\nfrom sensor_msgs.msg import JointState\nfrom std_srvs.srv import SetBool, SetBoolResponse\nimport serial\nimport struct\nfrom mainpkg.msg import MyGoal\nimport re, json, sys, time\nsys.path.append(\"..\")\nfrom communication.curi_communication_socket import curi_communication_socket\nfrom base.curi_robot_control import curi_robot_control, robot, ROBOT_STATE, CONTROL_SPACE, CONTROL_MODE\nfrom communication.curi_ros_trajectory_action import curi_ros_trajectory_action\nimport numpy as np\nimport actionlib\nfrom control_msgs.msg import FollowJointTrajectoryAction\n\n\ns_open = [0x01, 0x05, 0x00, 0x00, 0xFF, 0x00, 0x8C, 0x3A]\ns_close = [0x01, 0x05, 0x00, 0x00, 0x00, 0x00, 0xCD, 0xCA]\nser = serial.Serial(\n port='/dev/usb_0',\n baudrate=9600,\n parity=serial.PARITY_NONE,\n stopbits=serial.STOPBITS_ONE,\n bytesize=serial.EIGHTBITS\n )\n\nclass curi_ros_driver(robot):\n def __init__(self):\n self.JointSize = 7\n self.rate = rospy.Rate(20)\n self.HighAccuracy=1\n robot.__init__(self, self.JointSize, np.array([0.0] * self.JointSize))\n self.socket_communication = curi_communication_socket(self.JointSize, \"192.168.0.1\", 11230, \"192.168.0.34\", 11231)\n\n self.pub = rospy.Publisher('joint_states', JointState, queue_size=5)\n self.sub_new=rospy.Subscriber('ManualPosCmd', MyGoal, self.ManualPosCmd_handle)\n self.gripper_srv_ = rospy.Service('/gripper/run', SetBool, self.gripper_handle)\n\n self.armserver = actionlib.ActionServer(\"palletizer_arm/follow_joint_trajectory\", FollowJointTrajectoryAction, self.on_goal_arm, self.on_cancel_arm, auto_start=True)\n\n def gripper_handle(self,req):\n resp = SetBoolResponse()\n if req.data:\n data = struct.pack(\"%dB\"%(len(s_open)),*s_open)\n ser.write(data) \n resp.success = True\n resp.message = 'openGripper'\n else:\n data = struct.pack(\"%dB\"%(len(s_close)),*s_close)\n ser.write(data) \n resp.success = True\n resp.message = 'closeGripper'\n return resp\n \n def ArriveCheck(self):\n Flag_Arrive=1 # 0 means arrived\n if self.HighAccuracy == 0:\n Err_limit_T=0.005\n Err_limit_R=0.01\n else:\n Err_limit_T=0.0002\n Err_limit_R=0.001\n for i in range(self.JointSize):\n if i==0 or i==5 or i==6: # Translate\n if abs(self.GoalPos[i]-self.joint_states.position[i])>=Err_limit_T:\n Flag_Arrive=0\n else: # Rotate\n if abs(self.GoalPos[i]-self.joint_states.position[i])>=Err_limit_R:\n Flag_Arrive=0\n return Flag_Arrive\n\n def SendPosCmd(self):\n for i in range(self.JointSize):\n if i==0 or i==5 or i==6: # Translate\n Vel_limit=0.1\n else: # Rotate\n Vel_limit=0.7\n self.JointCmdVel[i] = 2*(self.GoalPos[i]-self.joint_states.position[i])\n if self.JointCmdVel[i] > Vel_limit:\n self.JointCmdVel[i] = Vel_limit\n elif self.JointCmdVel[i] < -Vel_limit:\n self.JointCmdVel[i] = -Vel_limit\n self.JointCmdMod[i] = CONTROL_MODE.CONTROL_MODE_VELOCITY\n vel=self.JointCmdVel # Moveit order\n self.JointCmdVel=[vel[0],vel[5],vel[6],vel[1]*180/np.pi,vel[2]*180/np.pi,vel[3]*180/np.pi,vel[4]*180/np.pi] # Low machine order\n self.ControlSpace = CONTROL_SPACE.CONTROL_SPACE_JOINT\n self.Command = ROBOT_STATE.RUNNING_STATE_ONLINE\n message = self.packRobotCommand()\n self.socket_communication.send(message)\n\n def ManualPosCmd_handle(self, msg): # The unit is m,rad\n self.GoalPos=msg.Position\n self.HighAccuracy=msg.HighAccuracy\n while not rospy.is_shutdown() and self.ArriveCheck()==0:\n self.SendPosCmd()\n self.rate.sleep()\n self.JointCmdVel=[0,0,0,0,0,0,0]\n message = self.packRobotCommand()\n self.socket_communication.send(message)\n print('Arrived success by Manual Cmd')\n \n def on_goal_arm(self, goal_handle): # Moveit setting: 240 374.5 175\n goal_handle.set_accepted()\n goal_handle.set_succeeded()\n for i in range(len(goal_handle.get_goal().trajectory.points)):\n TempP=goal_handle.get_goal().trajectory.points[i].positions\n self.GoalPos=[TempP[0],TempP[1],TempP[2],TempP[3],TempP[4],self.joint_states.position[5],self.joint_states.position[6]]\n cur_time=time.time()\n while self.ArriveCheck()==0 and time.time()-cur_time<0.2:\n self.SendPosCmd()\n self.rate.sleep()\n while self.ArriveCheck()==0:\n self.SendPosCmd()\n self.rate.sleep()\n self.JointCmdVel=[0,0,0,0,0,0,0]\n message = self.packRobotCommand()\n self.socket_communication.send(message)\n print('Arrived success by Moveit')\n\n def on_cancel_arm(self, goal_handle):\n print('ON cancel')\n \n def pub_joint_states(self):\n self.socket_communication.open()\n self.joint_states = JointState()\n self.joint_states.header = Header()\n self.joint_states.name = [\"Joint1\", \"Joint2\", \"Joint3\", \"Joint4\", \"Joint5\", \"Joint6\", \"Joint7\"]\n while not rospy.is_shutdown():\n data = self.socket_communication.recieve(flag=1)\n if data:\n self.unpackRobotState(data.strip(\"b'\")) \n pos = self.JointCurPos[:] # Low machine order\n self.joint_states.position = [pos[0]*180/np.pi,pos[3],pos[4],pos[5],pos[6],pos[1]*180/np.pi,pos[2]*180/np.pi] # Moveit order\n vel = self.JointCurVel[:]\n self.joint_states.velocity = [vel[0],vel[3],vel[4],vel[5],vel[6],vel[1],vel[2]]\n eff = self.JointCurTor[:]\n self.joint_states.effort = [eff[0],eff[3],eff[4],eff[5],eff[6],eff[1],eff[2]]\n self.joint_states.header.stamp = rospy.Time.now()\n self.pub.publish(self.joint_states)\n self.rate.sleep()\n self.Command = ROBOT_STATE.RUNNING_STATE_HOLDON\n message = self.packRobotCommand()\n self.socket_communication.send(message)\n self.socket_communication.close()\n \nif __name__ == '__main__':\n try:\n rospy.init_node('curi_ros_driver')\n myclass = curi_ros_driver()\n myclass.pub_joint_states()\n except rospy.ROSInterruptException:\n pass","repo_name":"Danielsong007/catkin_ws","sub_path":"src/robot_controller/scripts/curi_ros_driver.py","file_name":"curi_ros_driver.py","file_ext":"py","file_size_in_byte":6667,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"15"} +{"seq_id":"29341965972","text":"import os\nimport fnmatch\nimport difflib\nimport re\nfrom idlecolors import *\n\nimport tkinter as tk\nfrom tkinter import *\nfrom tkinter import filedialog\nimport ctypes\n\n# Function to choose folder and set rootFolderInitial and rootFolderDelta variables\ndef chooseFolder():\n root = tk.Tk()\n root.withdraw()\n file_path = filedialog.askdirectory()\n return file_path\n\n# Message box to notify user to select Initial Root Folder (rootFolderInitial)\nMessageBox = ctypes.windll.user32.MessageBoxW\nMessageBox(None, \"Please select the root folder of the initial files\", \"Choose Initial Folder\", 0)\n\n# Set rootFolderInitial to user's selected folder\nrootFolderInitial = os.path.abspath(chooseFolder())\n\n# Message box to notify user to select Delta Root Folder (rootFolderDelta)\nMessageBox = ctypes.windll.user32.MessageBoxW\nMessageBox(None, \"Please select the root folder of the delta files\", \"Choose Delta Folder\", 0)\n\n# Set rootFolderDelta to user's selected folder\nrootFolderDelta = os.path.abspath(chooseFolder())\n\nprint('Compiling data, please wait...')\n\n# Temp list to store all initial files; didn't want to do this but I was getting bugs when trying to dynamically add files to the InitialFilePaths list\nTempInitialList = []\n\n# Lists for the Intial and Delta file paths, these will be a 1-1 match when comparing files\nInitialFilePaths = []\nDeltaFilePaths = []\n\n# Hostnames for all delta configs\nDeltaNameList = []\n\n# Add all delta files into the DeltaFilePaths list\nfor subdir, dirs, files in os.walk(rootFolderDelta):\n \n for file in files:\n DeltaFilePaths.append(os.path.join(subdir, file))\n \n# For each file in the list, open the file, pull the 'hostname' string, remove 'hostname' (get the router/switch name by itself) strip all spaces/newlines and add the name to the DeltaNameList \nfor fNames in DeltaFilePaths:\n \n with open(fNames, 'r') as dFileHostName:\n \n dFile_Name = dFileHostName.readlines()\n \n for i, line in enumerate(dFile_Name):\n \n if 'hostname' in line:\n \n DeltaNameList.append(dFile_Name[i].replace('hostname', '').strip())\n \n# Add all initial files into a temp list.\nfor subdir, dirs, files in os.walk(rootFolderInitial):\n\n for file in files:\n TempInitialList.append(os.path.join(subdir, file))\n\n# For each item in the DeltaNameList (router/switch names) open each file in the TempInitialList (Initial files). If the hostname of the file in TempInitalList matches with a name in DeltaNameList\n# add the file from TempInitialList to the InitialFilePaths list. This isn't efficient but it works.\nfor items in DeltaNameList:\n \n for things in TempInitialList:\n \n with open(things, 'r') as IFileHostName:\n \n IFile_Name = IFileHostName.readlines()\n \n for i, line in enumerate(IFile_Name):\n \n if 'hostname' in line:\n \n if IFile_Name[i].replace('hostname', '').strip() == items:\n InitialFilePaths.append(things)\n\n# There should now be a 1-1 config list match between InitialFilePaths and DeltaFilePaths, iterate through each and print the differences from\n# InitialFilePaths to DeltaFilePaths, a (-) in green indicates something exclusive to Initial, a (+) indicates something exclusive to delta. A (-) immediately followed by (+) indicates\n# a change in the string (partially similar).\ni = 0\n\nwhile i < len(InitialFilePaths):\n\n print(f\"##########{InitialFilePaths[i]}##########\")\n print(f\"##########{DeltaFilePaths[i]}##########\")\n print()\n \n\n with open(InitialFilePaths[i], 'r') as rFile1:\n f1_text = rFile1.readlines()\n\n with open(DeltaFilePaths[i], 'r') as rFile2:\n f2_text = rFile2.readlines()\n\n for line in difflib.unified_diff(f1_text, f2_text, fromfile=InitialFilePaths[i], tofile=DeltaFilePaths[i], lineterm = '\\n', n = 5):\n if re.search(\"^[+]\", line):\n printc(red(line))\n elif re.search(\"^-\", line):\n printc(green(line))\n else:\n printc(black(line))\n \n i += 1\n","repo_name":"JovanGeary94/Mega-Meld-Windows-","sub_path":"Meld.py","file_name":"Meld.py","file_ext":"py","file_size_in_byte":4179,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"15"} +{"seq_id":"10303197668","text":"#!/usr/bin/python\n# -*- coding:utf-8 -*-\n# create time\n\n\nclass Person:\n def __init__(self, name, hp, ad, sex, job):\n self.username = name\n self.hp = hp\n self.ad = ad\n self.sex = sex\n self.job = job\n\n def attack(self, dog):\n dog.hp -= self.ad\n print('%s打了%s,%s掉了%s血' % (self.username, dog.name, dog.name, self.ad))\n\n\nalex = Person('alex', 100, 5, '不详', '乞丐')\n\n\nclass Dog:\n def __init__(self, name, kind, hp, ad):\n self.name = name\n self.kind = kind\n self.hp = hp\n self.ad = ad\n\n def bite(self, person):\n person.hp -= self.ad\n print('%s咬了%s,%s掉了%s血' % (self.name, person.username, person.username, self.ad))\n\n\nwang_cai = Dog('wangcai', 'teddy', 500, 200)\nwang_cai.bite(alex)\nalex.attack(wang_cai)\nprint(wang_cai.hp, alex.hp)\n","repo_name":"wlj572831/Class_27","sub_path":"day07/课上/3.面向对象.py","file_name":"3.面向对象.py","file_ext":"py","file_size_in_byte":854,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"15"} +{"seq_id":"17518291641","text":"import win32con, win32api, win32gui\nfrom .system import system\nimport os\n\ndef set_wallpaper(imagepath):\n key = win32api.RegOpenKeyEx(win32con.HKEY_CURRENT_USER,\n \"Control Panel\\\\Desktop\",0,win32con.KEY_SET_VALUE)\n win32api.RegSetValueEx(key, \"WallpaperStyle\", 0, win32con.REG_SZ, \"2\")\n #2拉伸适应桌面,0桌面居中\n win32api.RegSetValueEx(key, \"TileWallpaper\", 0, win32con.REG_SZ, \"0\")\n # targetpath = os.path.join(system.appdatadir, \"wallpaper.jpg\")\n targetpath = imagepath\n win32gui.SystemParametersInfo(win32con.SPI_SETDESKWALLPAPER, targetpath, 1+2)\n\n","repo_name":"cosmozhang1995/python-wallpaper","sub_path":"wallpaper/wallpaper.py","file_name":"wallpaper.py","file_ext":"py","file_size_in_byte":589,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"15"} +{"seq_id":"13304150902","text":"# from unicodedata import category\nfrom django import forms\nfrom registration.models import Scout, MasterCity, MasterState, MasterCategory,MasterGroup\n\n\n\n\n \ncity = MasterCity.objects.raw( 'select `id`, `city` from `registration_mastercity`')\ncitychoice=[]\nfor i in city:\n \n l=[]\n l.append(i.id)\n l.append(i.city)\n \n citychoice.append(l)\n\ngroup=MasterGroup.objects.raw( 'select `id` from `registration_mastergroup`')\ngroup_choice=[]\nfor i in group:\n \n l=[]\n l.append(i.id)\n l.append(i.id)\n \n group_choice.append(l)\n\nclass NameForm(forms.Form):\n \n \n\n city= forms.CharField(label='City ', widget=forms.Select(choices=citychoice))\n group= forms.CharField(label='Group ', widget=forms.Select(choices=group_choice))\n crete_update= forms.CharField(label='Action ', widget=forms.Select(choices=[[\"update\",\"Update\"],[\"create\",\"Create\"],[\"download\",\"Download\"]]))\n\nclass NameForm2(forms.Form):\n \n \n\n city= forms.CharField(label='City', widget=forms.Select(choices=citychoice))\n group= forms.CharField(label='Group', widget=forms.Select(choices=group_choice))\n\n\n\n\nclass playerForm(forms.Form):\n \n \n\n player= forms.CharField(label='Scout')\n group= forms.CharField(label='category')\n ","repo_name":"Shanukarn11/scout","sub_path":"scoutikf/teams/forms.py","file_name":"forms.py","file_ext":"py","file_size_in_byte":1248,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"15"} +{"seq_id":"29888073529","text":"from flag import flag\nimport argparse as argprs\n\nif __name__ == '__main__':\n\n parser = argprs.ArgumentParser(description='Drawing japanese flag!:)')\n right_arg = parser.add_argument('n', type=int, help='Size of flag.')\n args = parser.parse_args()\n\n fl = flag(args.n)\n\n print(fl)\n\n\n","repo_name":"AlexeyLyapeshkin/Japanese-Flag-Drawer","sub_path":"test.py","file_name":"test.py","file_ext":"py","file_size_in_byte":296,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"15"} +{"seq_id":"74500992650","text":"# Funções e Iteractive Help\r\ndef contador(i, f, p):\r\n \"\"\"\r\n -> Teste Interactive Help nas funçoes criadas <-\r\n => Faz a contagem e mostra na tela <=\r\n :param i: inicio da contagem\r\n :param f: final da contagem\r\n :param p: passos da contagem\r\n :return: sem retorno\r\n \"\"\"\r\n c = i\r\n while c <= f:\r\n print(f'{c}', end='')\r\n c += p\r\n print('FIM!')\r\n\r\n# criado por mim\r\nhelp(contador)\r\n# nativo python\r\nhelp(input)\r\n\r\n# Parâmetros Opcionais\r\ndef somar(a=0, b=0, c=0):\r\n \"\"\"\r\n -> Faz a soma de 3 valores e mostra o resultado na tela <-\r\n :param a: o primeiro valor\r\n :param b: o segundo valor\r\n :param c: o terceiro valor\r\n :return: sem retorno\r\n \"\"\"\r\n s = a + b + c\r\n print(f'A soma vale {s}')\r\n\r\n\r\nsomar(3, 2, 5)\r\nsomar(3, 5)\r\nsomar(5)\r\nsomar()\r\nhelp(somar)\r\n\r\n# Escopo de Variáveis\r\ndef teste():\r\n # variavel local\r\n global n\r\n x = 8\r\n n = x + n\r\n print(f'Na função o valor de x é {x}')\r\n print(f'Na função o valor de n é {n}')\r\n\r\n# variavel global\r\nn = 2\r\n# print(f'No programa o valor de x é {x}')\r\nprint(f'No programa o valor de n é {n}')\r\nteste()\r\n\r\n# Retorno de valores\r\n\r\ndef somar2 (a=0, b=0, c=0):\r\n s = a + b + c\r\n return s\r\n\r\n\r\nr1 = somar2(3, 5, 2)\r\nr2 = somar2(2, 2)\r\nr3 = somar2(6)\r\n\r\nprint(f'Os resultados foram {r1}, {r2} e {r3}')\r\n\r\n# Na prática\r\n\r\ndef fatorial(num=1):\r\n f = 1\r\n for c in range(num, 0, -1):\r\n f *= c\r\n return f\r\n\r\n\r\nn = int(input('Digite um número: '))\r\nprint(f'O fatorial de {n} é igual a {fatorial(n)}')","repo_name":"jefersonar-cmd/repositorio-curso-em-video","sub_path":"python_mundo3/Aulas/aula21.py","file_name":"aula21.py","file_ext":"py","file_size_in_byte":1563,"program_lang":"python","lang":"pt","doc_type":"code","stars":0,"dataset":"github-code","pt":"15"} +{"seq_id":"3129664564","text":"\"\"\" Module to search for files in a directory \"\"\"\n#pylint: disable=import-error,invalid-name,broad-except,superfluous-parens\nimport re\nimport pathlib\nimport itertools\n\nfrom pyrevit import script, forms\n\nlogger = script.get_logger()\n\n\nclass FileFinder:\n \"\"\"\n Handles the file search in a directory\n\n Attributes\n ----------\n directory : str\n Path of the target directory\n paths : set()\n Holds absolute paths of search result\n\n Methods\n -------\n search(str)\n Searches in the target directory for the given glob pattern.\n Adds absolute paths to self.paths.\n\n exclude_by_pattern(str)\n Filters self.paths by the given regex pattern.\n \"\"\"\n def __init__(self, directory):\n \"\"\"\n Parameters\n ----------\n directory : str\n Absolute path to target directory.\n \"\"\"\n self.directory = directory\n self.paths = set()\n\n def search(self, pattern):\n \"\"\"\n Searches in the target directory for the given glob pattern.\n Adds absolute paths to self.paths.\n\n Parameters\n ----------\n pattern : str\n Glob pattern\n \"\"\"\n result = pathlib.Path(self.directory).rglob(pattern)\n for path in result:\n logger.debug('Found file: {}'.format(path))\n self.paths.add(str(path))\n if len(self.paths) == 0:\n logger.debug(\n 'No {} files in \"{}\" found.'.format(pattern, self.directory))\n forms.alert(\n 'No {} files in \"{}\" found.'.format(pattern, self.directory))\n script.exit()\n\n def exclude_by_pattern(self, pattern):\n \"\"\"\n Filters self.paths by the given regex pattern.\n\n Parameters\n ----------\n pattern : str\n Regular expression pattern\n \"\"\"\n self.paths = itertools.ifilterfalse( #pylint: disable=no-member\n re.compile(pattern).match, self.paths)\n","repo_name":"eirannejad/pyRevit","sub_path":"extensions/pyRevitTools.extension/pyRevit.tab/Project.panel/ptools.stack/Family.pulldown/Load Families.pushbutton/lib/file_utils.py","file_name":"file_utils.py","file_ext":"py","file_size_in_byte":1982,"program_lang":"python","lang":"en","doc_type":"code","stars":1092,"dataset":"github-code","pt":"15"} +{"seq_id":"73926731210","text":"'''\nGiven a circular array (the next element of the last element is the first element of the array), print the Next Greater Number for every element. The Next Greater Number of a number x is the first greater number to its traversing-order next in the array, which means you could search circularly to find its next greater number. If it doesn't exist, output -1 for this number.\n\nThe length of given array won't exceed 10000.\n\nExample\nExample 1:\n\nInput: [1,2,1]\nOutput: [2,-1,2]\nExplanation: The first 1's next greater number is 2;\nThe number 2 can't find next greater number;\nThe second 1's next greater number needs to search circularly, which is also 2.\nExample 2:\n\nInput: [1]\nOutput: [-1]\nExplanation:\nThe number 1 can't find next greater number.\n'''\n\n\n'''\n[1, 2, 1, 1, 0 3, 1]\n[2, 3, 3, 3, 3 -1, 2]\n\n\nmax stack , reverse\n\n'''\n\nclass Solution:\n \"\"\"\n @param nums: an array\n @return: the Next Greater Number for every element\n \"\"\"\n def nextGreaterElements(self, nums):\n '''\n [1,2,1,1,3,2,3] iterate -> [1,2,1,1,3,2,3,1,2,1,1,3,2]\n init reversed mono stack for idx, 2n - 1 ~ n\n start from n - 1 to 0\n '''\n if not nums or len(nums) == 0:\n return []\n\n n = len(nums)\n idx_mono_stack = []\n res = [-1 for _ in range(n)]\n\n # init\n for i in range(n - 2, -1, -1):\n while len(idx_mono_stack) > 0 and nums[i] >= nums[idx_mono_stack[-1]]:\n idx_mono_stack.pop()\n idx_mono_stack.append(i)\n\n # run results reversely\n for i in range(n - 1, -1, -1):\n while len(idx_mono_stack) > 0 and nums[i] >= nums[idx_mono_stack[-1]]:\n idx_mono_stack.pop()\n if len(idx_mono_stack) > 0:\n res[i] = nums[idx_mono_stack[-1]]\n idx_mono_stack.append(i)\n\n return res\n\n\n\n\nclass Solution:\n \"\"\"\n @param nums: an array\n @return: the Next Greater Number for every element\n \"\"\"\n def nextGreaterElements(self, nums):\n n = len(nums)\n res = [-1 for _ in range(n)]\n for i in range(n):\n for j in range(1, n):\n idx = (i + j) % n\n if nums[idx] > nums[i]:\n res[i] = nums[idx]\n break\n\n return res\n\n","repo_name":"ctc316/algorithm-python","sub_path":"Lintcode/G_Practice/Tag_Stack/1201. Next Greater Element II.py","file_name":"1201. Next Greater Element II.py","file_ext":"py","file_size_in_byte":2296,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"15"} +{"seq_id":"5618140430","text":"from django.urls import include, path, re_path\r\nfrom . import views\r\n\r\nurlpatterns = [\r\n path('', views.home, name=\"name\"),\r\n path('login/', views.login, name=\"login\"),\r\n path('logout/', views.logout, name=\"logout\"),\r\n path('register/', views.register, name=\"register\"),\r\n path('addclient/', views.add_client, name=\"addclient\"),\r\n path('dialog/', views.dialog, name=\"dialog\"),\r\n path('customers/', views.customers, name=\"customers\"),\r\n path('partners/', views.partners, name=\"partners\"),\r\n\r\n\r\n re_path(r'^status/(?P\\d+)/', views.status),\r\n re_path(r'^dialog/(?P\\d+)/', views.dialog),\r\n re_path(r'^choice/(?P\\d+)/', views.choice),\r\n re_path(r'^customer_contact_fact_academy/(?P\\d+)/', views.customer_contact_fact_academy),\r\n re_path(r'^customer_contract_fact/(?P\\d+)/', views.customer_contract_fact),\r\n\r\n re_path(r'^customer_payment_fact_when/(?P\\d+)/', views.customer_payment_fact_when),\r\n re_path(r'^customer_payment_fact_where/(?P\\d+)/', views.customer_payment_fact_where),\r\n re_path(r'^customer_payment_fact_how_much/(?P\\d+)/', views.customer_payment_fact_how_much),\r\n\r\n re_path(r'^customers/(?P\\d+)/', views.customers),\r\n re_path(r'^partners/(?P\\d+)/', views.partners),\r\nre_path(r'^partners_remove/(?P\\d+)/', views.partners_remove)\r\n\r\n\r\n\r\n\r\n\r\n\r\n]\r\n\r\n","repo_name":"tami-sub/ucvt","sub_path":"ucvt/project/urls.py","file_name":"urls.py","file_ext":"py","file_size_in_byte":1435,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"15"} +{"seq_id":"39236741013","text":"from tkinter import *\r\nfrom pytube import YouTube\r\nimport tkinter.filedialog as filedialog\r\n\r\n\r\na = Tk()\r\na.geometry(\"600x400\")\r\na.title(\"MP4 youtube downloader\")\r\na.resizable(False,False)\r\ns = Frame(a,width=600,height=400,bg=\"#1B90CA\")\r\ns.place(x=0,y=0)\r\n\r\nlink = StringVar()\r\n\r\ne = Entry(a,width=85,textvariable = link)\r\ne.place(x=80,y=255)\r\nLabel(text=\"MP4 youtube downloader\",font=(1),bg=\"#1B90CA\",fg=\"white\").place(x=5,y=5)\r\n\r\nLabel(s,text=\"ctrl + v = Paste\",font=2).place(x=1,y=130)\r\nLabel(s,text=\"ctrl + c = Copy \",font=2).place(x=1,y=160)\r\n\r\nLabel(s,text=\"if the download takes a lot of time, please check that the link is \\n correct \",font=2, bg=\"#1B90CA\", fg=\"white\").place(x=1,y=200)\r\ndef downloader():\r\n\r\n url=YouTube(str(link.get()))\r\n video=url.streams.get_highest_resolution()\r\n global asy1\r\n global asy2\r\n\r\n\r\n file_path = filedialog.asksaveasfilename(title='Save Video', defaultextension='.mp4')\r\n video.download(file_path)\r\n\r\nl = Label(s,text=\"URL =\",font=(1),bg=\"#1B90CA\",fg=\"white\")\r\nl.place(x=5,y=250)\r\nb = Button(s,text=\"Download\",width=50,height=2,font=(1),command=downloader,bg=\"#1F5D97\",fg=\"white\")\r\nb.place(x=20,y=300)\r\n\r\n\r\na.mainloop()\r\n","repo_name":"Mohd-khair-Alshrouf/oalo-python","sub_path":"youtube MP4 downloader.py","file_name":"youtube MP4 downloader.py","file_ext":"py","file_size_in_byte":1260,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"15"} +{"seq_id":"9654789303","text":"import os\nfrom os.path import join\nfrom collections import OrderedDict\n\nimport pandas as pd\nimport torch\nfrom torchvision import utils\nimport datetime\nimport logging\nimport numpy as np\nimport matplotlib.pyplot as plt\nimport matplotlib.cm as cm\nimport matplotlib as mpl\n#from tensorboardX import SummaryWriter\nfrom torch.utils.tensorboard import SummaryWriter\nfrom . import utils\nfrom .html_maker import df_html\n\n\nclass vis_writer:\n def __init__(self, opt):\n \"\"\"\n - checkpoint\n - exp_name\n - 000...00.pt\n - logs/\n - saved\n - imgs/\n - index.html\n \"\"\"\n\n exp_name = opt['exp_name']\n hyper_params = opt['hyper_params']\n\n cur_ofolder = join(hyper_params['default_folder'], exp_name)\n log_folder = join(cur_ofolder, 'logs', utils.get_cur_time_stamp())\n save_folder = join(cur_ofolder, 'saved')\n save_img_folder = join(save_folder, 'imgs')\n self.exp_name = exp_name\n\n os.makedirs(log_folder, exist_ok=True)\n os.makedirs(save_folder, exist_ok=True)\n os.makedirs(save_img_folder, exist_ok=True)\n\n self.writer = SummaryWriter(log_folder)\n self.save_folder = save_folder\n self.iter_counters = {}\n\n\n def plot_loss(self, loss:float, name:str):\n writer = self.writer\n iter = self.update_iter(name)\n\n writer.add_scalar('Loss/{}'.format(name), loss, iter)\n\n\n def plot_losses(self, all_loss: dict, name:str):\n writer = self.writer\n iter = self.update_iter(name)\n\n writer.add_scalars('Loss/{}'.format(name), all_loss, iter)\n\n\n def plot_img(self, img_np, name:str):\n writer = self.writer\n iter = self.update_iter(name)\n\n h, w, c = img_np.shape\n writer.add_image(name, img_np, iter, dataformats='HWC')\n\n\n def update_iter(self, name):\n if name not in self.iter_counters.keys():\n self.iter_counters[name] = 0\n else:\n self.iter_counters[name] += 1\n\n return self.iter_counters[name]\n\n\n def save_visualize(self, vis_images:OrderedDict, label:str):\n \"\"\" Save results to a html\n \"\"\"\n save_folder = self.save_folder\n csv = join(save_folder, 'meta.csv')\n img_ofolder = join(save_folder, 'imgs')\n html_file = join(save_folder, 'index.html')\n exp_name = self.exp_name\n\n new_data = {}\n for k, v in vis_images.items():\n key = '{}_{}'.format(label, k)\n opath = join(img_ofolder, key + '.png')\n new_data[k] = opath\n plt.imsave(opath, v)\n\n if os.path.exists(csv):\n df = pd.read_csv(csv)\n df = df.append(new_data, ignore_index=True)\n else:\n df = pd.DataFrame(data=[new_data])\n\n # make a html\n if os.path.exists(html_file):\n os.remove(html_file)\n\n df_html(df, save_folder, self.exp_name)\n df.to_csv(csv, index=False)\n","repo_name":"ShengCN/SSN_SoftShadowNet","sub_path":"Train/utils/vis_writer.py","file_name":"vis_writer.py","file_ext":"py","file_size_in_byte":3019,"program_lang":"python","lang":"en","doc_type":"code","stars":16,"dataset":"github-code","pt":"15"} +{"seq_id":"42732048810","text":"from django.conf import settings\nfrom rest_framework.routers import DefaultRouter, SimpleRouter\nfrom django.urls import include, path\n\nfrom talana_prueba.users.api.views import UserViewSet\nfrom talana_prueba.competition.views import CompetitionViewset\n\nfrom rest_framework_simplejwt.views import (\n TokenObtainPairView,\n TokenRefreshView,\n)\nif settings.DEBUG:\n router = DefaultRouter()\nelse:\n router = SimpleRouter()\n\nrouter.register(\"users\", UserViewSet)\nrouter.register(\"competition\" , CompetitionViewset , basename=\"competition\")\n\n\napp_name = \"api\"\nurlpatterns = router.urls\n\n\n\n\njwt = {\n path(\"auth-token\" , TokenObtainPairView.as_view() , name=\"auth\"), \n path(\"refresh-token\" ,TokenRefreshView.as_view() , name =\"refresh_token\" ),\n\n}\n\nurlpatterns += jwt","repo_name":"morwen1/talana_prueba","sub_path":"config/api_router.py","file_name":"api_router.py","file_ext":"py","file_size_in_byte":775,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"15"} +{"seq_id":"31376361854","text":"from email.mime import base\nfrom re import T\nimport re\nfrom googlesearch import search\nfrom urllib.error import HTTPError\nimport sys\nimport webbrowser\n\nbase_url = \"https://www.google.co.uk/search?q=\"\n\ndef parse(index):\n raw_query = sys.argv[index:]\n parsed_query = \"\"\n for word in raw_query:\n parsed_query += str(word) + \" \"\n return parsed_query\n\n\ndef launch():\n first_param = sys.argv[1]\n flag = \"\"\n if first_param == 's':\n parsed_query = parse(2)\n flag = \"site:stackoverflow.com\"\n elif first_param == 'r':\n parsed_query = parse(2)\n flag = \"site:reddit.com\"\n else:\n parsed_query = parse(1)\n\n launch_query = base_url + parsed_query + flag\n webbrowser.open_new_tab(launch_query)\n\n\nlaunch()","repo_name":"ermeyasgirma/search_command","sub_path":"search.py","file_name":"search.py","file_ext":"py","file_size_in_byte":763,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"15"} +{"seq_id":"29137969720","text":"#!/usr/bin/env python\n\nimport pika\nimport time\n\n\ndef publish(body):\n # send a task\n channel.basic_publish(exchange='',\n routing_key='queue-test',\n body=body,\n properties=pika.BasicProperties(\n delivery_mode=2 # make task persistent\n ))\n\n\n# Wait for rabbit to start\ntime.sleep(30)\nconnection = pika.BlockingConnection(\n pika.ConnectionParameters(host='rabbit'))\n\nchannel = connection.channel()\n\nchannel.queue_declare(queue='queue-test', durable=True)\n\nwhile True:\n message = time.time_ns() // 1000\n publish('message number {}'.format(message))\n print('published message {}'.format(message))\n time.sleep(15)\n","repo_name":"MarcoStaccato/rabbit-producer-consumer","sub_path":"producer/Producer.py","file_name":"Producer.py","file_ext":"py","file_size_in_byte":757,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"15"} +{"seq_id":"10751663800","text":"import re\n\nfrom pygments.lexer import RegexLexer, include, bygroups, using, DelegatingLexer\nfrom pygments.lexers import get_lexer_by_name\nfrom pygments.token import *\n\n\nclass DisassemblyLexer(RegexLexer):\n \"\"\"\n For Nasm (Intel) disassembly from LLDB.\n\n Based on the NasmLexer included with Pygments\n \"\"\"\n name = 'LLDB Intel syntax disassembly'\n aliases = ['lldb_intel']\n filenames = []\n mimetypes = []\n\n identifier = r'[]*'\n hexn = r'(?:0[xX][0-9a-f]+|$0[0-9a-f]*|[0-9]+[0-9a-f]*h)'\n octn = r'[0-7]+q'\n binn = r'[01]+b'\n decn = r'[0-9]+'\n floatn = decn + r'\\.e?' + decn\n string = r'\"(\\\\\"|[^\"\\n])*\"|' + r\"'(\\\\'|[^'\\n])*'|\" + r\"`(\\\\`|[^`\\n])*`\"\n declkw = r'(?:res|d)[bwdqt]|times'\n register = (r'r[0-9]+[bwd]{0,1}|'\n r'[a-d][lh]|[er]?[a-d]x|[er]?[sbi]p|[er]?[sd]i|[c-gs]s|st[0-7]|'\n r'mm[0-7]|cr[0-4]|dr[0-367]|tr[3-7]|.mm\\d+')\n wordop = r'seg|wrt|strict'\n type = r'byte|[dq]?word|ptr|xmmword|opaque'\n\n flags = re.IGNORECASE | re.MULTILINE\n tokens = {\n 'root': [\n (identifier + '`' + identifier, Name.Function),\n ('->', Generic.Prompt),\n include('whitespace'),\n (r'^\\s*%', Comment.Preproc, 'preproc'),\n (identifier + ':', Name.Label),\n (r'(%s)(\\s+)(equ)' % identifier,\n bygroups(Name.Constant, Keyword.Declaration, Keyword.Declaration),\n 'instruction-args'),\n (declkw, Keyword.Declaration, 'instruction-args'),\n (identifier, Keyword.Declaration, 'instruction-args'),\n (r' *' + hexn, Name.Label),\n (r'[:]', Text),\n (r'^->', Error),\n (r'[\\r\\n]+', Text)\n ],\n 'instruction-args': [\n (register, Name.Builtin),\n (string, String),\n (hexn, Number.Hex),\n (octn, Number.Oct),\n (binn, Number.Bin),\n (floatn, Number.Float),\n (decn, Number.Integer),\n include('punctuation'),\n (identifier, Name.Variable),\n (r'[\\r\\n]+', Text, '#pop'),\n include('whitespace')\n ],\n 'preproc': [\n (r'[^;\\n]+', Comment.Preproc),\n (r';.*?\\n', Comment.Single, '#pop'),\n (r'\\n', Comment.Preproc, '#pop'),\n ],\n 'whitespace': [\n (r'\\n', Text),\n (r'[ \\t]+', Text),\n (r';.*', Comment.Single),\n (r'#.*', Comment.Single)\n ],\n 'punctuation': [\n (r'[,():\\[\\]]+', Punctuation),\n (r'[&|^<>+*/%~-]+', Operator),\n (r'[$]+', Keyword.Constant),\n (wordop, Operator.Word),\n (type, Keyword.Type)\n ],\n }\n\n\nclass LLDBIntelLexer(DisassemblyLexer):\n name = 'LLDB Intel syntax disassembly'\n aliases = ['lldb_intel']\n\n\nclass LLDBATTLexer(DisassemblyLexer):\n name = 'LLDB AT&T syntax disassembly'\n aliases = ['lldb_att']\n\n\nclass GDBATTLexer(DisassemblyLexer):\n name = 'GDB AT&T syntax disassembly'\n aliases = ['gdb_att']\n\n\nclass GDBIntelLexer(DisassemblyLexer):\n name = 'GDB Intel syntax disassembly'\n aliases = ['gdb_intel']\n\n\nclass VDBATTLexer(DisassemblyLexer):\n name = 'VDB AT&T syntax disassembly'\n aliases = ['vdb_att']\n\n\nclass CapstoneIntelLexer(DisassemblyLexer):\n name = 'Capstone Intel syntax disassembly'\n aliases = ['capstone_intel']\n\n\nclass VDBIntelLexer(RegexLexer):\n \"\"\"\n For Nasm (Intel) disassembly from VDB.\n\n Based on the LLDBIntelLexer above.\n major difference is the raw instruction hex after the instruction address.\n\n example:\n rip 0x000000000056eb4f: 4885ff test rdi,rdi ;0x7f4f8740ca50,0x7f4f8740ca50\n 0x000000000056eb52: 740f jz 0x0056eb63\n \"\"\"\n name = 'VDB Intel syntax disassembly'\n aliases = ['vdb_intel']\n filenames = []\n mimetypes = []\n\n space = r'[ \\t]+'\n identifier = r'[]*'\n hexn = r'(?:0[xX][0-9a-f]+|$0[0-9a-f]*|[0-9]+[0-9a-f]*h)' # hex number\n hexr = r'(?:[0-9a-f]+)' # hex raw (no leader/trailer)\n octn = r'[0-7]+q'\n binn = r'[01]+b'\n decn = r'[0-9]+'\n floatn = decn + r'\\.e?' + decn\n string = r'\"(\\\\\"|[^\"\\n])*\"|' + r\"'(\\\\'|[^'\\n])*'|\" + r\"`(\\\\`|[^`\\n])*`\"\n register = (r'r[0-9]+[bwd]{0,1}|'\n r'[a-d][lh]|[er]?[a-d]x|[er]?[sbi]p|[er]?[sd]i|[c-gs]s|st[0-7]|'\n r'mm[0-7]|cr[0-4]|dr[0-367]|tr[3-7]|.mm\\d*')\n wordop = r'seg|wrt|strict'\n type = r'byte|[dq]?word|ptr'\n\n flags = re.IGNORECASE | re.MULTILINE\n tokens = {\n 'root': [\n (r'^(%s)(%s)(%s)(: )(%s)(%s)' % (register, space, hexn, hexr, space),\n bygroups(Name.Builtin, Text, Name.Label, Text, Number.Hex, Text),\n \"instruction\"),\n (r'^(%s)(%s)(: )(%s)(%s)' % (space, hexn, hexr, space),\n bygroups(Text, Name.Label, Text, Number.Hex, Text),\n \"instruction\")\n ],\n 'instruction': [\n (space, Text),\n (r\"(rep[a-z]*)( )\", bygroups(Name.Function, Text)),\n (r\"(%s)\" % identifier, Name.Function, (\"#pop\", \"instruction-args\")),\n ],\n 'instruction-args': [\n (space, Text),\n (string, String),\n (hexn, Number.Hex),\n (octn, Number.Oct),\n (binn, Number.Bin),\n (floatn, Number.Float),\n (decn, Number.Integer),\n include('punctuation'),\n (register, Name.Builtin),\n (identifier, Name.Variable),\n (r'[\\r\\n]+', Text, '#pop'),\n (r';', Text, (\"#pop\", 'comment')),\n ],\n 'comment': [\n (space, Text),\n (string, Comment.Single),\n (hexn, Number.Hex),\n (octn, Number.Oct),\n (binn, Number.Bin),\n (floatn, Number.Float),\n (decn, Number.Integer),\n include('punctuation'),\n (register, Name.Builtin),\n (identifier, Name.Variable),\n (r'[\\r\\n]+', Text, '#pop'),\n ],\n 'punctuation': [\n (r'[,():\\[\\]]+', Punctuation),\n (r'[&|^<>+*/%~-]+', Operator),\n (r'[$]+', Keyword.Constant),\n (wordop, Operator.Word),\n (type, Keyword.Type)\n ],\n }\n\n\nclass WinDbgIntelLexer(RegexLexer):\n name = 'WinDbg Intel syntax disassembly'\n aliases = ['windbg_intel']\n filenames = []\n mimetypes = []\n\n identifier = r'[]*'\n hexn = r'(0[xX])?([0-9a-f]+|$0[0-9a-f`]*|[0-9]+[0-9a-f]*h)'\n addr = r'(0[xX])?([0-9a-f`]+|$0[0-9a-f`]*|[0-9]+[0-9a-f`]*h)'\n octn = r'[0-7]+q'\n binn = r'[01]+b'\n decn = r'[0-9]+'\n floatn = decn + r'\\.e?' + decn\n string = r'\"(\\\\\"|[^\"\\n])*\"|' + r\"'(\\\\'|[^'\\n])*'|\" + r\"`(\\\\`|[^`\\n])*`\"\n declkw = r'(?:res|d)[bwdqt]|times'\n register = (r'r[0-9]+?[bwd]{0,1}|'\n r'[a-d][lh]|[er]?[a-d]x|[er]?[sbi]p|[er]?[sd]i|[c-gs]s|st[0-7]|'\n r'mm[0-7]|cr[0-4]|dr[0-367]|tr[3-7]|.mm\\d*')\n wordop = r'seg|wrt|strict'\n type = r'byte|[dq]?word|ptr'\n func = r'[a-zA-Z]*\\!?'\n\n flags = re.IGNORECASE | re.MULTILINE\n tokens = {\n 'root': [\n (addr, Number.Hex, 'instruction-line'),\n include('whitespace'),\n (identifier, Name.Class, 'label'),\n (r'[:]', Text),\n (r'[\\r\\n]+', Text)\n ],\n 'instruction-line': [\n (r' ', Text),\n (hexn, Text, 'instruction'),\n ],\n 'instruction': [\n include('whitespace'),\n (r'(%s)(\\s+)(equ)' % identifier,\n bygroups(Name.Constant, Keyword.Declaration, Keyword.Declaration),\n 'instruction-args'),\n (declkw, Keyword.Declaration, 'instruction-args'),\n (identifier, Name.Function, 'instruction-args'),\n ],\n 'label': [\n (r'[!+]', Operator),\n (identifier, Name.Function),\n (hexn, Number.Hex),\n (r'[:]', Text, '#pop'),\n\n ],\n 'instruction-args': [\n (string, String),\n include('punctuation'),\n (register, Name.Builtin),\n include('label'),\n (identifier, Name.Variable),\n (r'[\\r\\n]+', Text, '#pop:3'),\n include('whitespace'),\n (hexn, Number.Hex),\n (addr, Number.Hex),\n (octn, Number.Oct),\n (binn, Number.Bin),\n (floatn, Number.Float),\n (decn, Number.Integer),\n ],\n 'preproc': [\n (r'[^;\\n]+', Comment.Preproc),\n (r';.*?\\n', Comment.Single, '#pop'),\n (r'\\n', Comment.Preproc, '#pop'),\n ],\n 'whitespace': [\n (r'\\n', Text),\n (r'[ \\t]+', Text),\n (r';.*', Comment.Single),\n (r'#.*', Comment.Single)\n ],\n 'punctuation': [\n (r'[,():\\[\\]]+', Punctuation),\n (r'[&|^<>+*/%~-]+', Operator),\n (r'[$]+', Keyword.Constant),\n (wordop, Operator.Word),\n (type, Keyword.Type)\n ],\n }\n\n\nclass WinDbgATTLexer(WinDbgIntelLexer):\n name = 'WinDbg ATT syntax disassembly'\n aliases = ['windbg_att']\n","repo_name":"snare/voltron","sub_path":"voltron/lexers.py","file_name":"lexers.py","file_ext":"py","file_size_in_byte":9227,"program_lang":"python","lang":"en","doc_type":"code","stars":6032,"dataset":"github-code","pt":"15"} +{"seq_id":"69872562892","text":"import serial\nimport serial.tools.list_ports\nimport time\nimport state_store\nfrom scan_helm import ScanHelm\nimport utils_waktu\nimport backend\n\nclass ScanRFID:\n def scan(self):\n ports = serial.tools.list_ports.comports()\n portList = []\n state_store.global_serial_init = serial.Serial()\n print(\"Port yang sedang terhubung sekarang: \")\n index_port = 0\n for port in ports:\n portList.append(port)\n print(\"(\" + str(index_port) + \"). \" + str(port))\n index_port += 1\n\n # Cara 1 inputan manual.\n # inputan_user = input(\"Pilih Port yang ingin disambungkan: COM\")\n # for i in range(0, len(portList)):\n # if str(portList[i]).startswith(\"COM\" + str(inputan_user)):\n # port_pilihan = \"COM\" + inputan_user\n #\n # serialInst.baudrate = 9600\n # serialInst.port = port_pilihan\n # serialInst.close()\n # serialInst.open()\n #################################################################\n\n # Cara 2 inputan brute\n brute_choose = 1\n for i in range(10):\n try:\n port_pilihan = \"\"\n for i in range(0, len(portList)):\n if str(portList[i]).startswith(\"COM\" + str(brute_choose)):\n port_pilihan = \"COM\" + str(brute_choose)\n\n state_store.global_serial_init.baudrate = 9600\n state_store.global_serial_init.port = port_pilihan\n state_store.global_serial_init.close()\n state_store.global_serial_init.open()\n print(f\"COM{brute_choose} bisa dikoneksikan..\")\n time.sleep(1)\n print(f\"Memulai scan RFID...\")\n time.sleep(2)\n break\n except serial.SerialException as err:\n print(f\"COM{brute_choose} tidak bisa dikoneksikan {str(err)}. mencoba port selanjutnya\")\n time.sleep(1)\n brute_choose += 1\n\n # serial LED test\n # serialInst.write(b'1')\n state_store.global_serial_init.write(b'3')\n # serialInst.write(b'5')\n\n toggle = True\n while toggle:\n rfid_number = \"\"\n if state_store.global_serial_init.in_waiting:\n rfid_number = str(state_store.global_serial_init.readline().decode('utf').rstrip('\\n'))\n print(str(rfid_number))\n if len(rfid_number) > 3:\n\n # check kehadiran\n uw = utils_waktu.UtilsWaktu()\n uw.getSeninSabtu()\n\n print(\"rfid terdeteksi.\")\n state_store.global_rfid_number = rfid_number\n # time.sleep(0.1)\n # state_store.global_serial_init.write(b'8')\n break\n else:\n print(\"rfid tidak terdeteksi\")\n\n time.sleep(0.25)\n\n print(\"Mempersiapkan untuk mendeteksi helm.\")\n # start deteksi helmnya\n scan_helm_object = ScanHelm()\n scan_helm_object.scan()\n\n\n\n","repo_name":"YudhaDev/yolo8-detection-helmet","sub_path":"scan_rfid.py","file_name":"scan_rfid.py","file_ext":"py","file_size_in_byte":3061,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"15"} +{"seq_id":"34763924682","text":"#!/usr/env/python3\n# -*- coding: UTF-8 -*-\n\nimport logging\nfrom ..bupt_messager.bot_handler.bot_handler import BotHandler\nfrom ..bupt_messager.queued_bot import create_queued_bot\nfrom ..bupt_messager.sql_handler import SQLManager\nfrom ..bupt_messager.mess import get_current_time, set_logger\n\n\ndef bot_handler_test():\n set_logger(\n f'log/test/bot_helper_test_{get_current_time()}.txt',\n console_level=logging.DEBUG,\n file_level=logging.DEBUG)\n queued_bot = create_queued_bot()\n sql_manager = SQLManager()\n bot_handler = BotHandler(sql_manager=sql_manager, bot=queued_bot)\n bot_handler.add_handler()\n bot_handler.start()\n return bot_handler\n\n\nif __name__ == '__main__':\n bot_handler_test()\n","repo_name":"Berailitz/bupt-messager","sub_path":"test/bot_handler_test.py","file_name":"bot_handler_test.py","file_ext":"py","file_size_in_byte":734,"program_lang":"python","lang":"en","doc_type":"code","stars":2,"dataset":"github-code","pt":"15"} +{"seq_id":"22111689819","text":"from torch import nn\nfrom torch.optim import Adam, SGD, AdamW\nfrom rt_torch.utilizes.optimizer_param_scheduler import OptimizerParamScheduler\nfrom torch.optim.lr_scheduler import CosineAnnealingLR\n\n\ndef get_optimizer_param_scheduler(args, optimizer):\n \"\"\"Build the learning rate scheduler.\"\"\"\n\n # # Iteration-based training.\n # if args.lr_decay_iters is None:\n # args.lr_decay_iters = args.train_iters\n # lr_decay_steps = args.lr_decay_iters * args.global_batch_size\n # wd_incr_steps = args.train_iters * args.global_batch_size\n # # if args.lr_warmup_fraction is not None:\n # # lr_warmup_steps = args.lr_warmup_fraction * lr_decay_steps\n # # else:\n # # lr_warmup_steps = args.lr_warmup_iters * args.global_batch_size\n\n # opt_param_scheduler = OptimizerParamScheduler(\n # optimizer,\n # max_lr=args.lr,\n # min_lr=args.min_lr,\n # lr_warmup_steps=0,\n # lr_decay_steps=lr_decay_steps,\n # lr_decay_style=args.lr_decay_style,\n # start_wd=args.start_weight_decay,\n # end_wd=args.end_weight_decay,\n # wd_incr_steps=wd_incr_steps,\n # wd_incr_style=args.weight_decay_incr_style,\n # use_checkpoint_opt_param_scheduler=args.use_checkpoint_opt_param_scheduler,\n # override_opt_param_scheduler=args.override_opt_param_scheduler,\n # )\n if args.lr_decay_style == \"cosine\":\n opt_param_scheduler = CosineAnnealingLR(optimizer, T_max=args.train_iters, eta_min=args.min_lr)\n else:\n raise NotImplementedError\n return opt_param_scheduler\n\n\ndef get_paramaters(args, model: nn.Module):\n lr_t = args.lr_t\n lr_eff = args.lr_eff\n if lr_t == lr_eff:\n return model.parameters()\n pretrained = set()\n unpretrained = set()\n for module_name, module in model.named_modules():\n for parameter_name, paramater in module.named_parameters():\n full_parameter_name = \"%s.%s\" % (module_name, parameter_name) if module_name else parameter_name # full param name\n if full_parameter_name.endswith(\"bias\") or full_parameter_name.endswith(\"weight\"):\n if \"film_efficient_net\" in full_parameter_name:\n if \"conditioning_layers\" in full_parameter_name:\n unpretrained.add(full_parameter_name)\n else:\n pretrained.add(full_parameter_name)\n else:\n unpretrained.add(full_parameter_name)\n else:\n import pdb; pdb.set_trace()\n param_dict = {parameter_name: paramater for parameter_name, paramater in model.named_parameters()}\n pretrained = param_dict.keys() & pretrained\n unpretrained = param_dict.keys() & unpretrained\n inter_params = pretrained & unpretrained\n union_params = pretrained | unpretrained\n assert (\n len(inter_params) == 0\n ), \"parameters %s made it into both pretrained/unpretrained sets!\" % (str(inter_params),)\n assert len(param_dict.keys() ^ union_params) == 0, (\n \"parameters %s were not separated into either pretrained/unpretrained set!\"\n % (str(param_dict.keys() - union_params),)\n )\n optim_groups = [\n {\n \"params\": [\n param_dict[pn] for pn in sorted(list(pretrained)) if pn in param_dict\n ],\n \"lr\": lr_eff,\n },\n {\"params\": [param_dict[pn] for pn in sorted(list(unpretrained))], \"lr\": lr_t,},\n ]\n return optim_groups\n \n\ndef get_optimizer(args, model):\n # Base optimizer.\n paramaters = get_paramaters(args, model)\n if args.optimizer == \"adam\":\n optimizer = Adam(\n paramaters,\n lr=args.lr,\n weight_decay=args.weight_decay,\n betas=(args.adam_beta1, args.adam_beta2),\n eps=args.adam_eps,\n )\n elif args.optimizer == \"adamw\":\n optimizer = AdamW(\n paramaters,\n lr=args.lr,\n betas=(args.adam_beta1, args.adam_beta2),\n eps=args.adam_eps,\n )\n elif args.optimizer == \"sgd\":\n optimizer = SGD(\n paramaters,\n lr=args.lr,\n weight_decay=args.weight_decay,\n momentum=args.sgd_momentum,\n )\n else:\n raise Exception(\"{} optimizer is not supported.\".format(args.optimizer))\n\n return optimizer","repo_name":"CZtheHusky/rt_torch","sub_path":"rt_torch/utilizes/train_configs.py","file_name":"train_configs.py","file_ext":"py","file_size_in_byte":4349,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"15"} +{"seq_id":"18347992360","text":"import gzip\nimport io\nimport sys\nimport time\nfrom urllib import request\n\n\ndef reporthook(count, block_size, total_size):\n global start_time\n if count == 0:\n start_time = time.time()\n return\n duration = time.time() - start_time\n progress_size = int(count * block_size)\n speed = int(progress_size / (1024 * duration))\n percent = int(count * block_size * 100 / total_size)\n sys.stdout.write(\"\\r...%d%%, %d MB, %d KB/s, %d seconds passed\" %\n (percent, progress_size / (1024 * 1024), speed, duration))\n sys.stdout.flush()\n\n\n# Grab corpus.\nurl = 'http://www.openslr.org/resources/11/librispeech-lm-norm.txt.gz'\ndata_upper = '/tmp/upper.txt.gz'\nrequest.urlretrieve(url, data_upper, reporthook)\nprint('Finished downloading, starting cleanup \\n')\n\n# Convert to lowercase and cleanup.\ndata_lower = '/tmp/lower.txt'\nwith open(data_lower, 'w', encoding='utf-8') as lower:\n with io.TextIOWrapper(io.BufferedReader(gzip.open(data_upper)), encoding='utf8') as upper:\n for line in upper:\n lower.write(line.lower())\n\nprint('Finished converting case, saved to /tmp/ folder \\n')","repo_name":"nginyc/rafiki","sub_path":"examples/datasets/speech_recognition/load_lm_txt.py","file_name":"load_lm_txt.py","file_ext":"py","file_size_in_byte":1137,"program_lang":"python","lang":"en","doc_type":"code","stars":34,"dataset":"github-code","pt":"15"} +{"seq_id":"33169897834","text":"import matplotlib.pyplot as plt\r\nimport numpy as np\r\n\r\ndef plot_misclassified_images(img_data, classes, img_name):\r\n figure = plt.figure(figsize=(10, 10))\r\n \r\n num_of_images = len(img_data)\r\n for index in range(1, num_of_images + 1):\r\n img = img_data[index-1][\"img\"] / 2 + 0.5 # unnormalize\r\n plt.subplot(5, 5, index)\r\n plt.axis('off')\r\n plt.imshow(np.transpose(img, (1, 2, 0)))\r\n plt.title(\"Predicted: %s\\nActual: %s\" % (classes[img_data[index-1][\"pred\"]], classes[img_data[index-1][\"target\"]]))\r\n \r\n plt.tight_layout()\r\n plt.savefig(img_name)\r\n\r\ndef plot_graph(data, metric):\r\n fig = plt.figure(figsize=(7, 7))\r\n \r\n plt.title(f'Graph of %s' % (metric))\r\n plt.xlabel('Epoch')\r\n plt.ylabel(metric)\r\n plt.plot(data)\r\n plt.show()\r\n \r\n fig.savefig(f'val_%s_change.png' % (metric.lower()))\r\n\r\ndef plot_acc_loss_graph(train_acc,test_accs):\r\n plt.figure(figsize=(15, 10))\r\n ax = plt.subplot(111)\r\n ax.plot(train_acc)\r\n ax.plot(test_accs)\r\n ax.set(title=\"Accuracy curves\", xlabel=\"Epoch\", ylabel=\"Accuracy\")\r\n ax.legend(['Training Accuracy', 'Testing Accuracy'], loc='best')\r\n plt.savefig(\"TrainTestAccuracy.png\")\r\n plt.show()","repo_name":"EVA4Phase2Work/MobileNetAssignment","sub_path":"utils/graphplot.py","file_name":"graphplot.py","file_ext":"py","file_size_in_byte":1207,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"15"} +{"seq_id":"24105170810","text":"def time(x, y):\r\n return y[0] * 60 + y[1] - x[0] * 60 - x[1]\r\n\r\ndef process():\r\n dic = {}\r\n n = int(input())\r\n for i in range(n) :\r\n name = input()\r\n x = [int(i) for i in input().split(':')]\r\n y = [int(i) for i in input().split(':')]\r\n mua = int(input())\r\n if name not in dic:\r\n dic[name] = (time(x, y), mua)\r\n else:\r\n dic[name] = (dic[name][0] + time(x, y), dic[name][1] + mua)\r\n cnt = 1\r\n for i in dic:\r\n print('T{:02d}'.format(cnt), i, \"{:.2f}\".format(dic[i][1] * 60 / dic[i][0]))\r\n cnt += 1\r\n\r\ndef main():\r\n\tt = 1\r\n\twhile t > 0:\r\n\t\tprocess()\r\n\t\tt -= 1\r\n \r\nif __name__ == '__main__':\r\n main()","repo_name":"springroll35/Python_PTIT","sub_path":"PY04013 - TINH TOAN LUONG MUA.py","file_name":"PY04013 - TINH TOAN LUONG MUA.py","file_ext":"py","file_size_in_byte":701,"program_lang":"python","lang":"en","doc_type":"code","stars":2,"dataset":"github-code","pt":"15"} +{"seq_id":"24383766133","text":"from functools import reduce\nfrom typing import Tuple\n\nimport tensorflow as tf\nimport numpy\n\nfrom layers.available_layers import Layer\nfrom layers.ilayer import ILayer\n\n\nclass Convolution(ILayer):\n def __init__(self, in_shape: Tuple, out_shape: Tuple, filter_len: int):\n super().__init__(in_shape, out_shape)\n if len(in_shape) != len(out_shape):\n raise Exception(\"Convolution::init - input shape and output shape doesn't match!\")\n self.output = None\n self.in_shape = in_shape\n self.out_shape = out_shape\n self.weights = self.init_weights(in_shape, out_shape, filter_len)\n self.type = Layer.convolution\n self.weight_length = len(self.decomposed_weights())\n\n def forward_pass(self, input: numpy.ndarray) -> numpy.ndarray:\n input_shape = numpy.shape(input)\n input = input[None][:, :, None]\n if len(input_shape) == 2:\n self.output = tf.nn.conv2d(\n input, self.weights, strides=5, padding='SAME', data_format='NHWC', dilations=None, name=None\n )\n elif len(input_shape) == 3:\n self.output = tf.nn.conv2d(\n input, self.weights, strides=5, padding='SAME', data_format='NHWC', dilations=None, name=None\n )\n elif len(input_shape) == 4:\n self.output = tf.nn.conv3d(\n input, self.weights, strides=[1, 5, 5, 5, 1], padding='SAME', data_format='NDHWC', dilations=None,\n name=None\n )\n else:\n raise Exception(\"Invalid input shape in convolution layer. Input: \" + str(len(input_shape)) +\n \". Weights: \" + str(len(self.weights)))\n\n self.output = tf.reshape(self.output, self.out_shape)\n return self.output\n\n def get_all_weights(self) -> numpy.ndarray:\n return self.weights\n\n def set_all_weights(self, new_weights):\n if numpy.shape(new_weights) == self.out_shape:\n self.weights = new_weights\n elif len(numpy.shape(new_weights)) == 1:\n self.weights = self.rebuild_weights(new_weights)\n else:\n raise Exception(\"Invalid new_weights shape in convolution layer: \" + str(numpy.shape(new_weights)) +\n \" expected: \" + str(self.out_shape))\n\n def decomposed_weights(self) -> numpy.ndarray:\n shape = numpy.shape(self.weights)\n flat_length = reduce(lambda x, y: x * y, shape)\n return tf.reshape(self.weights, flat_length)\n\n def rebuild_weights(self, flat_weights) -> numpy.ndarray:\n return tf.reshape(flat_weights, self.weights)\n\n def init_weights(self, in_shape: Tuple, out_shape: Tuple, filter_len: int) -> numpy.ndarray:\n if len(out_shape) == 2: # 1-D input plus kernels\n # [filter_height, filter_width, in_channels, out_channels]\n return numpy.random.normal(loc=0, scale=0.25, size=(1, filter_len, in_shape[1], out_shape[1]))\n elif len(out_shape) == 3: # 2-D input plus kernels\n # [filter_height, filter_width, in_channels, out_channels]\n return numpy.random.normal(loc=0, scale=0.25, size=(filter_len, filter_len, in_shape[2], out_shape[2]))\n elif len(out_shape) == 4: # 3-D input plus kernels\n # [filter_height, filter_width, filter_depth, in_channels, out_channels]\n return numpy.random.normal(loc=0, scale=0.25, size=(filter_len, filter_len, filter_len, in_shape[3],\n out_shape[3]))\n else:\n raise Exception(\"Invalid input shape in convolution layer::init_weights. Dimensions: \" +\n str(len(in_shape)) + \". Expected: 2 to 5.\")\n","repo_name":"marcindahlen/EEG-with-CNN-and-GA","sub_path":"layers/layer_convolution.py","file_name":"layer_convolution.py","file_ext":"py","file_size_in_byte":3724,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"15"} +{"seq_id":"4393961685","text":"import os\nimport sys\nif __name__ == '__main__':\n if 'PIPENV_ACTIVE' not in os.environ:\n sys.exit(f'This script should be run in a Pipenv.\\n\\nRun it as:\\npipenv run python {os.path.basename(__file__)}')\n\nfrom pathlib import Path\nimport shutil\nimport subprocess\n\ndef run():\n SCRIPT_PATH = Path(__file__).absolute().parent\n REPO_ROOT = SCRIPT_PATH.parent\n\n proto_path = REPO_ROOT / 'proto'\n\n nanopb_path = REPO_ROOT / 'thirdparty' / 'nanopb'\n\n # Make sure nanopb submodule is available\n if not os.path.isdir(nanopb_path):\n print(f'Nanopb checkout not found! Make sure you have inited/updated the submodule located at {nanopb_path}', file=sys.stderr)\n exit(1)\n\n nanopb_generator_path = nanopb_path / 'generator' / 'nanopb_generator.py'\n c_generated_output_path = REPO_ROOT / 'firmware' / 'src' / 'proto_gen'\n\n proto_files = [f for f in os.listdir(proto_path) if f.endswith('.proto')]\n assert len(proto_files) > 0, 'No proto files found!'\n\n # Generate C files via nanopb\n subprocess.check_call(['python3', nanopb_generator_path, '-D', c_generated_output_path] + proto_files, cwd=proto_path)\n\n\n # Use nanopb's packaged protoc to generate python bindings\n protoc_path = nanopb_path / 'generator' / 'protoc'\n python_generated_output_path = REPO_ROOT / 'software' / 'python' / 'proto_gen'\n python_generated_output_path.mkdir(parents=True, exist_ok=True)\n subprocess.check_call([protoc_path, '--version'])\n subprocess.check_call([\n protoc_path,\n '--python_out',\n python_generated_output_path,\n ] + proto_files, cwd=proto_path)\n\n # Copy nanopb's compiled options proto\n shutil.copy2(nanopb_path / 'generator' / 'proto' / 'nanopb_pb2.py', python_generated_output_path)\n\n\nif __name__ == '__main__':\n run()\n","repo_name":"scottbez1/smartknob","sub_path":"proto/generate_protobuf.py","file_name":"generate_protobuf.py","file_ext":"py","file_size_in_byte":1804,"program_lang":"python","lang":"en","doc_type":"code","stars":16346,"dataset":"github-code","pt":"15"} +{"seq_id":"41882775559","text":"import wpilib\nimport ctre\n\n\nclass ColorSensor:\n def __init__(self):\n self.sensor = None\n def setSensor(self, sensor):\n self.sensor = sensor\n def getColor(self):\n assert self.sensor != None\n c = self.sensor.getColor()\n #return str(str(c.red) + \",\" + str(c.green) + \",\" + str(c.blue))\n out = \"\"\n maptable = {\"red\" : [0.564, 0.321, 0.115], \"green\" : [0.150, 0.600, 0.248], \"blue\" : [0.110, 0.422, 0.469], \"yellow\" : [0.324, 0.568, 0.108]}\n costs = dict()\n for name in maptable:\n test = maptable[name]\n cost = 0\n cost += (c.red - test[0])**2\n cost += (c.green - test[1])**2\n cost += (c.blue - test[2])**2\n costs[name] = cost\n min_cost = min(costs.values())\n results = [a for a in costs if costs[a] == min_cost]\n return results[0]\n","repo_name":"RavenRoboticsTeam1288/Robot-Code-2020","sub_path":"colorSensor.py","file_name":"colorSensor.py","file_ext":"py","file_size_in_byte":969,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"15"} +{"seq_id":"32508999900","text":"import numpy as np\nimport glob\nimport tifffile as tiff\nimport pandas as pd\nfrom skimage.filters import gaussian, difference_of_gaussians, median\nfrom skimage import exposure\nfrom skimage.restoration import rolling_ball\nimport skimage.morphology as morph\nimport scipy.signal as signal\nimport matplotlib.cm as cm\nimport matplotlib.colors as col\nimport scipy.spatial as spatial\n\n\ndef read_images(path):\n \n full_paths = np.sort(glob.glob(path))\n \n filenames = []\n images = []\n voxel_dims = []\n for a_path in full_paths:\n filenames.append(a_path.split(\"/\")[-1])\n images.append(tiff.imread(a_path))\n if a_path[-4:] == '.lsm':\n voxel_size= np.array([tiff.TiffFile(a_path).pages[0].tags['CZ_LSMINFO'].value['VoxelSizeZ'], tiff.TiffFile(full_paths[0]).pages[0].tags['CZ_LSMINFO'].value['VoxelSizeX'], tiff.TiffFile(full_paths[0]).pages[0].tags['CZ_LSMINFO'].value['VoxelSizeY']])\n voxel_size = voxel_size * 1000000\n voxel_dims.append(voxel_size)\n else:\n voxel_dims.append((1,1,1))\n \n voxel_dims = np.array(voxel_dims)\n \n return filenames, images, voxel_dims\n\n#doesnt work for csvs use only for numpy files\ndef load_files(path, pandas = False):\n files = np.sort(glob.glob(path))\n all_data = []\n for file in files:\n if pandas == False:\n if file[-3:] == 'npy':\n data = np.load(file,allow_pickle='TRUE')\n all_data.append(data)\n elif file[-3:] == 'csv':\n data = np.loadtxt(file,delimiter = ',',skiprows = 1)\n all_data.append(data)\n else:\n print('incorrect format')\n elif pandas == True:\n if file[-3:] == 'csv':\n data = pd.read_csv(file)\n else:\n print('incorrect format for pandas loading')\n else:\n print('incorrect format')\n \n return all_data\n\n\ndef split_channels(images, channel_axis = 1):\n '''splits channels into lists and then assigns them to values in a dictionary. Can split any number of channels. '''\n \n channel_split = {}\n for i in range(len(images)):\n channels = np.split(images[i], images[i].shape[channel_axis],axis = channel_axis)\n if i == 0:\n for j in range(len(channels)):\n print(f'image {i} has {j} channels')\n channel_split[f'ch{j}'] = [channels[j]]\n else:\n for j in range(len(channels)):\n print(f'image {i} has {j} channels')\n channel_split[f'ch{j}'].append(channels[j])\n \n return channel_split\n\ndef merge_channels(channel0, channel1, channel2):\n \n images = []\n \n for i in range(len(channel0)):\n image = np.concatenate((channel0[i],channel1[i],channel2[i]), axis = 1)\n images.append(image)\n \n return images\n\ndef clahe(images, kernel_clahe = (50,50,10), clahe_limit = 0.05):\n \n assert type(images) == list, 'Input images must be in a list'\n \n images_clahe = []\n \n for image in images:\n if len(image.shape) == 3:\n image = image.transpose()\n image_clahe = exposure.equalize_adapthist(image,kernel_size = kernel_clahe, clip_limit = clahe_limit)\n image_clahe = image_clahe.transpose()\n images_clahe.append(image_clahe)\n else: \n channel_number = image.shape[1] #assuming that channel number is the second dimension of the np array\n channels_array = np.empty(image.shape)\n for channel in range(channel_number):\n single_channel = image[:,channel,...].transpose()\n single_channel_clahe = exposure.equalize_adapthist(single_channel,kernel_size = kernel_clahe, clip_limit = clahe_limit)\n single_channel_clahe = single_channel_clahe.transpose()\n channels_array[:,channel,...] = single_channel_clahe\n images_clahe.append(channels_array)\n \n return images_clahe\n\ndef batch_gaussian(images, sigma = 1, diff_gauss = False, high_sigma = 3, channel_axis = 1, preserve_range = True):\n \n \n images_gauss = []\n \n for i in range(len(images)):\n img = images[i]\n \n if diff_gauss == False:\n img_gauss = gaussian(img, sigma, channel_axis = channel_axis, preserve_range = preserve_range)\n elif diff_gauss == True:\n img_gauss = difference_of_gaussians(img, low_sigma = sigma, high_sigma = high_sigma, channel_axis = channel_axis)\n \n images_gauss.append(img_gauss.reshape((img_gauss.shape[0],)+img_gauss.shape[2:]))\n \n \n return images_gauss\n\ndef supress_background(image):\n # create structuring element that is the size of a true HCR nuclear spot (5,5,3 pixels)\n disk = morph.disk(2)\n disk = np.stack((disk,disk,disk),axis=0)\n # use element to remove salt and pepper noise below this size/shape, 2x median filter enhances difference between background and signal\n img_med = median(image,footprint= disk)\n img_med = median(img_med,footprint= disk)\n # remove further background using rolling ball subtraction with same element\n bk_roll = rolling_ball(img_med,kernel=disk)\n img_roll = img_med - bk_roll\n \n return img_roll\n\ndef qqplot(array1, array2):\n \n q1 = np.percentile(array1,range(100))\n q2 = np.percentile(array2,range(100))\n \n plt.plot(q1,q1)\n plt.scatter(q1,q2)\n plt.show()\n \n return plt\n\ndef plotting_grid_index(cols,rows):\n total_plots = cols+ rows\n row_index = []\n col_index = []\n for i in range(len(total_plots)):\n row_index.append(i//cols)\n col_index.append(i%cols)\n \n return row_index,col_index\n\ndef optimal_nn_radius(data,voxel_dims):\n \n #kd tree with a radius of 35 gives most common nn num to be 14 which is the number of nearest neighbours in a cube\n kd_tree = spatial.KDTree(data.loc[:,['z','y','x']][~np.isnan(data.loc[:,['z','y','x']])]*voxel_dims)\n \n mean_nn = 0\n radius = 0\n while mean_nn < 14:\n radius += 1\n nn_index = kd_tree.query_ball_tree(kd_tree,r=radius)\n mean_nn = np.mean([len(pt_nn) for pt_nn in nn_index])\n \n return radius\n\ndef data_nn(data,voxel_dims,radius):\n #kd tree with a radius of 35 gives most common nn num to be 14 which is the number of nearest neighbours in a cube\n kd_tree = spatial.KDTree(data.loc[:,['z','y','x']][~np.isnan(data.loc[:,['z','y','x']])]*voxel_dims)\n nn_index = kd_tree.query_ball_tree(kd_tree,r=radius)\n \n nn_num = [len(pt_nn) for pt_nn in nn_index]\n \n nn_data = pd.concat([np.mean(data.iloc[i[1:]],axis=0) for i in nn_index],axis=1).transpose()\n nn_data.index= data.index\n nn_data['num_nn'] = nn_num \n\n nn_data_std = pd.concat([np.std(data.iloc[i[1:]],axis=0) for i in nn_index],axis=1).transpose()\n nn_data_std.index= data.index\n nn_data_std['num_nn'] = nn_num\n \n return nn_data,nn_data_std\n\n\ndef color_map(int_array, cmap):\n min_intensity = np.nanmin(int_array)\n max_intensity = np.nanmax(int_array)\n norm = col.Normalize(vmin=min_intensity,vmax = max_intensity)\n col_map = cm.get_cmap(cmap)\n lut=cm.ScalarMappable(norm=norm,cmap=col_map)\n rgb_array = np.empty((len(int_array),4))\n \n for i in range(len(int_array)):\n rgb_array[i,:] = lut.to_rgba(int_array[i])\n \n return rgb_array\n\ndef density_map(xaxis_array,yaxis_array,window_size=20,normalize = False):\n \n assert(type(xaxis_array) == type(yaxis_array)), 'Both arrays must be of the same type'\n \n if type(xaxis_array) == np.ndarray or type(xaxis_array) == pd.core.series.Series:\n assert(xaxis_array.shape[0] == yaxis_array.shape[0]),'Both arrays must have the same length'\n\n if normalize == True:\n xaxis_array = nucseg.decimal_normalization(xaxis_array)\n yaxis_array = nucseg.decimal_normalization(yaxis_array)\n \n xaxis_max = np.round(np.nanmax(xaxis_array))\n yaxis_max = np.round(np.nanmax(yaxis_array))\n xaxis_min = np.round(np.nanmin(xaxis_array))\n yaxis_min = np.round(np.nanmin(yaxis_array))\n\n xaxis_intervals = np.linspace(xaxis_min,xaxis_max,window_size)\n yaxis_intervals = np.linspace(yaxis_min,yaxis_max,window_size)\n\n density = np.zeros((window_size,window_size),dtype = np.int16)\n for i in range(len(xaxis_intervals)-1):\n for j in range(len(yaxis_intervals)-1):\n density[-(j+1),i] = xaxis_array[(xaxis_array >= xaxis_intervals[i])&(xaxis_array < xaxis_intervals[i+1]) & (yaxis_array >= yaxis_intervals[j]) & (yaxis_array = xaxis_intervals[i])&(xaxis_array[array_index] < xaxis_intervals[i+1]) & (yaxis_array[array_index] >= yaxis_intervals[j]) & (yaxis_array[array_index] 0:\n density[-(j+1),i] += 1\n return density","repo_name":"DillanSaunders/TailbudAnalysis","sub_path":"nucseg_utils.py","file_name":"nucseg_utils.py","file_ext":"py","file_size_in_byte":10083,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"15"} +{"seq_id":"31418091922","text":"##########################################################################\n# #\n# Filename: ring_group_graph.py #\n# Author: htdv92 #\n# Date created: #\n# Date Last-Modified: #\n# Python Version: 3.7 #\n# Dependicies: #\n# Description: A #\n# #\n##########################################################################\n\nimport random\n\n\"\"\"\nA Ring Group Graph is defined by four parameters m, k, p and q and is constructed as follows:\n• Create mk vertices. The vertices are partitioned into m groups each of size k. The groups are labelled from 0 to m−1.\n• For each pair of distinct vertices u and v, let lu and lv be the labels of the groups that u and v belong to respectively and\n– iflu =lv (thatis,uandvareinthesamegroup)orif|lu−lv|=1modm(thatis,uandvare in adjacent groups), add an edge between u and v with probability p,\n– otherwise add an edge between u and v with probability q.\n\nm = group number\nk = group size\np = \nq = \n\"\"\"\n\n\ndef load_graph(m, k, p, q):\n num_nodes = m * k\n ring_graph = {} # initialize empty graph\n\n for vertex in range(num_nodes): ring_graph[vertex] = set() # Add vertices\n\n for vertex_u in range(num_nodes):\n vertex_v = vertex_u + 1\n for vertex_v in range(vertex_v, num_nodes):\n group_u = vertex_u // k\n group_v = vertex_v // k\n random_number = random.random()\n test = abs(group_u - group_v) % m\n if (group_u == group_v) or (test == 1) or test == (m-1):\n if random_number < p:\n ring_graph[vertex_u].add(vertex_v)\n ring_graph[vertex_v].add(vertex_u)\n else:\n if random_number < q:\n ring_graph[vertex_u].add(vertex_v)\n ring_graph[vertex_v].add(vertex_u)\n\n return ring_graph\n","repo_name":"Ollivanders/Network-Analysis","sub_path":"Code/ring_group_graph.py","file_name":"ring_group_graph.py","file_ext":"py","file_size_in_byte":2321,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"15"} +{"seq_id":"43602336626","text":"from tkinter import *\nfrom Driver import Driver\nfrom HomeworkList import HomeworkList\nfrom functools import partial\nimport pickle\nimport os\nimport datetime\nimport threading\nimport time\n\n\nclass Ui:\n def __init__(self):\n self.ui = Tk()\n self.start_ui()\n self.reader = Driver()\n self.homework = HomeworkList()\n self.timer = 0\n self.auto = threading.Thread(target=self.auto_load_thread, daemon=True)\n self.id_input = Label(self.ui, text='아이디', font='Verdana 10 bold', background='white')\n self.id_value = Entry(self.ui)\n self.password_input = Label(self.ui, text='비밀번호', font='Verdana 10 bold', background='white')\n self.password_value = Entry(self.ui, show='*')\n self.password_value.bind('', self.enter_key)\n self.login_btn = Button(self.ui, text='로그인', command=self.click_login, height=2, font='Verdana 10 bold'\n , background='white')\n self.is_rest = False\n self.time_interval = 24\n self.subject_name = []\n self.homework_name = []\n self.end_time = []\n self.remain = []\n self.submit_btn = []\n self.submit = []\n self.login()\n self.ui.mainloop()\n\n def start_ui(self):\n self.ui.title('과제 시간표')\n self.ui.configure(background='white')\n\n # Login Class\n def login(self):\n if os.path.isfile('./loginData.bin'):\n self.reader.Login.load_login_data()\n Label(self.ui, text='과���', font='Verdana 10 bold', background='white').grid(row=0, column=0)\n Label(self.ui, text='과제 이름', font='Verdana 10 bold', background='white').grid(row=0, column=1)\n Label(self.ui, text='제출 기한', font='Verdana 10 bold', background='white').grid(row=0, column=2)\n Label(self.ui, text='남은 기간', font='Verdana 10 bold', background='white').grid(row=0, column=3)\n Label(self.ui, text='제출 여부', font='Verdana 10 bold', background='white').grid(row=0, column=4)\n Button(self.ui, text='로그아웃', command=self.click_logout, background='white').grid(row=0, column=5)\n self.read_homework_file()\n self.auto.start()\n else:\n self.id_input.grid(row=0, column=0)\n self.id_value.grid(row=0, column=1)\n self.password_input.grid(row=1, column=0)\n self.password_value.grid(row=1, column=1)\n self.login_btn.grid(row=0, column=2, rowspan=2)\n\n def enter_key(self, event):\n self.click_login()\n\n def click_login(self):\n self.reader.Login.login(str(self.id_value.get()), str(self.password_value.get()))\n self.reader.Login.save_login_data()\n self.id_input.destroy()\n self.id_value.destroy()\n self.password_input.destroy()\n self.password_value.destroy()\n self.login_btn.destroy()\n self.login()\n\n def click_logout(self):\n if os.path.isfile('./loginData.bin'):\n os.remove('./loginData.bin')\n self.ui.quit()\n\n # Driver Class\n def click_submit(self, index):\n submit_driver = self.reader.create_driver('chrome')\n self.reader.login_homepage(submit_driver)\n if not self.reader.submit_homework(submit_driver, self.homework.homework_list[index]):\n self.reader.delete_driver(submit_driver)\n return\n self.reader.wait_terminate(submit_driver)\n self.reader.delete_driver(submit_driver)\n self.auto_homework_loader()\n\n # 남은 시간을 refresh 해줌.\n def refresh_time(self):\n now = datetime.datetime.now()\n now_day = now.date()\n year = now.year\n remain_days = []\n\n for homework_data in self.homework.homework_list:\n remain_days.append((datetime.date(int(year), int(homework_data[2][1]), int(homework_data[2][2]))\n - now_day).days)\n i = 0\n remove_item =[]\n for homework_data in self.homework.homework_list:\n if remain_days[i] > 1:\n homework_data.append(str(remain_days[i]) + ' 일 전..')\n elif remain_days[i] >= 0:\n remain_time = int(((remain_days[i] * 24 + int(homework_data[3][0]) - now.hour) * 60\n + int(homework_data[3][1]) - now.minute) / 60)\n if remain_time > 24:\n homework_data.append('1 일 전..')\n elif remain_time > 0:\n homework_data.append(str(remain_time) + ' 시간 전..')\n else:\n homework_data.append('1 시간 이내..')\n else:\n remove_item.append(homework_data)\n i += 1\n for remove in remove_item:\n self.homework.homework_list.remove(remove)\n\n # ui에 적용.\n def grid_homework_list(self):\n self.refresh_time()\n i = 0\n self.ui.title(\"과제 시간표\")\n for homework_data in self.homework.homework_list:\n time_info = '20' + homework_data[2][0] + '년 ' + homework_data[2][1] + '월 ' + homework_data[2][2] + '일 ' \\\n + homework_data[3][0] + '시 ' + homework_data[3][1] + '분까지...'\n self.subject_name.append(Label(self.ui, text=homework_data[0], background='white'))\n self.homework_name.append(Label(self.ui, text=homework_data[1], background='white'))\n self.end_time.append(Label(self.ui, text=time_info, background='white'))\n self.remain.append(Label(self.ui, text=homework_data[5], background='white'))\n self.submit.append(Label(self.ui, text=homework_data[4], background='white'))\n self.submit_btn.append(Button(self.ui, text='제출하기',\n command=threading.Thread(target=partial(self.click_submit, i),\n daemon=True).start, background='red',\n foreground='white'))\n self.subject_name[i].grid(row=i + 1, column=0)\n self.homework_name[i].grid(row=i + 1, column=1)\n self.end_time[i].grid(row=i + 1, column=2)\n self.remain[i].grid(row=i + 1, column=3)\n self.submit[i].grid(row=i + 1, column=4)\n self.submit_btn[i].grid(row=i + 1, column=5)\n i += 1\n if i == 0:\n self.subject_name.append(Label(self.ui, text='현재 ', background='white'))\n self.homework_name.append(Label(self.ui, text='남아있는 ', background='white'))\n self.end_time.append(Label(self.ui, text='e-learning', background='white'))\n self.remain.append(Label(self.ui, text='과제가', background='white'))\n self.submit.append(Label(self.ui, text='없습니다.', background='white'))\n self.submit_btn.append(Label(self.ui, text='^^ ', background='white'))\n self.subject_name[i].grid(row=i + 1, column=0)\n self.homework_name[i].grid(row=i + 1, column=1)\n self.end_time[i].grid(row=i + 1, column=2)\n self.remain[i].grid(row=i + 1, column=3)\n self.submit[i].grid(row=i + 1, column=4)\n self.submit_btn[i].grid(row=i + 1, column=5)\n\n def read_homework_file(self):\n if os.path.isfile('./' + self.reader.Login.login_data[0] + '.bin'):\n file = open('./' + self.reader.Login.login_data[0] + '.bin', 'rb')\n self.homework.homework_list = pickle.load(file)\n file.close()\n self.grid_homework_list()\n\n def save_homework_file(self):\n file = open('./' + self.reader.Login.login_data[0] + '.bin', 'wb')\n pickle.dump(self.homework.homework_list, file)\n file.close()\n\n # auto thread 로 계속 값을 가져옴.\n def auto_load_thread(self):\n while True:\n self.auto_homework_loader()\n time.sleep(30 - (datetime.datetime.now().minute % 30))\n while self.timer < self.time_interval:\n time.sleep(300)\n self.refresh_ui()\n self.timer += 1\n self.timer = 0\n\n def auto_homework_loader(self):\n auto_driver = self.reader.create_driver('phantom')\n self.ui.title('과제 시간표 (로그인...)')\n if not self.reader.login_homepage(auto_driver):\n self.ui.title('과제 시간표 로그인 실패')\n self.reader.delete_driver(auto_driver)\n return\n self.ui.title('과제 시간표 (읽는 중...)')\n if not self.reader.read_homework_table(auto_driver):\n self.ui.title('과제 시간표 읽기 실패')\n self.reader.delete_driver(auto_driver)\n return\n self.reader.delete_driver(auto_driver)\n self.homework.create_homework_list(self.reader.homework_table)\n self.save_homework_file()\n self.refresh_ui()\n\n def refresh_ui(self):\n i = 0\n count = len(self.subject_name)\n while i < count:\n self.subject_name[i].destroy()\n self.homework_name[i].destroy()\n self.end_time[i].destroy()\n self.remain[i].destroy()\n self.submit[i].destroy()\n self.submit_btn[i].destroy()\n i += 1\n self.subject_name.clear()\n self.homework_name.clear()\n self.end_time.clear()\n self.remain.clear()\n self.submit.clear()\n self.submit_btn.clear()\n self.ui.after(0, self.grid_homework_list)","repo_name":"HyeockJinKim/Homework-Memo","sub_path":"Ui.py","file_name":"Ui.py","file_ext":"py","file_size_in_byte":9572,"program_lang":"python","lang":"en","doc_type":"code","stars":4,"dataset":"github-code","pt":"15"} +{"seq_id":"73763574411","text":"import csv\npath='usernames.csv'\n\nclass buscar_nomes_cartao:\n \"\"\"\n lista nomes com string OO\n \"\"\"\n def __init__(self, parametro='322'):\n \"\"\"\n Construtor de objetos para listar nomes com substring\n e inicio do campo do cartão.\n\n Args:\n parametro (int): numero do cartãopen_code\n \"\"\"\n self.parametro = parametro\n self.busca_cartao_string = self.busca_cartao_OO_v1()\n self.busca_cartao_incial = self.busca_cartao_OO_v2()\n \n def busca_cartao_OO_v1(self):\n \"\"\"\n Metódo para buscar cartões por string\n \"\"\"\n lista_completa = []\n lista_nomes = []\n with open(path, newline='\\n') as csvfile:\n reader = csv.DictReader(csvfile)\n for line in reader:\n lista_completa.append(line)\n for item in lista_completa:\n try:\n if self.parametro in item.get('credit_card'):\n lista_nomes.append(item['name'])\n except KeyError:\n print(KeyError)\n return lista_nomes\n\n def busca_cartao_OO_v2(self):\n \"\"\"\n Metódo para buscar cartões pela inicial do cartão\n \"\"\"\n lista_completa = []\n lista_nomes = []\n with open(path, newline='\\n') as csvfile:\n reader = csv.DictReader(csvfile)\n for line in reader:\n lista_completa.append(line)\n for item in lista_completa:\n try:\n if self.parametro in item.get('credit_card')[0:3]:\n lista_nomes.append(item['name'])\n except KeyError:\n print(KeyError)\n return lista_nomes\n\nprint('--- Exercicio 01 e 02 em OO sem parametro ---')\nbuscar1 = buscar_nomes_cartao()\nprint(buscar1.busca_cartao_string)\nprint(buscar1.busca_cartao_incial)\nprint('\\n--- Exercicio 01 e 02 em OO passando parametro ---')\nbuscar2 = buscar_nomes_cartao('222')\nprint(buscar2.busca_cartao_string)\nprint(buscar2.busca_cartao_incial)\n\n","repo_name":"GuilhermeSSx/NappAcademy1","sub_path":"semana 03/exercicio09.py","file_name":"exercicio09.py","file_ext":"py","file_size_in_byte":2022,"program_lang":"python","lang":"pt","doc_type":"code","stars":0,"dataset":"github-code","pt":"15"} +{"seq_id":"2217641493","text":"import pandas as pd\n\ndf = pd.read_excel('tabla2.xlsx')\nprint(df.columns)\nvalues = df['Id'].values\nprint(values)\ndf.describe()\n\n#mostrar tabla\ncolumnas = ['Id', 'Nombre', 'Nivel_De_Poder']\ndf_seleccionados = df[columnas]\nprint(df_seleccionados)\n\ndf['Incremento_De_Poder'] = df.Nivel_De_Poder.apply(lambda x: \\\n \tx*4 if x > 8000 else x*2)\n\ndf.to_excel('resultado.xlsx', sheet_name='Hoja1') \n\noverpower = df[df.Incremento_De_Poder > 40000] \nwith open('max.txt', 'w') as gen_file:\n gen_file.write('') \n\nfor i in overpower.index: \n with open(\"max.txt\", \"a\") as max_power:\n max_power.write('Se detecto un alto nivel de poder en la fila : ' + str(overpower[\"Id\"][i]) +'\\n')\n\n\n# Replace missing values to None\n#auto['city-mpg'] = auto['city-mpg'].replace(['missing'], np.nan)\n#print(auto['city-mpg'].unique()) \n\n# Change data type\n#auto['city-mpg'] = auto['city-mpg'].astype('float')\n \n# Change the data type of `Rating` to category\n#clothes['Rating'] = pd.Categorical(clothes['Rating'], \\ \n# ['very unsatisfied', 'unsatisfied', 'neutral', 'satisfied', 'very satisfied'], ordered = True) \n\n#Cat codes asigna valor numerico a cada categoria\n#median_index = np.median(df['education'].cat.codes)\n#print(median_index) # Output: 9\n\n#For ordinal categorical data\n#nintieth_perc_ind = np.percentile(df['education'].cat.codes, 90)\n#nintieth_perc_cat = correct_order[int(nintieth_perc_ind)]\n#print(nintieth_perc_cat): #output: Bachelors\n\n#calcular proporciones de valores de columna, sin incluir missing\n#health_proportions = nyc_trees['health'].value_counts(normalize = True)\n#calcular proporciones de valores de columna, incluyendo missing\n#health_proportions_2 = nyc_trees['health'].value_counts(normalize = True, dropna = False)\n\n#Then, we can use the sum or mean to calculate a frequency or proportion of Trues in the data.\n#change the value for the one u want to calculate\n#(df.workclass == 'Local-gov').sum() #output: 2093\n#(df.workclass == 'Local-gov').mean() #output: 0.064","repo_name":"Alastordmg/Python","sub_path":"poder.py","file_name":"poder.py","file_ext":"py","file_size_in_byte":2086,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"15"} +{"seq_id":"24970845090","text":"#!/usr/bin/env python3\n# -*- coding: utf-8 -*-\n\"\"\"\n@author: EmaPajic\n\"\"\"\n\nimport unittest\nfrom assignment4 import count_islands\n\nclass Test(unittest.TestCase):\n \n def setUp(self):\n self.tiles_empty = []\n self.tiles1 = [[False,False],\n [False,False]]\n self.tiles2 = [[True,True]]\n self.tiles3 = [[True , True , True , True , True],\n [True , False, False, False, True],\n [True , False, True , False, True],\n [True , False, False, False, True],\n [True , True , True , True , True]]\n \n def test_empty(self):\n self.assertEqual(0,count_islands(0,0,self.tiles_empty))\n \n def test_small(self):\n self.assertEqual(0,count_islands(2,2,self.tiles1))\n self.assertEqual(1,count_islands(1,2,self.tiles2))\n \n def test_bigger(self):\n self.assertEqual(2,count_islands(5,5,self.tiles3))\n \ndef suite():\n suite = unittest.TestSuite()\n suite.addTest(Test('test_empty'))\n suite.addTest(Test('test_small'))\n suite.addTest(Test('test_bigger'))\n return suite\n\ndef main():\n runner = unittest.TextTestRunner()\n runner.run(suite())\n \nmain()\n","repo_name":"flerdacodeu/CodeU-2018-Group7","sub_path":"EmaPajic/assignment4/test_assignment4.py","file_name":"test_assignment4.py","file_ext":"py","file_size_in_byte":1245,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"15"} +{"seq_id":"37702792529","text":"from enum import Enum\n\n\nclass StudentKeywords(Enum):\n FIO = \"fio\"\n NAME = \"name\"\n SURNAME = \"surname\"\n PATRONYMIC = \"patronymic\"\n STATUS = \"status\"\n EMAIL = \"email\"\n NUMBER = \"number\"\n DISLOCATION = \"dislocation\"\n SCHOOL = \"school\"\n POST = \"post\"\n HOW_KNOW = \"how_know\"\n EDUCATIONAL_PROGRAM = \"educational_program\"\n LIST_OF_COURSES = \"list_of_courses\"\n MENTIONS = \"mentions\"\n SHEET = \"sheet\"\n WORKBOOK = \"workbook\"\n ROW = \"row\"\n\n\nclass StudentStatus(Enum):\n SCHOOLBOY = 1\n STUDENT = 2\n PARENT = 3\n ANOTHER = 4\n\n\nstudents_keywords = {\n StudentKeywords.FIO: ['|фио|', '|ученика|', '|фио|участника|'],\n StudentKeywords.NAME: ['|имя|', '|имя|ученика|', '|имя|участника|'],\n StudentKeywords.SURNAME: ['|фамилия|', '|фамилия|ученика|', '|фамилия|участника|'],\n StudentKeywords.PATRONYMIC: ['|отчество|', '|отчество|ученика|', '|отчество|участника|'],\n StudentKeywords.STATUS: ['|статус|', '|статус|ученика|', '|статус|участника|', '|ваш|статус|',\n '|кем|вы|являетесь|'],\n StudentKeywords.EMAIL: ['|почта|', '|почта|ученика|', '|почта|участника|', '|email|', '|e-mail|'],\n StudentKeywords.NUMBER: ['|номер|', '|номер|ученика|', '|номер|участника|', '|телефон|', '|телефон|ученика|',\n '|телефон|участника|'],\n StudentKeywords.DISLOCATION: ['|место|проживания|', '|город|', '|страна|', '|проживания|'],\n StudentKeywords.SCHOOL: ['|школа|', '|учебы|', '|школы|'],\n StudentKeywords.POST: ['|должность|', '|класс|'],\n StudentKeywords.HOW_KNOW: ['|узнали о|', '|как|узнали|', '|узнали|'],\n StudentKeywords.EDUCATIONAL_PROGRAM: ['|образовательная|программа|', '|программа|', '|интересующая|Оп|',\n '|интересующая|программа|',\n '|оп|', '|консультации|', '|консультация|', '|консультации|программы|'],\n # StudentKeywords.LIST_OF_COURSES: ['консультации', 'консультация']\n}\n\nstudents_banned_keywords = {\n StudentKeywords.FIO: ['сопровождающего'],\n StudentKeywords.NAME: ['сопровождающего', 'в чате'],\n StudentKeywords.SURNAME: ['сопровождающего'],\n StudentKeywords.PATRONYMIC: ['сопровождающего']\n}\n\n\nclass TrainingPrograms(Enum):\n PMI = \"PMI\"\n PI = \"PI\"\n PAD = \"PAD\"\n KNAD = \"KNAD\"\n EAD = \"EAD\"\n ONE_OF_THEM = \"ONE_OF_THEM\"\n\n\ndoesnt_want_to_visit = [\"|не|заинтересован|\",\n \"|не|заинтересован|в|поступлении|на|эту|образовательную|программу|\"]\n\ntraining_programs_keywords = {TrainingPrograms.PMI: ['пми', 'прикладная|математика|и|информатика'],\n TrainingPrograms.PI: ['пи', 'программная|инженерия'],\n TrainingPrograms.PI: ['пи', 'программная|инженерия'],\n TrainingPrograms.PAD: ['пад', 'прикладной|анализ|данных'],\n TrainingPrograms.KNAD: ['кнад', 'компьютерные|науки|и|анализ|данных'],\n TrainingPrograms.EAD: ['эад', 'экономика|и|анализ|данных']\n }\n\nparents_keywords = [\"родительское|собрание\", \"родительское\"]\n\nstudent_status_keywords = {StudentStatus.SCHOOLBOY: ['школьник', 'школьница', 'абитуриент'],\n StudentStatus.STUDENT: ['студент', 'студентка'],\n StudentStatus.PARENT: ['родитель', 'мама', 'папа', 'родители']\n }\n","repo_name":"kr1sta1l/HSEAnalysis","sub_path":"modules/gui/calculator/database/keywords/keywords.py","file_name":"keywords.py","file_ext":"py","file_size_in_byte":4353,"program_lang":"python","lang":"ru","doc_type":"code","stars":0,"dataset":"github-code","pt":"15"} +{"seq_id":"33315364874","text":"import json\nimport boto3\n\ndef lambda_handler(event, context):\n \n # Variaveis\n path_File = \"/tmp/transacoes.txt\"\n fileName = \"transacoes.txt\"\n nameS3 = \"transacoes-enviadas\"\n \n # Cria arquivo\narquivo = open(\"/tmp/transacoes.txt\", 'w')\narquivo.write('{ \"nsu\": 1, \"cartao\": \"1234567890123456\" , \"valor\": \"10.00\", \"data\": \"10102021\" } \\n')\narquivo.write('{ \"nsu\": 2, \"cartao\": \"2234567890123456\" , \"valor\": \"20.00\", \"data\": \"20102021\" } \\n')\narquivo.write('{ \"nsu\": 3, \"cartao\": \"3234567890123456\" , \"valor\": \"30.00\", \"data\": \"30102021\" } \\n')\narquivo.close()\n\n\n#\"Upload S3\"\ns3 = boto3.client('s3')\nwith open (\"/tmp/transacoes.txt\", \"rb\") as f:\n s3.upload_fileobj(f, \"transacoes-enviadas\", \"transacoes.txt\")\n \nprint ('processamento efetuado com sucesso...')","repo_name":"marcelomgabriel/pocs","sub_path":"phyton-s3/upload-file-s3-lambda.py","file_name":"upload-file-s3-lambda.py","file_ext":"py","file_size_in_byte":781,"program_lang":"python","lang":"pt","doc_type":"code","stars":0,"dataset":"github-code","pt":"15"} +{"seq_id":"13510958288","text":"#!/usr/bin/env python3\nimport requests\nimport json\nimport os\nfrom time import sleep, time\nimport sqlite3\nfrom argparse import ArgumentParser\nfrom requests.adapters import HTTPAdapter\nfrom requests.packages.urllib3.util.retry import Retry\n\ndef is_bot_game(g):\n\treturn g[\"players\"][\"white\"][\"ui_class\"] == \"bot\" \\\n\tor g[\"players\"][\"black\"][\"ui_class\"] == \"bot\"\n\nclass OGS_Mirror:\n\n\tdef __init__(self, db_path, sgf_dir):\n\t\tprint(\"SOLite database:\", db_path);\n\t\tself.db=sqlite3.connect(db_path, isolation_level='IMMEDIATE')\n\t\tself.dbc=self.db.cursor()\n\t\tself.dbc.execute(\"CREATE TABLE IF NOT EXISTS response (url TEXT UNIQUE NOT NULL, content TEXT);\")\n\t\tself.dbc.execute(\"CREATE TABLE IF NOT EXISTS player_id (name TEXT UNIQUE NOT NULL, id INTEGER);\")\n\t\t# games table is for conveniently searching downloaded sgf\n\t\tself.dbc.execute(\"CREATE TABLE IF NOT EXISTS games (id INTEGER UNIQUE, playerB TEXT, playerW TEXT, started TEXT, ended TEXT, robot INTEGER);\")\n\t\tself.min_request_interval = 0.5\n\t\tself.sgf_dir = sgf_dir\n\n\t\tstrat=Retry(total=5,\n\t\t\tstatus_forcelist=[429, 500, 502, 503, 504],\n\t\t\tmethod_whitelist=[\"HEAD\", \"GET\", \"OPTIONS\"],\n\t\t\tbackoff_factor=5)\n\t\tadapter=HTTPAdapter(max_retries=strat)\n\t\tself.sess=requests.Session()\n\t\tself.sess.mount(\"http://\", adapter)\n\t\tself.sess.mount(\"https://\", adapter)\n\t\n\tdef close(self):\n\t\tself.sess.close()\n\t\tself.dbc.close()\n\t\tself.db.commit()\n\t\tself.db.close()\n\t\n\tdef get_raw(self, url):\n\t\tprint(\"GET\", url)\n\t\tsleep(self.min_request_interval)\n\t\tr=self.sess.get(url)\n\t\tif r.status_code == requests.codes.ok:\n\t\t\treturn r.text\n\t\tprint(\"HTTP status\", r.status_code)\n\t\treturn None\n\t\n\tdef get_cached(self, url):\n\t\tfor row in self.dbc.execute('SELECT content FROM response WHERE url = ?', (url,)):\n\t\t\tprint(\"from cache:\", url)\n\t\t\treturn row[0]\n\t\tcontent = self.get_raw(url)\n\t\tif content:\n\t\t\tself.dbc.execute(\"INSERT INTO response (url, content) VALUES (?,?)\", (url, content))\n\t\treturn content\n\n\tdef get_file(self, url, filepath):\n\t\tif not os.path.exists(filepath) or os.path.getsize(filepath) == 0:\n\t\t\tos.makedirs(os.path.dirname(filepath), exist_ok=True)\n\t\t\tcontent=self.get_raw(url).encode(\"utf8\")\n\t\t\tif content:\n\t\t\t\twith open(filepath,\"wb\") as f:\n\t\t\t\t\tf.write(content)\n\t\t\t\tprint(\"wrote\", len(content), \"bytes to file\", filepath)\n\t\t\t\treturn True\n\t\treturn False\n\n\tdef get_player_id(self, username):\n\t\tfor row in self.dbc.execute('SELECT id FROM player_id WHERE name = ?', (username,)):\n\t\t\treturn int(row[0])\n\t\turl=\"http://online-go.com/api/v1/players?username=\" + requests.utils.quote(username,safe='')\n\t\tds=self.get_cached(url);\n\t\ti=None\n\t\tif ds:\n\t\t\tds=json.loads(ds)\n\t\t\ti=ds[\"results\"][0][\"id\"]\n\t\t\t# what if player not found ?\n\t\t\tself.dbc.execute(\"INSERT INTO player_id (name,id) VALUES (?,?)\", (username, i))\n\t\treturn i\n\n\tdef get_recent_games(self, pid, limit=-1, quit_early=False):\n\t\tpage=0\n\t\tgames_found=0\n\t\tgames_saved=0\n\t\twhile limit < 0 or games_found < limit:\n\t\t\tpage += 1\n\t\t\tds = self.get_raw(\"http://online-go.com/api/v1/players/{}/games?ordering=-id&page={}\".format(pid,page))\n\t\t\tif ds is None:\n\t\t\t\t# we don't know how many pages exist, try them all until 404\n\t\t\t\tbreak\n\t\t\tds = json.loads(ds)\n\t\t\tgames = ds[\"results\"]\n\t\t\tnew_games_saved = 0\n\t\t\tfor g in games:\n\t\t\t\tif g[\"mode\"] != \"game\":\n\t\t\t\t\tcontinue\n\t\t\t\ti=g[\"id\"]\n\t\t\t\tb=g[\"players\"][\"black\"][\"username\"]\n\t\t\t\tw=g[\"players\"][\"white\"][\"username\"]\n\t\t\t\tstarted=g.get(\"started\",None)\n\t\t\t\tended=g.get(\"ended\",None)\n\t\t\t\trobot=is_bot_game(g)\n\t\t\t\turl=\"http://online-go.com/api/v1/games/{}/sgf\".format(i)\n\t\t\t\tpath=os.path.join(self.sgf_dir, \"{}-{}-{}.sgf\".format(i,b,w))\n\t\t\t\tif self.get_file(url, path):\n\t\t\t\t\tnew_games_saved += 1\n\t\t\t\t\tself.db.execute(\"INSERT INTO games (id,playerB,playerW,started,ended,robot) VALUES (?,?,?,?,?,?)\",\n\t\t\t\t\t\t(i, b, w, started, ended, robot))\n\t\t\t\tgames_found += 1\n\t\t\t\tif games_found == limit:\n\t\t\t\t\tbreak\n\t\t\tgames_saved += new_games_saved\n\t\t\tprint(\"page\", page, \"games found\", games_found, \"saved\", games_saved)\n\t\t\tif quit_early and new_games_saved==0:\n\t\t\t\tbreak\n\ndef main():\n\tap=ArgumentParser(prog=\"sgf_get.py\",\n\t\tdescription=\"\"\"\nFetches at most LIMIT most recent games (most recent first) of user USERNAME from online-go.com.\nSGF files are saved to directory OUTPUTDIR.\nYou can re-run this script whenever to keep your local SGF collection up to date.\n\"\"\")\n\tap.add_argument(\"username\", metavar=\"USERNAME\", nargs='+', help='Can specify multiple usernames. Case sensitive')\n\tap.add_argument(\"-l\", \"--limit\", metavar=\"LIMIT\", type=int, default=100, help='Maximum number of recent games to check. Default 100. Use -1 for no limit.')\n\tap.add_argument(\"-o\", \"--outputdir\", metavar=\"OUTPUTDIR\", type=str, default='./sgf', help=\"Default ./sgf\")\n\tap.add_argument(\"-k\", \"--keep-going\", action='store_true', help='Keep going all the way into the past even if many games are found to be already downloaded')\n\targs=ap.parse_args()\n\n\tassert type(args.outputdir) is str\n\tassert type(args.limit) is int\n\n\tdb_path = os.path.join(args.outputdir, 'sgf_get.db')\n\tos.makedirs(args.outputdir, exist_ok=True)\n\n\tprint(\"Output directory:\", args.outputdir)\n\tprint(\"SQLite database file:\", db_path)\n\tprint(\"Maximum games:\", args.limit)\n\n\ttry:\n\t\tapi=OGS_Mirror(db_path = db_path, sgf_dir = args.outputdir)\n\n\t\tfor username in args.username:\n\t\t\tuserid=api.get_player_id(username)\n\t\t\tif userid is None:\n\t\t\t\tprint(\"user not found:\", username)\n\t\t\telse:\n\t\t\t\tprint(\"fetching games for user\", username, \"ID:\", userid)\n\t\t\t\tapi.get_recent_games(pid = userid, limit = args.limit, quit_early = not (args.keep_going is True))\n\texcept KeyboardInterrupt:\n\t\tprint(\"Canceled\")\n\tfinally:\n\t\tapi.close()\n\t\tprint(\"Done\")\n\nmain()\n\n","repo_name":"sinf/ogs_sgf_get","sub_path":"sgf_get.py","file_name":"sgf_get.py","file_ext":"py","file_size_in_byte":5598,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"15"} +{"seq_id":"4375056550","text":"# a statistical look at the target for attacks.\nclass TargetAnalyser(object):\n\n dbaccessor = None\n\n def getLocationWithKills(self):\n attacks = self.dbaccessor.getAll()\n attackLocation = []\n\n for attack in attacks:\n formatAttack = {}\n\n try:\n formatAttack[\"kills\"] = int(attack[\"kill_count\"])\n except Exception as e:\n #kills were 0\n formatAttack[\"kills\"] = 0\n\n formatAttack[\"city\"] = attack[\"city\"]\n formatAttack[\"region\"] = attack[\"region_name\"]\n formatAttack[\"year\"] = attack[\"year\"]\n formatAttack[\"description\"] = attack[\"description\"]\n\n try:\n formatAttack[\"longitude\"] = float(attack[\"longitude\"])\n formatAttack[\"latitude\"] = float(attack[\"latitude\"])\n except Exception as e:\n #could not convert lat lng\n continue\n attackLocation.append(formatAttack)\n\n return attackLocation\n\n\n def __init__(self, dbaccessor):\n self.dbaccessor = dbaccessor\n","repo_name":"Guardian-Development/TerrorAttackAnalysis","sub_path":"terror-attack-analysis/analysis/targetanalyser.py","file_name":"targetanalyser.py","file_ext":"py","file_size_in_byte":1101,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"15"} +{"seq_id":"30228339800","text":"import argparse\nfrom gamestate import GameState\nimport GameWindow\nfrom curses import wrapper\n\nparser = argparse.ArgumentParser()\nparser.add_argument('R', help='number of rows for the game board (>=5)')\nparser.add_argument('C',help='number of columns for the game board (>=5)')\nargs = parser.parse_args()\n\n\ndef GameRun(stdscr):\n \"\"\"\n initiate interactive window\n \"\"\"\n params = {\n 'title_rows': 2,\n 'window_size': (Game.nrow+2, Game.ncol*2+2),\n 'status_rows': 3\n }\n window = GameWindow.Window(params,stdscr)\n window.set_title(\"Tetris.py: written by Li Zeng\")\n \n \"\"\"\n start game\n \"\"\"\n while not Game.gameover() and window.key() != 27:\n \"\"\"\n check if a new piece is needed\n if so, generate random piece, and reset needNew flag\n \"\"\"\n if Game.RequestNew():\n cur_piece = Game.RandomPiece()\n Game.needNew = False\n # if cur_piece not valid, then game over\n if not Game.ValidPiece(cur_piece):\n break\n \n \"\"\"\n print the game with piece overlay\n \"\"\"\n Game.print_to_window(window,cur_piece)\n \n \"\"\"\n ask for movement direction when it can move down\n otherwise, fix the piece to board, and rest needNew flag\n \"\"\" \n if Game.ValidMove(cur_piece,'d'):\n # request a movement\n window.set_status(\"Use the direction button to move the stone (up:rotation)\",1)\n Game.print_to_window(window,cur_piece)\n # process new movement\n window.newKey()\n mv = Game.keymap.get(window.key(),' ')\n if not Game.ValidMove(cur_piece, mv):\n window.set_status(\"Invalid move.\",2)\n else:\n window.set_status('',2)\n cur_piece = cur_piece.makeMove(mv)\n if Game.ValidMove(cur_piece,'d'):\n cur_piece = cur_piece.makeMove('d')\n else:\n window.set_status('',2)\n Game.addPiece(cur_piece)\n Game.fullRow()\n Game.needNew = True\n \n \n window.set_status(\"Game Over. Press any key to exit.\",2)\n Game.print_to_window(window, cur_piece)\n window.newKey()\n window.closeWindow()\n\n\nif __name__ == \"__main__\":\n # initialize game\n nrow = int(args.R)\n ncol = int(args.C)\n Game = GameState(nrow,ncol)\n wrapper(GameRun)\n \n \n","repo_name":"zengliX/Games","sub_path":"Tetris/Tetris.py","file_name":"Tetris.py","file_ext":"py","file_size_in_byte":2459,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"15"} +{"seq_id":"40202144347","text":"import numpy as np\nimport pandas as pd\nimport sklearn.linear_model as skl_lm\nimport sklearn.model_selection as skl_ms\nfrom pandas.io.parsers.readers import read_csv\n\n#Importing\ntrain = pd.read_csv('/Users/admin/Documents/CodeProjects/numpy_projects/train.csv').dropna().reset_index(drop=True)\n#train.info()\n\n# Choose output variable\nX = train.drop(columns=['Lead'])\ny = train['Lead']\n\n# Split parameters\nn_fold = 10\ncv = skl_ms.KFold(n_splits = n_fold, random_state = 1, shuffle = True)\n\n# Visualizing\nfrom IPython.display import set_matplotlib_formats\nset_matplotlib_formats('svg') # Output as svg. Else you can try png\nfrom IPython.core.pylabtools import figsize\nfigsize(10, 6) # Width and hight\nnp.set_printoptions(precision=3)\n\n# Model\nnp.random.seed(1)\nmodel = skl_lm.LogisticRegression(solver='liblinear')\nX_train, X_test, y_train, y_test = skl_ms.train_test_split(X,y,test_size=0.23)\n\nmodel.fit(X_train, y_train)\nprint(model)\npredict_prob=model.predict_proba(X_test)\nprint(model.classes_)\npredict_prob[0:5]\nprediction=np.empty(len(X_test), dtype=object)\nprediction=np.where(predict_prob[:, 0]>=0.5, 'Female', 'Male')\nprediction[0:5]\n\n#Confusion matrix\nprint(pd.crosstab(prediction, y_test), '\\n')\nprint(f\"Accuracy: {np.mean(prediction == y_test):.3f}\")","repo_name":"pictorviktor/smasken","sub_path":"logisticRegression.py","file_name":"logisticRegression.py","file_ext":"py","file_size_in_byte":1259,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"15"} +{"seq_id":"41682152577","text":"# -*- coding: utf-8 -*-\r\n##############################################################################\r\n#\r\n# OpenERP, Open Source Management Solution\r\n# Copyright (C) 2011 NovaPoint Group LLC ()\r\n# Copyright (C) 2004-2010 OpenERP SA ()\r\n#\r\n# This program is free software: you can redistribute it and/or modify\r\n# it under the terms of the GNU General Public License as published by\r\n# the Free Software Foundation, either version 3 of the License, or\r\n# (at your option) any later version.\r\n#\r\n# This program is distributed in the hope that it will be useful,\r\n# but WITHOUT ANY WARRANTY; without even the implied warranty of\r\n# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the\r\n# GNU General Public License for more details.\r\n#\r\n# You should have received a copy of the GNU General Public License\r\n# along with this program. If not, see \r\n#\r\n##############################################################################\r\n\r\nimport time\r\nimport decimal_precision as dp\r\n\r\nfrom openerp.osv import osv, fields\r\n\r\nclass account_invoice(osv.osv):\r\n _inherit = \"account.invoice\"\r\n\r\n def _total_weight_net(self, cr, uid, ids, field_name, arg, context=None):\r\n \"\"\"Compute the total net weight of the given Invoice.\"\"\"\r\n result = {}\r\n for invoice in self.browse(cr, uid, ids, context=context):\r\n result[invoice.id] = 0.0\r\n for line in invoice.invoice_line:\r\n if line.product_id:\r\n result[invoice.id] += line.weight_net or 0.0\r\n return result\r\n\r\n def _get_invoice(self, cr, uid, ids, context=None):\r\n \"\"\"Get the invoice ids of the given Invoice Lines.\"\"\"\r\n result = {}\r\n for line in self.pool.get('account.invoice.line').browse(cr, uid, ids, context=context):\r\n result[line.invoice_id.id] = True\r\n return result.keys()\r\n\r\n def _amount_shipment_tax(self, cr, uid, shipment_taxes, shipment_charge):\r\n val = 0.0\r\n for c in self.pool.get('account.tax').compute_all(cr, uid, shipment_taxes, shipment_charge, 1)['taxes']:\r\n val += c.get('amount', 0.0)\r\n return val\r\n\r\n def _amount_all(self, cr, uid, ids, name, args, context=None):\r\n res = super(account_invoice, self)._amount_all(cr, uid, ids, name, args, context=context)\r\n for invoice in self.browse(cr, uid, ids, context=context):\r\n if invoice.shipcharge:\r\n res[invoice.id]['amount_total'] = res[invoice.id]['amount_untaxed'] + res[invoice.id]['amount_tax'] + invoice.shipcharge\r\n return res\r\n\r\n def _get_invoice_tax(self, cr, uid, ids, context=None):\r\n invoice = self.pool.get('account.invoice')\r\n return super(account_invoice, invoice)._get_invoice_tax(cr, uid, ids, context=context)\r\n\r\n def _get_invoice_line(self, cr, uid, ids, context=None):\r\n invoice = self.pool.get('account.invoice')\r\n return super(account_invoice, invoice)._get_invoice_line(cr, uid, ids, context=context)\r\n\r\n def _get_invoice_from_line(self, cr, uid, ids, context=None):\r\n invoice = self.pool.get('account.invoice')\r\n return super(account_invoice, invoice)._get_invoice_from_line(cr, uid, ids, context=context)\r\n\r\n def finalize_invoice_move_lines(self, cr, uid, invoice, move_lines):\r\n \"\"\"\r\n finalize_invoice_move_lines(cr, uid, invoice, move_lines) -> move_lines\r\n Hook method to be overridden in additional modules to verify and possibly alter the\r\n move lines to be created by an invoice, for special cases.\r\n Args:\r\n invoice: browsable record of the invoice that is generating the move lines\r\n move_lines: list of dictionaries with the account.move.lines (as for create())\r\n Returns:\r\n The (possibly updated) final move_lines to create for this invoice\r\n \"\"\"\r\n move_lines = super(account_invoice, self).finalize_invoice_move_lines(cr, uid, invoice, move_lines)\r\n if invoice.type == \"out_refund\":\r\n account = invoice.account_id.id\r\n else:\r\n account = invoice.sale_account_id.id\r\n if invoice.type in ('out_invoice','out_refund') and account and invoice.shipcharge:\r\n lines1 = {\r\n 'analytic_account_id': False,\r\n 'tax_code_id': False,\r\n 'analytic_lines': [],\r\n 'tax_amount': False,\r\n 'name': 'Shipping Charge',\r\n 'ref': '',\r\n 'currency_id': False,\r\n 'credit': invoice.shipcharge,\r\n 'product_id': False,\r\n 'date_maturity': False,\r\n 'debit': False,\r\n 'date': time.strftime(\"%Y-%m-%d\"),\r\n 'amount_currency': 0,\r\n 'product_uom_id': False,\r\n 'quantity': 1,\r\n 'partner_id': invoice.partner_id.id,\r\n 'account_id': account\r\n }\r\n move_lines.append((0, 0, lines1))\r\n has_entry = False\r\n for move_line in move_lines:\r\n journal_entry = move_line[2]\r\n if journal_entry['account_id'] == invoice.partner_id.property_account_receivable.id:\r\n journal_entry['debit'] += invoice.shipcharge\r\n has_entry = True\r\n break\r\n if not has_entry: # If debit line does not exist create one\r\n lines2 = {\r\n 'analytic_account_id': False,\r\n 'tax_code_id': False,\r\n 'analytic_lines': [],\r\n 'tax_amount': False,\r\n 'name': '/',\r\n 'ref': '',\r\n 'currency_id': False,\r\n 'credit': False,\r\n 'product_id': False,\r\n 'date_maturity': False,\r\n 'debit': invoice.shipcharge,\r\n 'date': time.strftime(\"%Y-%m-%d\"),\r\n 'amount_currency': 0,\r\n 'product_uom_id': False,\r\n 'quantity': 1,\r\n 'partner_id': invoice.partner_id.id,\r\n 'account_id': invoice.partner_id.property_account_receivable.id\r\n }\r\n move_lines.append((0, 0, lines2))\r\n return move_lines\r\n \r\n\r\n _columns = {\r\n 'amount_total': fields.function(_amount_all, method=True, digits_compute=dp.get_precision('Account'), string='Total',\r\n store = {\r\n 'account.invoice': (lambda self, cr, uid, ids, c={}: ids, ['invoice_line','shipcharge'], -10),\r\n 'account.invoice.tax': (_get_invoice_tax, None, -10),\r\n 'account.invoice.line': (_get_invoice_line, ['price_unit', 'invoice_line_tax_id', 'quantity', 'discount', 'invoice_id'], -10),\r\n }, multi='all'),\r\n 'total_weight_net': fields.function(_total_weight_net, method=True, string='Total Net Weight',\r\n store = {\r\n 'account.invoice': (lambda self, cr, uid, ids, c={}: ids, ['invoice_line'], 10),\r\n 'account.invoice.line': (_get_invoice, ['quantity', 'product_id'], 10),\r\n },help=\"The cumulated net weight of all the invoice lines.\"),\r\n 'shipcharge': fields.float('Shipping Cost', readonly=True),\r\n 'ship_method': fields.char('Ship Method', size=128, readonly=True),\r\n 'ship_method_id': fields.many2one('shipping.rate.config', 'Shipping Method', readonly=True),\r\n 'sale_account_id':fields.many2one('account.account', 'Shipping Account', readonly=True,\r\n help='This account represents the g/l account for booking shipping income.')\r\n }\r\n\r\naccount_invoice()\r\n\r\nclass invoice_line(osv.osv):\r\n \"\"\"Add the net weight to the object \"Invoice Line\".\"\"\"\r\n _inherit = 'account.invoice.line'\r\n\r\n def _weight_net(self, cr, uid, ids, field_name, arg, context=None):\r\n \"\"\"Compute the net weight of the given Invoice Lines.\"\"\"\r\n result = {}\r\n for line in self.browse(cr, uid, ids, context=context):\r\n result[line.id] = 0.0\r\n if line.product_id:\r\n result[line.id] += line.product_id.weight_net * line.quantity\r\n return result\r\n \r\n \r\n _columns = {\r\n 'weight_net': fields.function(_weight_net, method=True, string='Net Weight', help=\"The net weight in Kg.\",\r\n store = {\r\n 'account.invoice.line': (lambda self, cr, uid, ids, c={}: ids,['quantity', 'product_id'], -11),\r\n })\r\n }\r\n\r\ninvoice_line()\r\n\r\nclass account_invoice_tax_inherit(osv.osv):\r\n _inherit = \"account.invoice.tax\"\r\n\r\n def compute(self, cr, uid, invoice_id, context=None):\r\n tax_grouped = super(account_invoice_tax_inherit, self).compute(cr, uid, invoice_id, context=context)\r\n tax_obj = self.pool.get('account.tax')\r\n cur_obj = self.pool.get('res.currency')\r\n inv = self.pool.get('account.invoice').browse(cr, uid, invoice_id, context=context)\r\n cur = inv.currency_id\r\n company_currency = inv.company_id.currency_id.id\r\n tax_ids = inv.ship_method_id and inv.ship_method_id.shipment_tax_ids\r\n if tax_ids:\r\n for tax in tax_obj.compute_all(cr, uid, tax_ids, inv.shipcharge, 1)['taxes']:\r\n val = {}\r\n val.update({\r\n 'invoice_id': inv.id,\r\n 'name': tax['name'],\r\n 'amount': tax['amount'],\r\n 'manual': False,\r\n 'sequence': tax['sequence'],\r\n 'base': tax['price_unit'] * 1\r\n })\r\n if inv.type in ('out_invoice','in_invoice'):\r\n val.update({\r\n 'base_code_id': tax['base_code_id'],\r\n 'tax_code_id': tax['tax_code_id'],\r\n 'base_amount': cur_obj.compute(cr, uid, inv.currency_id.id, company_currency, val['base'] * tax['base_sign'],\r\n context={'date': inv.date_invoice or time.strftime('%Y-%m-%d')}, round=False),\r\n 'tax_amount': cur_obj.compute(cr, uid, inv.currency_id.id, company_currency, val['amount'] * tax['tax_sign'],\r\n context={'date': inv.date_invoice or time.strftime('%Y-%m-%d')}, round=False),\r\n 'account_id': tax['account_collected_id'] or line.account_id.id\r\n })\r\n else:\r\n val.update({\r\n 'base_code_id': tax['ref_base_code_id'],\r\n 'tax_code_id': tax['ref_tax_code_id'],\r\n 'base_amount': cur_obj.compute(cr, uid, inv.currency_id.id, company_currency, val['base'] * tax['ref_base_sign'],\r\n context={'date': inv.date_invoice or time.strftime('%Y-%m-%d')}, round=False),\r\n 'tax_amount': cur_obj.compute(cr, uid, inv.currency_id.id, company_currency, val['amount'] * tax['ref_tax_sign'],\r\n context={'date': inv.date_invoice or time.strftime('%Y-%m-%d')}, round=False),\r\n 'account_id': tax['account_paid_id'] or line.account_id.id\r\n })\r\n\r\n key = (val['tax_code_id'], val['base_code_id'], val['account_id'])\r\n if not key in tax_grouped:\r\n tax_grouped[key] = val\r\n else:\r\n tax_grouped[key]['amount'] += val['amount']\r\n tax_grouped[key]['base'] += val['base']\r\n tax_grouped[key]['base_amount'] += val['base_amount']\r\n tax_grouped[key]['tax_amount'] += val['tax_amount']\r\n\r\n for t in tax_grouped.values():\r\n t['base'] = cur_obj.round(cr, uid, cur, t['base'])\r\n t['amount'] = cur_obj.round(cr, uid, cur, t['amount'])\r\n t['base_amount'] = cur_obj.round(cr, uid, cur, t['base_amount'])\r\n t['tax_amount'] = cur_obj.round(cr, uid, cur, t['tax_amount'])\r\n return tax_grouped\r\n\r\naccount_invoice_tax_inherit()\r\n# vim:expandtab:smartindent:tabstop=4:softtabstop=4:shiftwidth=4:\r\n","repo_name":"savoirfairelinux/openerp-usa","sub_path":"sale_negotiated_shipping/account_invoice.py","file_name":"account_invoice.py","file_ext":"py","file_size_in_byte":12469,"program_lang":"python","lang":"en","doc_type":"code","stars":4,"dataset":"github-code","pt":"15"} +{"seq_id":"32321466459","text":"import gensim.models \nfrom gensim.corpora import WikiCorpus\nfrom gensim.models.doc2vec import TaggedDocument,Doc2Vec\nimport codecs\nimport os\nimport jieba\nimport jieba.posseg as pseg\nimport numpy as np\n\n\nabs_path = os.path.dirname(__file__)\n\n# 结巴加载用户词典\nuserDict_path = os.path.join(abs_path,r\"../extract/词典/all.txt\")\njieba.load_userdict(userDict_path)\n\n# 停用词文本\nstopwords_path = os.path.join(abs_path,r\"../extract/baidu_stopwords.txt\")\n\ndef get_stopwords_list():\n \"\"\"返回stopwords列表\"\"\"\n stopwords_list = [i.strip()\n for i in codecs.open(stopwords_path).readlines()]\n return stopwords_list\n\n\n# 所有的停用词列表\nstopwords_list = get_stopwords_list()\n\n# 现有数据的data_path\n# data_path = os.path.join(abs_path,r\"./data\")\ndata_path = os.path.join(abs_path,r\"../extract/data/a.csv\")\n\n\ndef cut_sentence(sentence):\n \"\"\"对切割之后的词语进行过滤,去除停用词,保留名词,英文和自定义词库中的词,长度大于2的词\"\"\"\n # print(sentence,\"*\"*100)\n # eg:[pair('今天', 't'), pair('有', 'd'), pair('雾', 'n'), pair('霾', 'g')]\n seg_list = pseg.lcut(sentence)\n seg_list = [i for i in seg_list if i.flag not in stopwords_list]\n filtered_words_list = []\n for seg in seg_list:\n # print(seg)\n if len(seg.word) <= 1:\n continue\n elif seg.flag == \"eng\":\n if len(seg.word) <= 2:\n continue\n else:\n filtered_words_list.append(seg.word)\n elif seg.flag.startswith(\"n\"):\n filtered_words_list.append(seg.word)\n elif seg.flag in [\"x\", \"eng\"]: # 是自定一个词语或者是英文单词\n filtered_words_list.append(seg.word)\n return filtered_words_list\n\ndef build_doc2vec_model():\n '''构建doc2vec的模型,保存'''\n document = []\n i = 0\n for line in codecs.open(data_path,\"r\").readlines():\n words = cut_sentence(line)\n # tag = line.split(\",\")[:3]\n tag = [str(i)]\n document.append(TaggedDocument(words,tag))\n i+=1\n \n doc2vec_model = Doc2Vec(document,dm=1,vector_size=100,window=8,min_count=1,\n sample=1e-3, negative=5, workers=8,hs=1,epochs=6)\n \n doc2vec_model_path = os.path.join(abs_path,\"doc2vec_model/model.doc2vec\")\n doc2vec_model.save(doc2vec_model_path)\n\n\ndef load_model():\n '''加载模型,返回doc2vec的model'''\n doc2vec_model_path = os.path.join(abs_path,\"doc2vec_model/model.doc2vec\")\n doc2vec_model = Doc2Vec.load(doc2vec_model_path)\n return doc2vec_model\n\ndef doc_similarity(model,text1,text2):\n '''\n 计算text1和text2在model下的相似度\n model:doc2vec的model\n text2,text1:需要计算相似性的文本\n '''\n vec1 = model.infer_vector(cut_sentence(text1))\n vec2 = model.infer_vector(cut_sentence(text2))\n # _similarity = 0\n # if vec1 !=0 and vec2 !=0:\n _similarity = (vec1.dot(vec2))/(np.sqrt(vec1.dot(vec1))*np.sqrt(vec1.dot(vec2)))\n return _similarity\n\ndef doc_infer_vector(model,text):\n '''\n 获取doc的向量值,100列\n '''\n infer_words = cut_sentence(text)\n vec = model.infer_vector(infer_words)\n return vec\n\ndef _usage1_infer_vector(text):\n '''\n 用例:获取doc的vector\n '''\n model = load_model()\n infer_words = cut_sentence(text)\n vec = model.infer_vector(infer_words)\n # print(vec)\n return vec\n\ndef _usage2_find_exist_most_similar_sentence(text):\n '''\n 用例:计算text和构建model的文章中,最相似的前10个文档\n '''\n model = load_model()\n infer_words = cut_sentence(text)\n infer_vector = model.infer_vector(infer_words)\n sims = model.docvecs.most_similar([infer_vector],topn=len(model.docvecs))\n \n print('Test Document :{} \\n'.format(text))\n\n print('SIMILAR/DISSIMILAR DOCS PER MODEL %s:\\n' % model)\n\n doc_list = codecs.open(data_path,\"r\").readlines()\n \n for k in range(10):\n print(\"%s %s: %s\\n\"%(k,sims[k],doc_list[int(sims[k][0])]))\n\nif __name__ == \"__main__\":\n #1. 构建模型\n # build_doc2vec_model()\n\n text = '''相机\",\"运动相机\",\"摄影摄像\",\"GoPro hero7运动相机水下潜水 4K户外直播防水摄像机 官方标配+三向自拍杆+双充电池+64G卡 hero7 black黑色(4K.60帧支持直播)\",\"【11月1日0:00开门红秒杀,立即抢购】【HyperSmooth视频稳定升级】【4K60+12MP高清画质/照片定时器】'''\n #2,获取doc���vector\n # ret = _usage1_infer_vector(text)\n # print(type(ret))\n\n #3. 获取用来训练模型的现有语料中和text最相似的doc\n # _usage2_find_exist_most_similar_sentence(text)\n\n text2 = '''\"手机\",\"数据线\",\"手机配件\",\"酷波【两个装】安卓Micro转Type-C转接头 手机数据线/充电线转换头 适用小米8SE/6华为P20荣耀9i一加6三星S9+\",\"\"'''\n\n #4. 获取文档的vector\n model = load_model()\n vec = doc_infer_vector(model,text)\n print(vec)\n\n #5. 计算文档相似性\n\n sim = similarity(model,text,text2)\n print(sim)\n\n\n \n\n","repo_name":"SpringMagnolia/keywordExtracor","sub_path":"tovec/doc2vec.py","file_name":"doc2vec.py","file_ext":"py","file_size_in_byte":5094,"program_lang":"python","lang":"en","doc_type":"code","stars":4,"dataset":"github-code","pt":"15"} +{"seq_id":"28073770850","text":"#!/usr/bin/env python3.7\n\nfrom rtlsdr import RtlSdr\nimport syslog\nimport math\nfrom threading import Timer # for watchdog timer\nimport sys\nimport datetime\nimport time\nimport logging\nimport signal\n\nNUM_SAMPLES = 32768\nBARGRAPH = \"################################################################################\" \\\n + \" \"\n\nloop_flag = True\n\ndef main():\n\n #Setup the SDR device here to match a centre freq; \n #TODO: Read from noSQL table for settings; Error handling\n sdr = RtlSdr()\n # configure device\n sdr.sample_rate = 1.024e6 # Hz\n sdr.center_freq = 433.9e6 # Hz\n sdr.freq_correction = 20 # PPM\n sdr.gain = 'auto'\n \n signal.signal(signal.SIGTERM, service_shutdown)\n signal.signal(signal.SIGINT, service_shutdown)\n\n #To get some initial readings and an estimate of averages;\n for i in range(0, 10):\n rssi = MeasureRSSI(sdr)\n\n # Measure minimum RSSI over a few readings, auto-adjust for dongle gain\n min_rssi = 1000\n avg_rssi = 0\n for i in range(0, 10):\n rssi = MeasureRSSI(sdr)\n min_rssi = min(min_rssi, rssi)\n avg_rssi += rssi\n avg_rssi /= 10\n ampl_offset = avg_rssi\n max_rssi = MeasureRSSI(sdr) - ampl_offset\n avg_rssi = max_rssi + 20;\n counter = 0\n redirect_stderr() #as is the function name; redirect errors to prevent flooding of std-out\n\n \n #init_dt = datetime.datetime.now() #we want to take an initial time here to check on 1 minute intervals \n #run the reading in a loop; takes around 6 seconds to converge to a value\n while(loop_flag): \n #current_dt = datetime.datetime.now() \n #if ((current_dt - init_dt).total_seconds() > 1 ):\n #print(\"1 minute passed\")\n #init_dt = datetime.datetime.now()\n rssi = MeasureRSSI(sdr) - ampl_offset\n avg_rssi = ((9 * avg_rssi) + rssi) / 10 \n if avg_rssi > 30:\n with open(\"sms_tx_fd\", \"w\") as sms_wr:\n sms_wr.write(\"2\");\n syslog.syslog(LOG_INFOG, 'Sending SMS: Jamming Detected')\n break #as a result of jamming detected, we send the sms and exit gracefully\n time.sleep(0.2) #here so the process does not flood the CPU\n\n sdr.close() #close the resource\n\n# First attempt: using floating-point complex samples\ndef MeasureRSSI_1(sdr):\n samples = sdr.read_samples(NUM_SAMPLES)\n power = 0.0\n for sample in samples:\n power += (sample.real * sample.real) + (sample.imag * sample.imag)\n return 10 * (math.log(power) - math.log(NUM_SAMPLES))\n\n# Second go: read raw bytes, square and add those\ndef MeasureRSSI_2(sdr):\n data_bytes = sdr.read_bytes(NUM_SAMPLES * 2)\n power = 0\n for next_byte in data_bytes:\n signed_byte = next_byte + next_byte - 255\n power += signed_byte * signed_byte\n return 10 * (math.log(power) - math.log(NUM_SAMPLES) - math.log(127)) - 70\n\n# Third go: modify librtlsdr, do the square-and-add calculation in C\ndef MeasureRSSI_3(sdr):\n while(True):\n try:\n return sdr.read_power_dB(NUM_SAMPLES) - 112\n except OSError: # e.g. SDR unplugged...\n pass # go round and try again, SDR will be replugged sometime...\n\n# Select the desired implementation here:\ndef MeasureRSSI(sdr):\n return MeasureRSSI_1(sdr)\n# return sdr.read_offset_I(NUM_SAMPLES) / (NUM_SAMPLES / 2)\n# return sdr.read_offset_Q(NUM_SAMPLES) / (NUM_SAMPLES / 2)\n\ndef service_shutdown():\n loop_flag = False\n logging.info('Exiting gracefully')\n syslog.closelog()\n \n\ndef redirect_stderr():\n import os, sys\n sys.stderr.flush()\n err = open('/dev/null', 'a+')\n os.dup2(err.fileno(), sys.stderr.fileno()) # send ALSA underrun error messages to /dev/null\n \n\nif __name__ == \"__main__\":\n import os, sys\n#try:\n main()\n\n#except(SystemExit, KeyboardInterrupt):\n exit()\n","repo_name":"YashveerR/intellesure","sub_path":"rtlsdr_driver.py","file_name":"rtlsdr_driver.py","file_ext":"py","file_size_in_byte":3960,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"15"} +{"seq_id":"32973067752","text":"import pygame\n\nfrom pygame.math import Vector2\n\nfrom source.globals import GRID_SIZE\nfrom source.misc_gfx import Color\n\nclass TileMap:\n\tdef __init__(self, tile_manager):\n\t\tself.tile_manager = tile_manager\n\t\tself.wall_highlight = pygame.Surface(Vector2(GRID_SIZE, GRID_SIZE))\n\t\tself.wall_highlight.fill(Color.PAL_YEL_2)\n\t\tself.wall_highlight.set_alpha(128)\n\n\tdef draw(self, screen, offset, map_array, highlight_walls=False):\n\t\tfor x in range(map_array.shape[0]):\n\t\t\tfor y in range(map_array.shape[1]):\n\t\t\t\tmy_pos = Vector2(x*GRID_SIZE, y*GRID_SIZE)\n\t\t\t\tmy_tid = map_array[x,y]\n\t\t\t\tif self.tile_manager.tile_img[my_tid] != None:\n\t\t\t\t\tscreen.blit(self.tile_manager.tile_img[my_tid], my_pos + offset)\n\t\t\t\tif highlight_walls and self.tile_manager.is_wall[my_tid]:\n\t\t\t\t\tscreen.blit(self.wall_highlight, my_pos + offset, special_flags=pygame.BLEND_ALPHA_SDL2)\n","repo_name":"ribbiks/openbound","sub_path":"source/tilemap.py","file_name":"tilemap.py","file_ext":"py","file_size_in_byte":858,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"15"} +{"seq_id":"684543238","text":"from django.shortcuts import render\nfrom django.http import HttpResponse\nfrom django.template import loader\nfrom .models import Category\nfrom .models import Article\nimport random\n\n\ndef helloWorld(request):\n return HttpResponse(\"Hello world!\")\n\ndef main(request):\n categories = Category.objects.all().values()\n template = loader.get_template('index.html')\n context = {\n 'categories': categories,\n }\n return HttpResponse(template.render(context, request))\n\ndef browseall(request):\n categories = Category.objects.all().values()\n articles = Article.objects.all().order_by(\"-createdAt\")\n\n template = loader.get_template('browseall.html')\n context = {\n 'categories': categories,\n 'articles': articles,\n }\n return HttpResponse(template.render(context, request))\n\ndef browse(request, id):\n category = Category.objects.get(id=id)\n categories = Category.objects.all().values()\n articles = Article.objects.filter(category=id).order_by(\"-createdAt\")\n\n template = loader.get_template('browse.html')\n context = {\n 'category': category,\n 'categories': categories,\n 'articles': articles,\n }\n return HttpResponse(template.render(context, request))\n\ndef testing(request):\n template = loader.get_template('template.html')\n context = {\n 'categories': ['Technology', 'Health', 'Culture', 'Politics', 'Sports', 'Entertainment'], \n }\n return HttpResponse(template.render(context, request))\n\ndef article(request, id):\n categories = Category.objects.all().values()\n article = Article.objects.get(id=id)\n categoryArticles = list(Article.objects.filter(category=article.category.id))\n recommendedArticles = random.sample(categoryArticles, 3)\n while(article in recommendedArticles):\n recommendedArticles = random.sample(categoryArticles, 3)\n template = loader.get_template('article.html')\n context = {\n 'categories': categories,\n 'article': article,\n 'recommendedArticles': recommendedArticles,\n }\n return HttpResponse(template.render(context, request))\n","repo_name":"thelearner411/Media_Web_App","sub_path":"torremedia/app/views.py","file_name":"views.py","file_ext":"py","file_size_in_byte":2089,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"15"} +{"seq_id":"86512046375","text":"__author__ = 'piotrek'\n\nfrom PyQt5 import QtWidgets, QtCore, QtGui\n\n\nclass Pole(QtWidgets.QLabel):\n \n def __init__(self, parent=None):\n super().__init__('', parent)\n self.resize(100, 100)\n self.setMaximumSize(self.size())\n self.setAlignment(QtCore.Qt.AlignCenter)\n self.setStyleSheet('Pole { background-color: red; border: 3px solid black; color: blue; }')\n self.setFont(QtGui.QFont('arial', 30))\n self.czy_ustawiony = False\n\n def mousePressEvent(self, mouse_event: QtGui.QMouseEvent):\n rodzic_glowny = self.parent().parent()\n if not self.czy_ustawiony:\n self.setText(rodzic_glowny.ruchGracza)\n if rodzic_glowny.sprawdz():\n return\n rodzic_glowny.ruchGracza = 'X' if rodzic_glowny.ruchGracza == 'O' else 'O'\n rodzic_glowny.informacja.setText('Kolej gracza: {}'.format(rodzic_glowny.ruchGracza))\n rodzic_glowny.statusBar().showMessage('Kolej gracza: {}'.format(rodzic_glowny.ruchGracza), 5000)\n self.czy_ustawiony = True\n\n else:\n rodzic_glowny.statusBar().showMessage('Pole jest juz ustawione')\n\n def ustawienie(self):\n return self.czy_ustawiony\n\n def reset(self):\n self.czy_ustawiony = False\n self.setText('')\n self.setEnabled(True)\n","repo_name":"PMazur92/Tic-Tac-Toe-PyQt5","sub_path":"Pole.py","file_name":"Pole.py","file_ext":"py","file_size_in_byte":1337,"program_lang":"python","lang":"pl","doc_type":"code","stars":0,"dataset":"github-code","pt":"15"} +{"seq_id":"25567422527","text":"\r\nimport streamlit as st\r\nimport pandas as pd\r\nimport numpy as np\r\nfrom PIL import Image\r\nimport xgboost as xgb\r\nimport pickle\r\n\r\nst.set_page_config(page_title=\"Credit Card Fraud Detection App\", page_icon=\"💰\",\r\n layout='centered', initial_sidebar_state='expanded')\r\n\r\nfilename = \"Fraud_Detection_Model.pkl\"\r\nmodel = pickle.load(open('HR_Dataset_model_rfc.pkl', 'rb'))\r\n# df\r\ndf = pd.read_csv(\"HR_Dataset.csv\")\r\n\r\ndef set_bg_hack_url():\r\n st.markdown(\r\n f\"\"\"\r\n \r\n \"\"\",\r\n unsafe_allow_html=True\r\n )\r\n\r\n\r\nset_bg_hack_url()\r\n\r\n# img = Image.open(\"file2.jpeg\")\r\n# new_img = img.resize((700, 225))\r\n# col1, col2, col3 = st.columns([1, 6, 1])\r\n\r\n# with col1:\r\n# st.write(' ')\r\n# with col2:\r\n# st.image(new_img)\r\n# with col3:\r\n# st.write(' ')\r\n\r\nvtxt= \"💰Credit Card Fraud Detection App💰\"\r\nhtmlstr1 = f\"\"\"

\r\n {vtxt}\r\n

\"\"\"\r\nst.markdown(htmlstr1,unsafe_allow_html=True)\r\n\r\n# sidebar\r\nimg = Image.open(\"Front+cover.jpeg\")\r\nimg = img.resize((250, 200))\r\ncolor = '#d60000'\r\nst.sidebar.image(img)\r\n\r\nst.markdown(\r\n \"\"\"\r\n\r\n\"\"\",\r\n unsafe_allow_html=True,\r\n)\r\n\r\nhtml_temp2 = \"\"\"\r\n
\r\n

Credit Card Fraud Detection

\r\n

\"\"\"\r\nst.sidebar.markdown(html_temp2, unsafe_allow_html=True)\r\n\r\nst.sidebar.header(\r\n \"Credit card fraud detection is the collective term for the policies, tools, methodologies, and practices that credit card companies and financial institutions take to combat identity fraud and stop fraudulent transactions. \")\r\nst.sidebar.header(\"A credit card account that doesn't require possession of a physical card. Commonly a method used to make online purchases, it requires only that the thief knows your name, account number and the card's security code.\")\r\nst.sidebar.subheader(\"Predict the fraud according features.\")\r\n\r\n# df\r\ndf = pd.read_csv(\"HR_Dataset.csv\")\r\n# Departments\"\r\ndept_list = df[\"Departments \"].unique().tolist()\r\n#Departments = st.selectbox(\"YOUR DEPARTMENTS\", dept_list)\r\n# time_spend_company\r\ncompany = df[\"time_spend_company\"].unique().tolist()\r\ncompany = st.selectbox(\"COMPANY WORKING YEAR\", company)\r\n# satisfaction_level\r\nsatisfaction = st.slider(\"YOUR COMPANY SATISFACTION LEVEL\", 0., max( df[\"satisfaction_level\"]), 0.30)\r\n# salary\r\n#salary = df[\"salary\"].unique().tolist()\r\n#salary = st.selectbox(\"YOUR SALARY LEVEL\", salary)\r\n\r\n# last_evaluatio\r\nlast_evaluation = st.slider(\"YOUR FINAL EVALUATION\", 0., max(df[\"last_evaluation\"]), 0.60)\r\n# promotion_last_5years\r\n#promotion = df[\"promotion_last_5years\"].unique().tolist()\r\n#promotion = st.selectbox(\"Have you any promotions in the last 5 years?\", promotion)\r\n # average_montly_hours\r\naverage_montly_hours = st.slider(\"YOUR MONTHLY AVERAGE WORKING HOURS\", 0, max(df[\"average_montly_hours\"]), 150)\r\n\r\n# number_proje\r\nnumber_project = st.slider(\"NUMBER OF PROJECTS YOU WORKED\", 0, max(df[\"number_project\"]), 2)\r\n# Work accident\r\n#Work_accident = df[\"Work_accident\"].unique().tolist()\r\n#Work_accident = st.selectbox(\"WORK ACCIDENT\", Work_accident)\r\nmy_dict = {#\"Departments\": Departments,\r\n #\"salary\": salary,\r\n \"satisfaction_level\": round(satisfaction, 2),\r\n \"last_evaluation\": last_evaluation,\r\n \"average_montly_hours\": average_montly_hours,\r\n \"number_project\": number_project,\r\n \"time_spend_company\": company,\r\n #\"promotion\": promotion,\r\n #\"Work_accident\": Work_accident\r\n }\r\ndf = pd.DataFrame.from_dict([my_dict]) \r\nmyButton1 = st.button(\"Predict the Fraud\")\r\nbutton_style = \"\"\"\r\n \r\n \"\"\"\r\nst.markdown(button_style, unsafe_allow_html=True) \r\nif myButton1:\r\n filename =\"HR_Dataset_model_rfc.pkl\"\r\n model = pickle.load(open('HR_Dataset_model_rfc.pkl', 'rb'))\r\n pred = model.predict(df)\r\n\r\n st.success('Churn : {}'.format(pred[0]))\r\n","repo_name":"sue-yavuz/streamlit-example-02","sub_path":"Project02_streamlit.py","file_name":"Project02_streamlit.py","file_ext":"py","file_size_in_byte":5316,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"15"} +{"seq_id":"26220072922","text":"from flask import Flask, render_template, abort\nfrom dotenv import load_dotenv\n\nload_dotenv()\n\ndef create_app():\n app = Flask(__name__)\n\n projects = [\n {\n \"name\": \"Postit\",\n \"thumb\": \"img/postit.png\",\n \"hero\": \"img/postit-hero.jpg\",\n \"categories\": [\"python\", 'css', 'html'],\n 'slug': 'postit',\n 'prod': 'https://postit-3n3g.onrender.com'\n },\n {\n \"name\": \"A simple Cookie Clicker style game\",\n \"thumb\": \"img/weight.jpg\",\n \"hero\": \"img/weight-hero.jpg\",\n \"categories\": [\"python\", 'css', 'html'],\n 'slug': 'weight-clicker',\n 'prod': 'https://weight-clicker.onrender.com/'\n },\n {\n \"name\": \"Habit tracking app using Flask and MongoDB\",\n \"thumb\": \"img/habit-tracking.png\",\n \"hero\": \"img/habit-tracking-hero.png\",\n \"categories\": [\"python\", 'css', 'html', 'Udemy'],\n 'slug': 'habit-tracking',\n 'prod': 'https://flask-habit-tracker-91g6.onrender.com/'\n },\n {\n \"name\": \"Movie Watchlist\",\n \"thumb\": \"img/movie.jpg\",\n \"hero\": \"img/movie-hero.jpg\",\n \"categories\": [\"python\", 'css', 'html', 'Udemy'],\n 'slug': 'movie-watchlist',\n 'prod': 'https://movie-watchlist-eyzg.onrender.com/'\n },\n ]\n # create a dictionary to map slugs to projects so that we don't have to loop through all projects\n # whenever we want to get a slug\n slug_to_project = {project['slug']: project for project in projects}\n\n @app.route(\"/\")\n def home():\n return render_template(\"home.html\", projects=projects)\n\n\n @app.route(\"/about\")\n def about():\n return render_template(\"about.html\")\n\n\n @app.route(\"/contact\")\n def contact():\n return render_template(\"contact.html\")\n\n @app.route(\"/project/\")\n def project(slug):\n # if the slug doesn't exist return a 404 error\n if slug not in slug_to_project:\n abort(404)\n # return a render template using the slug to get the needed html page\n return render_template(f\"project_{slug}.html\", \n project=slug_to_project[slug]\n )\n\n @app.errorhandler(404)\n def pagenotfound(error):\n return render_template(\"404.html\"), 404\n\n return app","repo_name":"ashereth/Website-Portfolio","sub_path":"portfolio/__init__.py","file_name":"__init__.py","file_ext":"py","file_size_in_byte":2426,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"15"} +{"seq_id":"44238863165","text":"from __future__ import annotations\n\nimport os\nfrom pathlib import Path, PurePath\n\nimport pytest\nfrom pytest_mock import MockerFixture\n\nfrom legate.tester import (\n DEFAULT_CPUS_PER_NODE,\n DEFAULT_GPU_BLOAT_FACTOR,\n DEFAULT_GPU_DELAY,\n DEFAULT_GPU_MEMORY_BUDGET,\n DEFAULT_GPUS_PER_NODE,\n DEFAULT_NODES,\n DEFAULT_OMPS_PER_NODE,\n DEFAULT_OMPTHREADS,\n DEFAULT_RANKS_PER_NODE,\n FEATURES,\n config as m,\n)\nfrom legate.tester.args import PIN_OPTIONS, PinOptionsType\nfrom legate.util import colors\n\nREPO_TOP = Path(__file__).parents[4]\n\n\nclass TestConfig:\n def test_default_init(self) -> None:\n c = m.Config([])\n\n assert colors.ENABLED is False\n\n assert c.examples is True\n assert c.integration is True\n assert c.unit is False\n assert c.files is None\n assert c.last_failed is False\n\n assert c.features == (\"cpus\",)\n\n assert c.cpus == DEFAULT_CPUS_PER_NODE\n assert c.gpus == DEFAULT_GPUS_PER_NODE\n assert c.cpu_pin == \"partial\"\n assert c.gpu_delay == DEFAULT_GPU_DELAY\n assert c.fbmem == DEFAULT_GPU_MEMORY_BUDGET\n assert c.bloat_factor == DEFAULT_GPU_BLOAT_FACTOR\n assert c.omps == DEFAULT_OMPS_PER_NODE\n assert c.ompthreads == DEFAULT_OMPTHREADS\n assert c.ranks_per_node == DEFAULT_RANKS_PER_NODE\n assert c.launcher == \"none\"\n assert c.launcher_extra == []\n assert c.nodes == DEFAULT_NODES\n\n assert c.timeout is None\n assert c.debug is False\n assert c.dry_run is False\n assert c.verbose == 0\n assert c.test_root is None\n assert c.requested_workers is None\n assert c.legate_dir is None\n\n assert c.extra_args == []\n assert c.root_dir == PurePath(os.getcwd())\n\n # TODO (bv) restore when generalized\n # assert len(c.test_files) > 0\n # assert any(\"examples\" in str(x) for x in c.test_files)\n # assert any(\"integration\" in str(x) for x in c.test_files)\n # assert all(\"unit\" not in str(x) for x in c.test_files)\n\n assert c.legate_path == \"legate\"\n\n assert c.cov_bin is None\n assert c.cov_args == \"run -a --branch\"\n assert c.cov_src_path is None\n\n def test_color_arg(self) -> None:\n m.Config([\"test.py\", \"--color\"])\n\n assert colors.ENABLED is True\n\n def test_files(self) -> None:\n c = m.Config([\"test.py\", \"--files\", \"a\", \"b\", \"c\"])\n assert c.files == [\"a\", \"b\", \"c\"]\n\n def test_last_failed(self) -> None:\n c = m.Config([\"test.py\", \"--last-failed\"])\n assert c.last_failed\n\n @pytest.mark.parametrize(\"feature\", FEATURES)\n def test_env_features(\n self, monkeypatch: pytest.MonkeyPatch, feature: str\n ) -> None:\n monkeypatch.setenv(f\"USE_{feature.upper()}\", \"1\")\n\n # test default config\n c = m.Config([])\n assert set(c.features) == {feature}\n\n # also test with a --use value provided\n c = m.Config([\"test.py\", \"--use\", \"cuda\"])\n assert set(c.features) == {\"cuda\"}\n\n @pytest.mark.parametrize(\"feature\", FEATURES)\n def test_cmd_features(self, feature: str) -> None:\n # test a single value\n c = m.Config([\"test.py\", \"--use\", feature])\n assert set(c.features) == {feature}\n\n # also test with multiple / duplication\n c = m.Config([\"test.py\", \"--use\", f\"cpus,{feature}\"])\n assert set(c.features) == {\"cpus\", feature}\n\n @pytest.mark.parametrize(\n \"opt\", (\"cpus\", \"gpus\", \"gpu-delay\", \"fbmem\", \"omps\", \"ompthreads\")\n )\n def test_feature_options(self, opt: str) -> None:\n c = m.Config([\"test.py\", f\"--{opt}\", \"1234\"])\n assert getattr(c, opt.replace(\"-\", \"_\")) == 1234\n\n @pytest.mark.parametrize(\"value\", PIN_OPTIONS)\n def test_cpu_pin(self, value: PinOptionsType) -> None:\n c = m.Config([\"test.py\", \"--cpu-pin\", value])\n assert c.cpu_pin == value\n\n def test_workers(self) -> None:\n c = m.Config([\"test.py\", \"-j\", \"1234\"])\n assert c.requested_workers == 1234\n\n def test_timeout(self) -> None:\n c = m.Config([\"test.py\", \"--timeout\", \"10\"])\n assert c.timeout == 10\n\n def test_debug(self) -> None:\n c = m.Config([\"test.py\", \"--debug\"])\n assert c.debug is True\n\n def test_dry_run(self) -> None:\n c = m.Config([\"test.py\", \"--dry-run\"])\n assert c.dry_run is True\n\n @pytest.mark.parametrize(\"arg\", (\"-v\", \"--verbose\"))\n def test_verbose1(self, arg: str) -> None:\n c = m.Config([\"test.py\", arg])\n assert c.verbose == 1\n\n def test_verbose2(self) -> None:\n c = m.Config([\"test.py\", \"-vv\"])\n assert c.verbose == 2\n\n @pytest.mark.parametrize(\"arg\", (\"-C\", \"--directory\"))\n def test_test_root(self, arg: str) -> None:\n c = m.Config([\"test.py\", arg, \"some/path\"])\n assert c.test_root == \"some/path\"\n\n def test_legate_dir(self) -> None:\n c = m.Config([])\n assert c.legate_dir is None\n assert c.legate_path == \"legate\"\n assert c._legate_source == \"install\"\n\n def test_cmd_legate_dir_good(self) -> None:\n legate_dir = Path(\"/usr/local\")\n c = m.Config([\"test.py\", \"--legate\", str(legate_dir)])\n assert c.legate_dir == legate_dir\n assert c.legate_path == str(legate_dir / \"bin\" / \"legate\")\n assert c._legate_source == \"cmd\"\n\n def test_env_legate_dir_good(\n self, monkeypatch: pytest.MonkeyPatch\n ) -> None:\n legate_dir = Path(\"/usr/local\")\n monkeypatch.setenv(\"LEGATE_DIR\", str(legate_dir))\n c = m.Config([])\n assert c.legate_dir == legate_dir\n assert c.legate_path == str(legate_dir / \"bin\" / \"legate\")\n assert c._legate_source == \"env\"\n\n def test_extra_args(self) -> None:\n extra = [\"-foo\", \"--bar\", \"--baz\", \"10\"]\n c = m.Config([\"test.py\"] + extra)\n assert c.extra_args == extra\n\n # also test with --files since that option collects arguments\n c = m.Config([\"test.py\", \"--files\", \"a\", \"b\"] + extra)\n assert c.extra_args == extra\n c = m.Config([\"test.py\"] + extra + [\"--files\", \"a\", \"b\"])\n assert c.extra_args == extra\n\n def test_cov_args(self) -> None:\n cov_args = [\"--cov-args\", \"run -a\"]\n c = m.Config([\"test.py\"] + cov_args)\n assert c.cov_args == \"run -a\"\n\n\nclass Test_test_files:\n # first two tests are too sensitive to actual repo state and run location\n\n @pytest.mark.skip\n def test_basic(self) -> None:\n c = m.Config([\"test.py\", \"--root-dir\", str(REPO_TOP)])\n\n assert len(c.test_files) > 0\n assert any(\"examples\" in str(x) for x in c.test_files)\n assert any(\"integration\" in str(x) for x in c.test_files)\n\n assert not any(\"unit\" in str(x) for x in c.test_files)\n\n @pytest.mark.skip\n def test_unit(self) -> None:\n c = m.Config([\"test.py\", \"--unit\", \"--root-dir\", str(REPO_TOP)])\n assert len(c.test_files) > 0\n assert any(\"unit\" in str(x) for x in c.test_files)\n\n def test_error(self) -> None:\n c = m.Config([\"test.py\", \"--files\", \"a\", \"b\", \"--last-failed\"])\n with pytest.raises(RuntimeError):\n c.test_files\n\n @pytest.mark.parametrize(\"data\", (\"\", \" \", \"\\n\", \" \\n \"))\n def test_last_failed_empty(self, mocker: MockerFixture, data: str) -> None:\n mock_last_failed = mocker.mock_open(read_data=data)\n mocker.patch(\"builtins.open\", mock_last_failed)\n c1 = m.Config(\n [\"test.py\", \"--last-failed\", \"--root-dir\", str(REPO_TOP)]\n )\n c2 = m.Config([\"test.py\", \"--root-dir\", str(REPO_TOP)])\n assert c1.test_files == c2.test_files\n\n def test_last_failed(self, mocker: MockerFixture) -> None:\n mock_last_failed = mocker.mock_open(read_data=\"\\nfoo\\nbar\\nbaz\\n\")\n mocker.patch(\"builtins.open\", mock_last_failed)\n c = m.Config([\"test.py\", \"--last-failed\", \"--root-dir\", str(REPO_TOP)])\n assert c.test_files == (Path(\"foo\"), Path(\"bar\"), Path(\"baz\"))\n","repo_name":"nv-legate/legate.core","sub_path":"tests/unit/legate/tester/test_config.py","file_name":"test_config.py","file_ext":"py","file_size_in_byte":8033,"program_lang":"python","lang":"en","doc_type":"code","stars":170,"dataset":"github-code","pt":"15"} +{"seq_id":"74653150092","text":"from django.conf.urls import url, include\nfrom . import views\n\napp_name = 'pharma'\n\nurlpatterns = [\n\n # /pharma/\n url(r'^$', views.index, name='index'),\n\n # /pharma/doctor/\n url(r'^doctor/$', views.doctor, name='doctor'),\n\n # /pharma/medicine/\n url(r'^medicine/$', views.medicine, name='medicine'),\n\n # /pharma/nonmedicine/\n url(r'^nonmedicine/$', views.nonmedicine, name='nonmedicine'),\n\n # /pharma/staff/\n url(r'^staff/$', views.staff, name='staff'),\n\n # /pharma/docs/Andheri\n url(r'^docs/(?P[a-zA-Z]+)/$', views.dispdocs, name='dispdocs'),\n\n # /pharma/meds/Andheri\n url(r'^meds/(?P[a-zA-Z]+)/$', views.dispmeds, name='dispmeds'),\n\n # /pharma/nonmeds/Andheri\n url(r'^nonmeds/(?P[a-zA-Z]+)/$', views.dispnonmeds, name='dispnonmeds'),\n\n # /pharma/staff/Andheri\n url(r'^staff/(?P[a-zA-Z]+)/$', views.dispstaff, name='dispstaff'),\n# url(r'^staff/$', views.staff, name='staff'),\n\n url(r'^get_doctor/$', views.get_doctor),\n\n url(r'^get_medicine/$', views.get_medicine),\n\n url(r'^get_non_medicine/$', views.get_non_medicine),\n\n url(r'^get_staff/$', views.get_staff),\n\n]","repo_name":"divyegala/pharmacy","sub_path":"pharma/urls.py","file_name":"urls.py","file_ext":"py","file_size_in_byte":1154,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"15"} +{"seq_id":"26741532171","text":"from django.urls import path\nfrom . import views\n\n# URLs dos usuários\n\napp_name = 'user'\n\nurlpatterns = [\n path('cadastro/',views.register, name='cadastro'),\n path('cadastro_aluno/',views.Aluno_register.as_view(), name='cadastro_aluno'),\n path('cadastro_professor/',views.Professor_register.as_view(), name='cadastro_professor'),\n path('home/',views.home, name = 'home'),\n]","repo_name":"tomasolenscki/USPesos","sub_path":"user/urls.py","file_name":"urls.py","file_ext":"py","file_size_in_byte":386,"program_lang":"python","lang":"pt","doc_type":"code","stars":0,"dataset":"github-code","pt":"17"} +{"seq_id":"26801914697","text":"\nimport pygame\nimport constants\n\n\nclass Intro():\n def __init__(self, game):\n self.game = game\n self.srf_menu = game.srf_menu\n # images\n self.img_logo = pygame.image.load('images/assets/logo.png').convert() # PlayOnRetro logo \n self.img_intro1 = pygame.image.load('images/assets/intro1.png').convert() # background\n self.img_intro2 = pygame.image.load('images/assets/intro2.png').convert_alpha() # title\n self.img_intro3 = pygame.image.load('images/assets/intro3.png').convert_alpha() # pi\n # sounds\n self.sfx_intro1 = pygame.mixer.Sound('sounds/fx/sfx_intro1.wav') # flash effect\n self.sfx_intro2 = pygame.mixer.Sound('sounds/fx/sfx_intro2.wav') # text sliding\n self.sfx_intro3 = pygame.mixer.Sound('sounds/fx/sfx_intro3.wav') # PlayOnRetro\n self.sfx_intro3.set_volume(.4)\n # auxiliary surface for fading and flashing visual effects\n self.srf_aux = pygame.Surface(constants.MENU_UNSCALED_SIZE, pygame.SRCALPHA)\n\n\n # the ESC, RETURN or SPACE key has been pressed.\n def main_key_pressed(self):\n for event in pygame.event.get():\n if event.type == pygame.KEYDOWN:\n if event.key == pygame.K_ESCAPE or event.key == pygame.K_RETURN or event.key == pygame.K_SPACE:\n return True\n\n\n def fades_surface(self, target_surf, aux_surf, opacity, delay):\n aux_surf.set_alpha(0) # totally transparent \n for z in range(opacity):\n aux_surf.set_alpha(z) # opacity is being applied\n target_surf.blit(aux_surf, (0,0)) # the two surfaces come together to be drawn\n self.game.update_screen() # draw target_surf\n pygame.time.wait(delay) # speed of transition\n\n\n def play(self):\n # PlayOnRetro logo\n # fade in\n self.srf_menu.fill(constants.PALETTE[\"BLACK\"]) # black background\n self.srf_aux.blit(self.img_logo, (0, 0))\n self.fades_surface(self.srf_menu, self.srf_aux, 45, 12)\n if self.main_key_pressed(): return # allows skipping the intro\n self.sfx_intro3.play()\n pygame.time.wait(1500)\n if self.main_key_pressed(): return\n # fade out\n self.srf_aux.fill(constants.PALETTE[\"BLACK\"]) # black background\n self.fades_surface(self.srf_menu, self.srf_aux, 45, 12)\n if self.main_key_pressed(): return # allows skipping the intro \n pygame.time.wait(1500)\n if self.main_key_pressed(): return\n\n # RedPlanetPi\n self.sfx_intro1.play()\n self.srf_menu.fill(constants.PALETTE[\"WHITE\"]) # white background\n self.srf_aux.blit(self.img_intro1, (0, 0))\n self.fades_surface(self.srf_menu, self.srf_aux, 50, 8)\n pygame.time.wait(200)\n if self.main_key_pressed(): return # allows skipping the intro\n # slide the title \"RED PLANET\" from the right to its final position\n self.sfx_intro2.play()\n for x in range(-170, 0, 10):\n self.srf_menu.blit(self.img_intro1, (0, 0))\n self.srf_menu.blit(self.img_intro2, (x, 0))\n self.game.update_screen()\n # slides the PI from the bottom to its final position\n self.sfx_intro2.play()\n for y in range(140, -5, -10):\n self.srf_menu.blit(self.img_intro1, (0, 0))\n self.srf_menu.blit(self.img_intro2, (0, 0))\n self.srf_menu.blit(self.img_intro3, (198, y))\n self.game.update_screen()\n if self.main_key_pressed(): return # allows skipping the intro\n # pause for recreation. Ooohhh how wonderful!\n pygame.time.wait(500)","repo_name":"salvakantero/RedPlanetPi","sub_path":"intro.py","file_name":"intro.py","file_ext":"py","file_size_in_byte":3630,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"17"} +{"seq_id":"33631283912","text":"import torch\nfrom torch import nn\n\nfrom src.layers.layers import conv3x3\n\nfrom .common_model import CompressionModel\nfrom .video_net import LowerBound, UNet, get_enc_dec_models, get_hyper_enc_dec_models\nfrom ..utils.stream_helper import encode_i, decode_i, get_downsampled_shape, filesize, \\\n get_rounded_q, get_state_dict\n\n\nclass IntraNoAR(CompressionModel):\n def __init__(self, N=192, anchor_num=4):\n super().__init__(y_distribution='gaussian', z_channel=N)\n\n self.enc, self.dec = get_enc_dec_models(3, 16, N)\n self.refine = nn.Sequential(\n UNet(16, 16),\n conv3x3(16, 3),\n )\n self.hyper_enc, self.hyper_dec = get_hyper_enc_dec_models(N, N)\n self.y_prior_fusion = nn.Sequential(\n nn.Conv2d(N * 2, N * 3, 3, stride=1, padding=1),\n nn.LeakyReLU(0.2),\n nn.Conv2d(N * 3, N * 3, 3, stride=1, padding=1),\n nn.LeakyReLU(0.2),\n nn.Conv2d(N * 3, N * 3, 3, stride=1, padding=1)\n )\n\n self.y_spatial_prior = nn.Sequential(\n nn.Conv2d(N * 4, N * 3, 3, padding=1),\n nn.LeakyReLU(0.2),\n nn.Conv2d(N * 3, N * 3, 3, padding=1),\n nn.LeakyReLU(0.2),\n nn.Conv2d(N * 3, N * 2, 3, padding=1)\n )\n\n self.q_basic = nn.Parameter(torch.ones((1, N, 1, 1)))\n self.q_scale = nn.Parameter(torch.ones((anchor_num, 1, 1, 1)))\n # the exact q_step is q_basic * q_scale\n self.N = int(N)\n self.anchor_num = int(anchor_num)\n\n self._initialize_weights()\n\n def get_curr_q(self, q_scale):\n q_basic = LowerBound.apply(self.q_basic, 0.5)\n return q_basic * q_scale\n\n def forward(self, x, q_scale=None):\n curr_q = self.get_curr_q(q_scale)\n\n y = self.enc(x)\n y = y / curr_q\n z = self.hyper_enc(y)\n z_hat = self.quant(z)\n\n params = self.hyper_dec(z_hat)\n q_step, scales, means = self.y_prior_fusion(params).chunk(3, 1)\n y_res, y_q, y_hat, scales_hat = self.forward_dual_prior(\n y, means, scales, q_step, self.y_spatial_prior)\n\n y_hat = y_hat * curr_q\n x_hat = self.refine(self.dec(y_hat))\n\n if self.training:\n y_for_bit = self.add_noise(y_res)\n z_for_bit = self.add_noise(z)\n else:\n y_for_bit = y_q\n z_for_bit = z_hat\n bits_y = self.get_y_gaussian_bits(y_for_bit, scales_hat)\n bits_z = self.get_z_bits(z_for_bit, self.bit_estimator_z)\n mse = self.mse(x, x_hat)\n ssim = self.ssim(x, x_hat)\n\n _, _, H, W = x.size()\n pixel_num = H * W\n bpp_y = torch.sum(bits_y, dim=(1, 2, 3)) / pixel_num\n bpp_z = torch.sum(bits_z, dim=(1, 2, 3)) / pixel_num\n mse = torch.sum(mse, dim=(1, 2, 3)) / pixel_num\n\n bits = torch.sum(bpp_y + bpp_z) * pixel_num\n bpp = bpp_y + bpp_z\n\n return {\n \"x_hat\": x_hat,\n \"mse\": mse,\n \"ssim\": ssim,\n \"bit\": bits.item(),\n \"bpp\": bpp,\n \"bpp_y\": bpp_y,\n \"bpp_z\": bpp_z,\n }\n\n @staticmethod\n def get_q_scales_from_ckpt(ckpt_path):\n ckpt = get_state_dict(ckpt_path)\n q_scales = ckpt[\"q_scale\"]\n return q_scales.reshape(-1)\n\n def encode_decode(self, x, q_scale, output_path=None, pic_width=None, pic_height=None):\n # pic_width and pic_height may be different from x's size. X here is after padding\n # x_hat has the same size with x\n if output_path is None:\n return self.forward(x, q_scale)\n\n assert pic_height is not None\n assert pic_width is not None\n q_scale, q_index = get_rounded_q(q_scale)\n compressed = self.compress(x, q_scale)\n bit_stream = compressed['bit_stream']\n encode_i(pic_height, pic_width, q_index, bit_stream, output_path)\n bit = filesize(output_path) * 8\n\n height, width, q_index, bit_stream = decode_i(output_path)\n decompressed = self.decompress(bit_stream, height, width, q_index / 100)\n x_hat = decompressed['x_hat']\n\n result = {\n 'bit': bit,\n 'x_hat': x_hat,\n }\n return result\n\n def compress(self, x, q_scale):\n curr_q = self.get_curr_q(q_scale)\n\n y = self.enc(x)\n y = y / curr_q\n z = self.hyper_enc(y)\n z_hat = torch.round(z)\n\n params = self.hyper_dec(z_hat)\n q_step, scales, means = self.y_prior_fusion(params).chunk(3, 1)\n y_q_w_0, y_q_w_1, scales_w_0, scales_w_1, y_hat = self.compress_dual_prior(\n y, means, scales, q_step, self.y_spatial_prior)\n y_hat = y_hat * curr_q\n\n self.entropy_coder.reset_encoder()\n _ = self.bit_estimator_z.encode(z_hat)\n _ = self.gaussian_encoder.encode(y_q_w_0, scales_w_0)\n _ = self.gaussian_encoder.encode(y_q_w_1, scales_w_1)\n bit_stream = self.entropy_coder.flush_encoder()\n\n result = {\n \"bit_stream\": bit_stream,\n }\n return result\n\n def decompress(self, bit_stream, height, width, q_scale):\n curr_q = self.get_curr_q(q_scale)\n\n self.entropy_coder.set_stream(bit_stream)\n device = next(self.parameters()).device\n z_size = get_downsampled_shape(height, width, 64)\n z_hat = self.bit_estimator_z.decode_stream(z_size)\n z_hat = z_hat.to(device)\n\n params = self.hyper_dec(z_hat)\n q_step, scales, means = self.y_prior_fusion(params).chunk(3, 1)\n y_hat = self.decompress_dual_prior(means, scales, q_step, self.y_spatial_prior)\n\n y_hat = y_hat * curr_q\n x_hat = self.refine(self.dec(y_hat)).clamp_(0, 1)\n return {\"x_hat\": x_hat}\n","repo_name":"microsoft/DCVC","sub_path":"DCVC-HEM/src/models/image_model.py","file_name":"image_model.py","file_ext":"py","file_size_in_byte":5718,"program_lang":"python","lang":"en","doc_type":"code","stars":231,"dataset":"github-code","pt":"17"} +{"seq_id":"15260079729","text":"import numpy as np\n\nfrom astropy.io import fits\nfrom astropy.time import Time\nfrom datetime import datetime as dt\nfrom datetime import timedelta as td\nimport plotly.graph_objects as go\n\ndef plot_stix_spec(filename, log=False, tickinterval = 100, time_int = None, idx_int = None, mode = 'Heatmap', binning = 'SDC', gridfac = 0.265506, error=True, zmin = None, zmax = None):\n \"\"\"Plot STIX spectrum converted to XSPEC-compatible format FITS file \"\"\"\n if isinstance(filename, str):\n spec = fits.open(filename)\n try:\n rate=spec[1].data['RATE']\n rate_err = spec[1].data['STAT_ERR']\n spectime=spec[1].data['TIME']\n emin=list(spec[2].data['E_MIN'])\n emax=list(spec[2].data['E_MAX'])\n header = spec[1].header\n cbar_title = \"Background Subtracted
Counts s-1 keV-1 cm-2\" #\"Counts s-1\"\n except KeyError: #it's a raw spectrogram\n rate=spec[2].data['counts']\n rate_err = spec[2].data['counts_err']\n if rate.ndim > 2:\n rate = np.sum(np.sum(rate, axis=2),axis=2)\n rate_err = np.sum(np.sum(rate_err, axis=2),axis=2)\n time_bin_center=spec[2].data['time']\n duration = spec[2].data['timedel']\n header = spec[0].header\n start_time = dt.strptime(header['DATE_BEG'],\"%Y-%m-%dT%H:%M:%S.%f\")\n #print('start_time',start_time)\n factor=1.\n spectime = Time([start_time + td(seconds = bc/factor - d/(2.*factor)) for bc,d in zip(time_bin_center, duration)]).mjd\n\n emin=list(spec[3].data['e_low'])\n emax=list(spec[3].data['e_high'])\n # timezeri = int(Time(start_time).mjd) - spec[0].header['MJDREF']\n\n # header.set('TIMEZERO',timezeri)\n # print('TIMEZERO',timezeri)\n cbar_title = 'Counts'\n #rate=spec[1].data['RATE']\n #rate_err = spec[1].data['STAT_ERR']\n #spectime=spec[1].data['TIME']\n #emin=list(spec[2].data['E_MIN'])\n #emax=list(spec[2].data['E_MAX'])\n #header = spec[1].header\n spec.close()\n tformat = 'mjd'\n else: #assume it's a stixpy.processing.spectrogram.spectrogram.Spectrogram\n spec = filename\n rate = spec.rate\n rate_err = spec.stat_err\n if spec.alpha and 'correction' not in spec.history:\n rate = np.sum(rate,axis=1) #sum over detector\n spectime = spec.t_axis.time_mean\n emin = spec.e_axis.low.tolist()\n emax = spec.e_axis.high.tolist()\n header = spec.primary_header\n tformat = None\n\n tt=Time(spectime, format = tformat)\n if tt.datetime[0].year < 2020 or tt.datetime[0].year > dt.now().year: #find a better way of doing this\n #compare time axis\n tt = Time([Time(header['TIMEZERO']+header['MJDREF'], format='mjd').datetime + td(seconds = t) for t in spectime])\n ylabels=[f\"{n:.0f}-{x:.0f}\" for n,x in zip(emin,emax)]\n plot_rate = rate.T\n cbar_title = \"Background Subtracted
Counts s-1 keV-1 cm-2\" #pretty much true, since counts was divided by eff_ewidth during correction\n plot_time = tt\n\n if log:\n plot_rate = np.log10(plot_rate)\n plot_rate[np.isnan(plot_rate)] = np.nanmin(plot_rate)\n \n #print(plot_rate.shape)\n if time_int: #format HH:MM\n idx_start = tt[0]\n idx_end = tt[-1]\n plot_rate = plot_rate[:,idx_start:idx_end]\n plot_time = plot_time[idx_start:idx_end]\n \n if idx_int:\n idx_start, idx_end = idx_int\n plot_rate = plot_rate[:,idx_start:idx_end]\n plot_time = plot_time[idx_start:idx_end]\n \n fig = go.Figure()\n fig.update_layout(xaxis2=dict(title='Index',tickmode='array',anchor='y',tickvals=np.arange(plot_rate.size/tickinterval)*tickinterval,ticktext=np.arange(1,(plot_rate.size+1)/tickinterval)*tickinterval,tickangle=360,overlaying='x',side='top'))\n if mode.lower() == 'heatmap':\n fig.add_trace(go.Heatmap(x=np.arange(plot_rate.size),z=plot_rate,colorbar_title=cbar_title,xaxis='x2', zauto= False, zmin = zmin, zmax = zmax, opacity = 0))\n fig.add_trace(go.Heatmap(x=plot_time.isot,z=plot_rate,colorbar_title=cbar_title,xaxis='x1', zauto= False, zmin = zmin, zmax = zmax))\n fig.update_yaxes(dict(title='Energy Bin (keV)',tickmode='array',ticktext=ylabels,tickvals=np.arange(len(ylabels))))\n #if zmin:\n # fig.update_layout(coloraxis_cmin = zmin)\n #if zmax:\n # fig.update_layout(coloraxis_cmax = zmax)\n elif mode.lower() == 'scatter':\n \n emin.append(emax[-1])\n if binning == 'SDC':\n bins = [(4,10),(10,15),(15,25),(25,50)] #keV\n bin_idx = [[emin.index(l),emin.index(h)] for l,h in bins]\n elif isinstance(binning, list): #bins are a list of tuples\n bins = binning\n bin_idx = [[emin.index(np.float32(l)),emin.index(np.float32(h))] for l,h in bins]\n else: # no binning\n bins = [[l,h] for l,h in zip(emin,emax)]\n bin_idx = [[emin.index(l),emin.index(h)] for l,h in zip(emin,emax)]\n \n #fig.add_trace(go.Scatter(x=np.arange(plot_rate.size),y=np.sum(plot_rate[bin_idx[0][0]:bin_idx[0][1]],axis=0)*gridfac,xaxis='x2',mode='lines',line_shape='hv')) #uneven time bins mess this up...\n for bi,b in zip(bin_idx,bins):\n error_y = None\n if error:\n error_y=dict(type='data',array=np.sum(rate_err[bi[0]:bi[1]],axis=0)*gridfac)\n fig.add_trace(go.Scatter(x=plot_time.isot,y=np.sum(plot_rate[bi[0]:bi[1]],axis=0)*gridfac,error_y=error_y,xaxis='x1',mode='lines',line_shape='hv',name=f\"{b[0]:.0f}-{b[1]:.0f} keV\")) #plot errors\n fig.update_yaxes(dict(title='Count Rate'))\n\n fig.update_layout(title=f\"Spectrogram {plot_time[0].datetime:%Y-%m-%d %H:%M:%S}\")\n return fig\n \ndef plot_stix_livetime(filename, log=False, tickinterval = 100, time_int = None, idx_int = None):\n \"\"\"Plot STIX spectrum converted to XSPEC-compatible format FITS file \"\"\"\n if isinstance(filename,str):\n spec = fits.open(filename)\n ltime=spec[1].data['LIVETIME']\n spectime=spec[1].data['TIME']\n emin=spec[2].data['E_MIN']\n emax=spec[2].data['E_MAX']\n spec.close()\n tformat = 'mjd'\n else: #assume it's a stixpy.processing.spectrogram.spectrogram.Spectrogram\n spec = filename\n try:\n ltime = spec.eff_livetime_fraction\n except AttributeError:\n ltime = np.mean(np.mean(spec.livetime_fraction,axis=0),axis=0)\n spectime = spec.t_axis.time_mean\n emin = spec.e_axis.low\n emax = spec.e_axis.high\n tformat = None\n \n tt=Time(spectime, format = tformat)\n ylabels=[f\"{n:.0f}-{x:.0f}\" for n,x in zip(emin,emax)]\n plot_rate = ltime.T\n plot_time = tt\n \n if log:\n plot_rate = np.log10(plot_rate)\n plot_rate[np.isnan(plot_rate)] = np.nanmin(plot_rate)\n \n #print(plot_rate.shape)\n if time_int: #format HH:MM\n idx_start = tt[0]\n idx_end = tt[-1]\n plot_rate = plot_rate[idx_start:idx_end]\n plot_time = plot_time[idx_start:idx_end]\n \n if idx_int:\n idx_start, idx_end = idx_int\n plot_rate = plot_rate[idx_start:idx_end]\n plot_time = plot_time[idx_start:idx_end]\n \n fig = go.Figure()\n #fig.add_trace(go.Heatmap(x=np.arange(rate.size),z=rate.T,xaxis='x2',showlegend=False,showscale=False))\n fig.add_trace(go.Scatter(x=plot_time.isot,y=plot_rate,xaxis='x1'))\n fig.update_yaxes(dict(title='Livetime Fraction'))\n fig.update_layout(xaxis2=dict(title='Index',tickmode='array',anchor='y',tickvals=np.arange(plot_rate.size/tickinterval),ticktext=np.arange(1,(plot_rate.size+1)/tickinterval),tickangle=360,overlaying='x',side='top'))\n fig.update_layout(title=f\"Livetime fraction {plot_time[0].datetime:%Y-%m-%d %H:%M:%S}\")\n return fig\n","repo_name":"elastufka/solar_all_purpose","sub_path":"plot_stix_spectrogram.py","file_name":"plot_stix_spectrogram.py","file_ext":"py","file_size_in_byte":8040,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"17"} +{"seq_id":"37378144738","text":"# -*- coding: utf-8 -*-\nimport scrapy\nfrom datetime import datetime\nfrom AutoDealerSpider.spiders.areas import provinceCityDatas\nimport json\n\n\nclass ChanganSpider(scrapy.Spider):\n name = 'changan'\n allowed_domains = ['changan.com.cn']\n start_urls = ['http://changan.com.cn/']\n\n def parse(self, response):\n for p in provinceCityDatas.values():\n if len(p['child']) == 0:\n continue\n for k, v in p['child'].items():\n next_page = 'https://www.changan.com.cn/cache/dealer/dealer_{}_json.js'.format(k)\n yield scrapy.Request(next_page, callback=self.parse_dlr,\n cb_kwargs=dict(province=p['name'], city=v['name']))\n\n def parse_dlr(self, response, province, city):\n dlrs = json.loads(response.text[18:-1])\n for dlr in dlrs:\n # print(dlr['map_position'])\n dealer = {\n '编号': dlr['dealer_code'],\n '省份': province,\n '城市': city,\n '县区': '',\n '品牌': self.name,\n '公司名称': dlr['dealer_name'],\n '联系电话': dlr['contact_phone'],\n '地址': dlr['address'],\n '经度': dlr['map_position'].split(',')[0].strip() if dlr['map_position'] else '',\n '纬度': dlr['map_position'].split(',')[1].strip() if dlr['map_position'] else '',\n '坐标': dlr['map_position'],\n 'crawlTime': datetime.today(),\n }\n yield dealer\n\n","repo_name":"lemonxug/AutoDealerSpider","sub_path":"AutoDealerSpider/spiders/changan.py","file_name":"changan.py","file_ext":"py","file_size_in_byte":1576,"program_lang":"python","lang":"en","doc_type":"code","stars":5,"dataset":"github-code","pt":"17"} +{"seq_id":"10971522843","text":"#!/usr/bin/env python3\n# -*- coding: utf-8 -*-\n\nimport setuptools\n\nwith open(\"README.md\", \"r\", encoding=\"utf-8\") as fh:\n long_description = fh.read()\n\nfrom xing import __version__ as version\n\nsetuptools.setup(\n name=\"xing\",\n version=version,\n author=\"ice.liao\",\n author_email=\"ice.liao@tophant.com\",\n description=\"Yet Another PoC Framework\",\n long_description=long_description,\n long_description_content_type=\"text/markdown\",\n url=\"https://git.tophant.com/Sec/NPoC\",\n packages=setuptools.find_packages(),\n classifiers=[\n \"Programming Language :: Python :: 3\"\n ],\n python_requires='>=3.6',\n entry_points={\n \"console_scripts\": [\n \"xing=xing.main:main\"\n ]\n }\n)","repo_name":"1c3z/ARL-NPoC","sub_path":"setup.py","file_name":"setup.py","file_ext":"py","file_size_in_byte":734,"program_lang":"python","lang":"en","doc_type":"code","stars":103,"dataset":"github-code","pt":"17"} +{"seq_id":"38805897031","text":"import uuid\nfrom api.models.model_vehicle import Vehicle, VehicleSchema\nfrom api.models.model_dealership import Dealership, DealershipSchema\nfrom api.models.model_person import Person, PersonSchema\nfrom api.models.model_sale import Sale, SaleSchema\nfrom api.models.model_account import Account, AccountSchema\n\n\ndef add_vehicle_record(data):\n vehicle_schema = VehicleSchema(exclude=['created'])\n vehicle, error = vehicle_schema.load(data)\n result = vehicle_schema.dump(vehicle.create()).data\n return result\n\n\ndef add_delearship_record(data):\n account_id = str(uuid.uuid4())\n account_data = {\n \"uuid\": account_id,\n \"is_dealer\": True\n }\n data[\"uuid\"] = account_id\n add_account_record(account_data)\n\n dealership_schema = DealershipSchema(exclude=['created'])\n dealership, error = dealership_schema.load(data)\n result = dealership_schema.dump(dealership.create()).data\n return result\n\n\ndef add_person_record(data):\n account_id = str(uuid.uuid4())\n account_data = {\n \"uuid\": account_id,\n \"is_dealer\": False\n }\n data[\"uuid\"] = account_id\n add_account_record(account_data)\n\n person_schema = PersonSchema(exclude=['created'])\n person, error = person_schema.load(data)\n result = person_schema.dump(person.create()).data\n return result\n\n\ndef add_account_record(data):\n account_schema = AccountSchema(exclude=['created'])\n account, error = account_schema.load(data)\n result = account_schema.dump(account.create()).data\n return result\n\n\ndef add_dealer_person(data):\n if data[\"type\"] == \"dealership\":\n return add_delearship_record(data)\n elif data[\"type\"] == \"person\":\n return add_person_record(data)\n\n\ndef add_sale_record(data):\n sale_schema = SaleSchema(exclude=['id', 'created'])\n sale, error = sale_schema.load(data)\n result = sale_schema.dump(sale.create()).data\n return result\n\n\ndef add_sales(data):\n vehicle_data = data[\"vehicle\"]\n buyer_data = data[\"buyer\"]\n seller_data = data[\"seller\"]\n\n vehicle = add_vehicle_record(vehicle_data)\n\n buyer = add_dealer_person(buyer_data)\n\n seller = add_dealer_person(seller_data)\n\n sale_record = {}\n sale_record[\"vin\"] = vehicle_data[\"vin\"]\n sale_record[\"buyer\"] = buyer[\"uuid\"]\n sale_record[\"seller\"] = seller[\"uuid\"]\n sale_record[\"price\"] = data[\"price\"]\n sale_record[\"transaction_date\"] = data[\"transaction_date\"]\n\n return add_sale_record(sale_record)\n\ndef delete_all_records():\n fetched = Sale.query.delete()\n fetched = Account.query.delete()\n fetched = Vehicle.query.delete()\n fetched = Dealership.query.delete()\n fetched = Person.query.delete()\n\n return True\n","repo_name":"animeshmanglik/sales_record","sub_path":"src/api/utils/data.py","file_name":"data.py","file_ext":"py","file_size_in_byte":2689,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"17"} +{"seq_id":"73064740825","text":"import torch.nn as nn\nfrom transformer.Modules import MultiHeadAttention, FeedForwardNetwork\n\n\nclass EncoderLayer(nn.Module):\n def __init__(self, d_model, num_heads, dff, dropout_rate=0.1):\n super(EncoderLayer, self).__init__()\n\n self.mha = MultiHeadAttention(d_model, num_heads)\n self.ffn = FeedForwardNetwork(d_model, dff)\n\n self.layernorm1 = nn.LayerNorm(d_model, eps=1e-6)\n self.layernorm2 = nn.LayerNorm(d_model, eps=1e-6)\n\n self.dropout1 = nn.Dropout(dropout_rate)\n self.dropout2 = nn.Dropout(dropout_rate)\n\n def forward(self, x, mask):\n attn_output, _ = self.mha(x, x, x, mask)\n attn_output = self.dropout1(attn_output)\n out1 = self.layernorm1(x + attn_output)\n\n ffn_output = self.ffn(out1)\n ffn_output = self.dropout2(ffn_output)\n out2 = self.layernorm2(out1 + ffn_output)\n\n return out2\n\n\nclass DecoderLayer(nn.Module):\n def __init__(self, d_model, num_heads, dff, dropout_rate=0.1):\n super(DecoderLayer, self).__init__()\n\n self.mha1 = MultiHeadAttention(d_model, num_heads)\n self.mha2 = MultiHeadAttention(d_model, num_heads)\n\n self.ffn = FeedForwardNetwork(d_model, dff)\n\n self.layernorm1 = nn.LayerNorm(d_model, eps=1e-6)\n self.layernorm2 = nn.LayerNorm(d_model, eps=1e-6)\n self.layernorm3 = nn.LayerNorm(d_model, eps=1e-6)\n\n self.dropout1 = nn.Dropout(dropout_rate)\n self.dropout2 = nn.Dropout(dropout_rate)\n self.dropout3 = nn.Dropout(dropout_rate)\n\n def forward(self, x, enc_output, look_ahead_mask, padding_mask):\n attn1, attn_weights_block1 = self.mha1(x, x, x, look_ahead_mask)\n attn1 = self.dropout1(attn1)\n out1 = self.layernorm1(attn1 + x)\n\n attn2, attn_weights_block2 = self.mha2(out1, enc_output, enc_output, padding_mask)\n attn2 = self.dropout2(attn2)\n out2 = self.layernorm2(attn2 + out1)\n\n ffn_output = self.ffn(out2)\n ffn_output = self.dropout3(ffn_output)\n out3 = self.layernorm3(ffn_output + out2)\n\n return out3, attn_weights_block1, attn_weights_block2\n","repo_name":"YangHan-Morningstar/Transformer-PyTorch","sub_path":"transformer/Layers.py","file_name":"Layers.py","file_ext":"py","file_size_in_byte":2132,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"17"} +{"seq_id":"72235199063","text":"T = int(input())\r\n\r\nfor _ in range(T):\r\n H, W, N = map(int, input().split())\r\n\r\n# 방번호 YYXX (Y : 층 수, X : 번호)\r\n Y = N % H\r\n X = (N // H) + 1\r\n\r\n if Y == 0:\r\n Y = H\r\n X = (N // H)\r\n\r\n answer = Y * 100 + X\r\n print(answer)","repo_name":"aramssong/Baekjoon_Python","sub_path":"백준/Bronze/10250. ACM 호텔/ACM 호텔.py","file_name":"ACM 호텔.py","file_ext":"py","file_size_in_byte":264,"program_lang":"python","lang":"ko","doc_type":"code","stars":0,"dataset":"github-code","pt":"17"} +{"seq_id":"38348228595","text":"#!/usr/bin/python3\nfrom __future__ import print_function\nfrom config import *\nfrom TopLyrics import *\nfrom tkinter import *\nfrom tkinter import ttk\n# import tkinter\n# import _tkinter\n# tkinter._test()\n\n\nclass Interface:\n\tdef __init__(self, master):\n\t\t\n\t\timport json\n\t\tfrom watson_developer_cloud import NaturalLanguageUnderstandingV1\n\t\tfrom watson_developer_cloud.natural_language_understanding_v1 import Features, EntitiesOptions, KeywordsOptions, CategoriesOptions, ConceptsOptions, EmotionOptions\n\t\tservice = NaturalLanguageUnderstandingV1(version='2018-03-16',url='https://gateway.watsonplatform.net/natural-language-understanding/api/v1/analyze?version=2018-03-19',username=IBM_api_username,password=IBM_api_password)\n\n\t\tmaster.title('Flubber')\n\t\tmaster.resizable(False,False)\n\t\tmaster.configure(background= '#ececec')\n\n\t\tstyle = ttk.Style()\n\t\tstyle.configure('WhiteFont.TLabel', font= ('Arial', 18, 'bold') )\n\n\t\ttitle = ttk.Label(master, text= 'Flubber - Your Music Connoisseur')\n\t\ttitle.config(justify= CENTER, font= ('Courier',32,'bold'))\n\t\ttitle.pack(pady= 20, padx= 10)\n\t\t\n\t\tmain_Frame = ttk.Frame(master)\n\t\tmain_Frame.config(height= 400, width= 600)\n\t\tmain_Frame.pack()\n\t\tglobal option\n\t\toption = StringVar(main_Frame)\n\t\tIndia_Radio_Button = ttk.Radiobutton(main_Frame, text= 'India', variable= option, value= 'in')\n\t\tIndia_Radio_Button.grid(row= 0, column= 0, columnspan= 2)\n\t\tUS_Radio_Button = ttk.Radiobutton(main_Frame, text= 'US', variable= option, value= 'us')\n\t\tUS_Radio_Button.grid(row= 1, column= 0, columnspan= 2)\n\n\t\tttk.Label(main_Frame, text= \"Lyrics\", style= 'Header.TLabel').grid(row= 2, column= 1)\n\t\tfetching_Label = ttk.Label(main_Frame, text= \"Fetching...\")\n\t\tfetching_Label.grid(row= 2, column= 0)\n\t\tfetching_Label.grid_forget()\n\t\ttrack_List_Display = ttk.Treeview(main_Frame)\n\n\t\tdef update_Selected_Top_Track(event):\n\t\t\tglobal selected\n\t\t\tselected = track_List_Display.selection()\n\n\t\ttrack_List_Display.bind('<>', update_Selected_Top_Track)\n\t\ttrack_List_Display.grid(row= 3, column=0)\n\t\ttrack_List_Display.heading('#0',text= \"Track List\")\n\t\tlyrics_Display = Text(main_Frame, width= 40, height= 10, wrap= 'word')\n\t\tlyrics_Display.grid(row= 3, column=1)\n\n\t\tdef on_Click_Fetch_Top_Tracks():\n\t\t\tglobal option\n\t\t\tfetching_Label.grid(row= 2, column= 0)\n\t\t\tfetch_Top_10_Button.state([('disabled')])\n\t\t\tglobal tracks_Names_And_Their_Artists\n\t\t\ttracks_Names_And_Their_Artists = get_Top_Tracks_Names_And_Their_Artists(option.get())\n\t\t\tfor track in tracks_Names_And_Their_Artists:\n\t\t\t\ttrack_List_Display.insert('', 'end', track, text= track)\n\t\t\tfetch_Top_10_Button.state([('!disabled')])\n\t\t\tfetching_Label.grid_forget()\n\t\t\tfetch_Top_10_Button.config(text= \"Fetch Top 10 Tracks\")\n\t\t\t\n\n\t\tfetch_Top_10_Button = ttk.Button(main_Frame, text = \"Fetch Top 10 Tracks\", command= on_Click_Fetch_Top_Tracks)\n\n\t\tdef on_Click_Fetch_Track_Lyrics():\n\t\t\tglobal selected\n\t\t\tglobal tracks_Names_And_Their_Artists\n\t\t\tartist_Name=''\n\t\t\tfor track in tracks_Names_And_Their_Artists:\n\t\t\t\tif selected[0] == track:\n\t\t\t\t\t\tprint(track)\n\t\t\t\t\t\tartist_Name = tracks_Names_And_Their_Artists[track]\n\t\t\tlyrics_Display.delete(1.0,END)\n\t\t\tprint('track_Name:',selected)\n\t\t\tprint('artist_Name:',artist_Name)\n\t\t\ttrack_Lyrics = get_Lyrics_From_Track_Name_And_Artist_Name(selected[0], artist_Name)\n\t\t\tprint('Lyrics:\\n',track_Lyrics)\n\t\t\tlyrics_Display.insert( 1.0 , str(track_Lyrics['lyrics']) )\n\t\t\t# lyrics_Display.config(state= 'disabled')\n\n\t\tfetch_Top_10_Button.grid(row= 4, column= 0)\n\t\tfetch_Lyrics_Button = ttk.Button(main_Frame, text= \"Fetch Lyrics of selected Track\", command= on_Click_Fetch_Track_Lyrics)\n\t\tfetch_Lyrics_Button.grid(row= 4, column= 1)\n\t\temotion_IBM_Label = ttk.Label(main_Frame, text= \"Emotions by IBM:\")\n\t\temotion_IBM_Label.grid(row= 5, column= 0)\n\n\t\tdef Watson_Analyze(text):\n\t\t\treturn service.analyze(text= text,features=Features(\temotion=EmotionOptions()) ).get_result()\n\n\n\t\tdef infer_IBM_Watson_Emotions(response):\n\t\t\temotion_Dictionary=response['emotion']['document']['emotion']\n\t\t\tsadness = emotion_Dictionary['sadness']\n\t\t\tsadnessPercentage = str(round(sadness*100,2))+'%'\n\t\t\tjoy = emotion_Dictionary['joy']\n\t\t\tjoyPercentage = str(round(joy*100,2))+'%'\n\t\t\tfear = emotion_Dictionary['fear']\n\t\t\tfearPercentage = str(round(fear*100,2))+'%'\n\t\t\tdisgust = emotion_Dictionary['disgust']\n\t\t\tdisgustPercentage = str(round(disgust*100,2))+'%'\n\t\t\tanger = emotion_Dictionary['anger']\n\t\t\tangerPercentage = str(round(anger*100,2))+'%'\n\t\t\treturn {'sadness': sadnessPercentage,'joy': joyPercentage,'fear': fearPercentage,'disgust': disgustPercentage,'anger': angerPercentage}\n\n\t\tdef on_Click_Watson_Emotion_Button():\n\t\t\tlyrics = lyrics_Display.get('1.0', 'end')\n\t\t\tlyrics\n\t\t\temotions = infer_IBM_Watson_Emotions(Watson_Analyze(lyrics))\n\t\t\tsad_Value_IBM_Label.config(text= emotions['sadness'])\n\t\t\tjoy_Value_IBM_Label.config(text= emotions['joy'])\n\t\t\tfear_Value_IBM_Label.config(text= emotions['fear'])\n\t\t\tdisgust_Value_IBM_Label.config(text= emotions['disgust'])\n\t\t\tanger_Value_IBM_Label.config(text= emotions['anger'])\n\n\t\twatson_Emotion_Button = ttk.Button(main_Frame, text=\"IBM Watson Sentiment Analysis\", command= on_Click_Watson_Emotion_Button)\n\t\twatson_Emotion_Button.grid(row= 5, column= 1)\n\t\tsad_IBM_Label = ttk.Label(main_Frame, text=\"Sad\")\n\t\tsad_IBM_Label.grid(row= 6, column= 0)\n\t\tsad_Value_IBM_Label = ttk.Label(main_Frame)\n\t\tsad_Value_IBM_Label.grid(row= 6, column= 1)\n\t\tjoy_IBM_Label = ttk.Label(main_Frame, text=\"Joy\")\n\t\tjoy_IBM_Label.grid(row= 7, column= 0)\n\t\tjoy_Value_IBM_Label = ttk.Label(main_Frame)\n\t\tjoy_Value_IBM_Label.grid(row= 7, column= 1)\n\t\tfear_IBM_Label = ttk.Label(main_Frame, text=\"Fear\")\n\t\tfear_IBM_Label.grid(row= 8, column= 0)\n\t\tfear_Value_IBM_Label = ttk.Label(main_Frame)\n\t\tfear_Value_IBM_Label.grid(row= 8, column= 1)\n\t\tdisgust_IBM_Label = ttk.Label(main_Frame, text=\"Disgust\")\n\t\tdisgust_IBM_Label.grid(row= 9, column= 0)\n\t\tdisgust_Value_IBM_Label = ttk.Label(main_Frame)\n\t\tdisgust_Value_IBM_Label.grid(row= 9, column= 1)\n\t\tanger_IBM_Label = ttk.Label(main_Frame, text=\"Anger\")\n\t\tanger_IBM_Label.grid(row= 10, column= 0)\n\t\tanger_Value_IBM_Label = ttk.Label(main_Frame)\n\t\tanger_Value_IBM_Label.grid(row= 10, column= 1)\n\t\t\n\n\t\t# coverFile = PhotoImage(file= 'havana.gif')\n\t\t# coverArt = Label(master, image= coverFile)\n\t\t# coverArt.pack()\n\t\t\n\t\t# bio = ttk.Label(master, text= 'Havana', wraplength= 150)\n\t\t# bio.pack()\n\n\ndef main():\t\t\t\n\t\n\troot = Tk()\n\tinterface = Interface(root)\n\troot.mainloop()\n\nif __name__ == \"__main__\": main()\n\n","repo_name":"D3V4N5H/StarBoy","sub_path":"interface.py","file_name":"interface.py","file_ext":"py","file_size_in_byte":6475,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"17"} +{"seq_id":"72916141144","text":"\"\"\"\n1796. 字符串中第二大的数字\n给你一个混合字符串s,请你返回 s中 第二大 的数字,如果不存在第二大的数字,请你返回 -1。\n\n混合字符串 由小写英文字母和数字组成。\n\n\n\n示例 1:\n\n输入:s = \"dfa12321afd\"\n输出:2\n解释:出现在 s 中的数字包括 [1, 2, 3] 。第二大的数字是 2 。\n示例 2:\n\n输入:s = \"abc1111\"\n输出:-1\n解释:出现在 s 中的数字只包含 [1] 。没有第二大的数字。\n\n\n提示:\n\n1 <= s.length <= 500\ns只 `包含小写英文字母和(或)数字。\n\n来源:力扣(LeetCode)\n链接:https://leetcode-cn.com/problems/second-largest-digit-in-a-string\n著作权归领扣网络所有。商业转载请联系官方授权,非商业转载请注明出处。\n\"\"\"\n\n\nclass Solution:\n def secondHighest(self, s: str) -> int:\n s_num = {int(x) for x in s if x.isdigit()}\n nn = sorted(list(s_num))\n return nn[-2] if len(nn) > 1 else -1\n\n\nS = Solution()\ns = \"dfa12321afd\"\nprint(S.secondHighest(s))\n","repo_name":"CLannadZSY/The-Road-To-LeetCode","sub_path":"字符串/1796. 字符串中第二大的数字.py","file_name":"1796. 字符串中第二大的数字.py","file_ext":"py","file_size_in_byte":1037,"program_lang":"python","lang":"zh","doc_type":"code","stars":2,"dataset":"github-code","pt":"17"} +{"seq_id":"6458961937","text":"from collections import Counter\nfrom typing import Any, List, Tuple\n\nfrom ..text.preprocessing import (normalize_whitespace, normalize_wiggles,\n remove_repeating_characters,\n sentence_tokenizer)\n\n\ndef split_youtube_audiences(\n db_batch: List[Any]) -> Tuple[List[Any], List[Any]]:\n \"\"\"Split Youtube audiences from a batch of comments.\n\n Usage:\n >>> db = CommentsSql(\"v2\")\n >>> batch = db.fetch_comments(\"%how to code%\")\n >>> replies, no_replies = split_youtube_audiences(batch)\n >>> print(len(replies), len(no_replies))\n >>> (8, 43)\n\n Returns two Iterables (comments with-replies, comments without-replies).\n Note: The attributes from the batch splits keep the attributes.\n\n \"\"\"\n is_reply = list(filter(lambda i: len(i.cid) > 26, db_batch))\n no_reply = list(filter(lambda i: len(i.cid) == 26, db_batch))\n return (is_reply, no_reply)\n","repo_name":"amoux/david","sub_path":"david/server/utils.py","file_name":"utils.py","file_ext":"py","file_size_in_byte":968,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"17"} +{"seq_id":"13970418325","text":"from contextlib import contextmanager\n\nfrom jinja2 import Environment, PackageLoader\n\nimport logging\n\nimport psycopg2\n\nfrom cubicweb_francearchives import admincnx\n\n\nclass LoggedCursor(object):\n def __init__(self, crs):\n self.crs = crs\n\n def __getattr__(self, attr):\n return getattr(self.crs, attr)\n\n def execute(self, query, args=None):\n logging.debug(\"executing %s (args=%s)\", query, args)\n return self.crs.execute(query, args)\n\n\n@contextmanager\ndef transaction(cnx):\n crs = cnx.cursor()\n try:\n yield LoggedCursor(crs)\n except Exception as exc:\n print(\"err\", exc)\n cnx.rollback()\n raise\n cnx.commit()\n\n\ndef table_exists(dbparams, tablename):\n with transaction(psycopg2.connect(**dbparams)) as crs:\n try:\n query = \"SELECT * FROM {0} LIMIT 1\".format(tablename)\n crs.execute(query)\n except psycopg2.ProgrammingError:\n return False\n except psycopg2.OperationalError:\n return False\n else:\n return True\n\n\ndef load_geonames_tables(appid, dbparams, allcountries_path, altnames_path, table_owner=None):\n \"\"\"Create and populate Geonames table.\n\n :param Connection cnx: connection to CubicWeb database\n :param str allcountries_path: path to allCountries.txt file\n :param str altnames_path: path to alternateNames.txt file\n \"\"\"\n\n env = Environment(loader=PackageLoader(\"cubicweb_frarchives_edition\", \"alignments/templates\"),)\n env.filters[\"sqlstr\"] = lambda x: \"'{}'\".format(x) # noqa\n geonames_template = env.get_template(\"geonames.sql\")\n geonames_sqlcode = geonames_template.render(\n allcountries_path=allcountries_path, altnames_path=altnames_path, owner=table_owner\n )\n with transaction(psycopg2.connect(**dbparams)) as crs:\n crs.execute(geonames_sqlcode)\n with admincnx(appid) as cnx:\n for tablename in (\"geonames\", \"geonames_altnames\"):\n rowcount = cnx.system_sql(\n \"SELECT count(*) FROM {0} LIMIT 1\".format(tablename)\n ).fetchall()[0][0]\n print(\"\\n-> {0} rows created in {1} table\".format(rowcount, tablename))\n\n\ndef load_bano_tables(appid, dbparams, path, table_owner=None):\n \"\"\"Create and populate BANO table.\n\n :param Connection cnx: connection to CubicWeb database\n :param str path: path to data file\n \"\"\"\n env = Environment(loader=PackageLoader(\"cubicweb_frarchives_edition\", \"alignments/templates\"),)\n template = env.get_template(\"bano_whitelisted.sql\")\n with transaction(psycopg2.connect(**dbparams)) as crs:\n crs.execute(template.render(path=path, owner=table_owner))\n with admincnx(appid) as cnx:\n for tablename in (\"bano_whitelisted\",):\n rowcount = cnx.system_sql(\n \"SELECT count(*) FROM {0} LIMIT 1\".format(tablename)\n ).fetchall()[0][0]\n print(\"\\n-> {0} rows created in {1} table\".format(rowcount, tablename))\n","repo_name":"culturecommunication/francearchives-cubicweb-edition","sub_path":"cubicweb_frarchives_edition/alignments/setup.py","file_name":"setup.py","file_ext":"py","file_size_in_byte":2970,"program_lang":"python","lang":"en","doc_type":"code","stars":3,"dataset":"github-code","pt":"17"} +{"seq_id":"13748054851","text":"#!/usr/bin/python\n\nimport sys\nimport urllib\nimport urllib2\nimport time\nimport signal\nimport logging\nimport os\nimport httplib\nimport json\nimport shutil\n\n################################################################################\n# generic boring stuff\n################################################################################\n# no stacktrace on SIGINT\ndef signal_handler(signal, frame):\n print('Terminated with SIGINT (Ctrl+C)') \n sys.exit(0)\nsignal.signal(signal.SIGINT, signal_handler)\n\n# logging setup\nFORMAT = '%(asctime)-15s - %(message)s'\nlogging.basicConfig(stream=sys.stdout, format=FORMAT)\nlogger = logging.getLogger(sys.argv[0])\nlogger.setLevel(logging.INFO)\n################################################################################\n\n\ndryrun = False\nshallow = False\nriakipandport = sys.argv[1] \n\nif (\"-v\" in sys.argv):\n logger.setLevel(logging.DEBUG)\nif (\"-s\" in sys.argv):\n logger.setLevel(logging.ERROR)\nif (\"--dry\" in sys.argv):\n dryrun = True\nif (\"--coward\" in sys.argv):\n shallow = True\n\npathprefix = \"/types/banners_type/buckets/banners/keys\"\nkeydir = \"banners-keys\"\nvaldir = \"banners-values\"\n\nkeylisturl = \"http://\"+riakipandport+pathprefix+\"?keys=true\"\nif dryrun:\n logger.info(\"running in dry mode - won't update anything\")\n \nlogger.info(\"reading urls from \"+keylisturl)\n\nkeylist = urllib.urlopen(keylisturl)\n\nkeysjson = json.loads(keylist.read())\n\nkeys = keysjson['keys']\n\nlogger.info(\"found \"+str(len(keys))+\" keys\")\n\nc = 1\n\nupcount = 0 # count updated urls\nigcount = 0 # count ignored urls (not 200 repo code on get call)\nstart = time.time()\n\nif not os.path.exists(keydir):\n os.mkdir(keydir)\n\nif not os.path.exists(valdir):\n os.mkdir(valdir)\n\nsrc = os.getcwd()\ndst1 = src + '/' + keydir\ndst2 = src + '/' + valdir\n\nfor url in keys:\n # e.g.: url = /fragments/marketCollections/en-gb/tennis/OB_EV6633074/-1\n logger.info(str(c)+\": handling url \"+url)\n\n riakkey = urllib.quote(url, \"\")\n\n fullurl = \"http://\"+riakipandport+pathprefix+\"/\"+riakkey\n puturl = \"/buckets/fillup/keys/\"+riakkey\n logger.debug(str(c)+\": getting \"+fullurl)\n\n # We need urllib2 to set header and collect compressed values\n # If we don't need compressed values, we can proceed with the following call instead:\n response = urllib.urlopen(fullurl)\n logger.info(str(c)+\": response: \"+str(response.code))\n if response.code == 200:\n page = response.read()\n else:\n logger.info(str(c)+\": response code was not 200. Ignoring key \"+riakkey)\n igcount = igcount + 1\n\n response.close()\n\n keyfile = open(str(c)+'_key' , 'w')\n pagefile = open(str(c)+'_res' , 'w')\n keyfile.write(str(url)) \n pagefile.write(str(page))\n\n kfpath = os.getcwd() + '/' + str(c)+ '_key'\n pfpath = os.getcwd() + '/' + str(c)+ '_res'\n \n shutil.move(kfpath, dst1)\n shutil.move(pfpath, dst2)\n\n c = c+1\n if shallow and (upcount > 10):\n break\n\nend = time.time()\n\nduration = end - start\n\n","repo_name":"spliakos/playingWithRIAK","sub_path":"cache_dumper_banners.py","file_name":"cache_dumper_banners.py","file_ext":"py","file_size_in_byte":2949,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"17"} +{"seq_id":"12195440741","text":"\n############################################################################### \n\n#import os.path\nimport os\nimport sys\nimport numpy as np\nimport nibabel as nib\nfrom skimage import measure \n\nEPIpath=os.environ['EPIpath']\nprint(\"EPIpath is: \",EPIpath)\n\nfIn=sys.argv[1]\nprint(\"fIN: \", fIn)\n\nfOut=sys.argv[2]\nprint(\"fOut: \", fOut)\n\nthr=int(sys.argv[3])\nprint(\"thr: \", thr)\n\n\nfileIn=''.join([EPIpath,fIn])\nfileOut=''.join([EPIpath,fOut])\n\nv=nib.load(fileIn) \nv_vol=v.get_fdata()\n# print(v_vol.shape)\nN = int(np.max(v_vol))\n# print(\"N = \",N)\nvol_clean = np.zeros(v_vol.shape)\n\nfor i in range(1,N+1):\n # print(i)\n vi = v_vol == i\n vi = vi.astype(bool).astype(int)\n # print(\"number of non-zero elements\",np.count_nonzero(vi))\n clusters = measure.label(vi,connectivity=2,return_num=True)\n # print(\"number of clusters \",clusters[1])\n for j in range(1,clusters[1]+1):\n vj = np.count_nonzero(clusters[0] == j)\n # print(\"label \",j, \"num elements \",vj)\n if vj > thr:\n # print(\"nonzero elements in vol_clean :\",np.count_nonzero(vol_clean))\n vol_clean[clusters[0] == j] = i\n # print(\"nonzero elements in vol_clean :\",np.count_nonzero(vol_clean))\n\n\n\nv_vol_new = nib.Nifti1Image(v_vol.astype(np.float32),v.affine,v.header)\nnib.save(v_vol_new,fileOut) \nprint(\"get_largest_clusters: saved \",fileOut)\n","repo_name":"IUSCA/IUSM-ConnPipe","sub_path":"src/func/get_largest_clusters.py","file_name":"get_largest_clusters.py","file_ext":"py","file_size_in_byte":1357,"program_lang":"python","lang":"en","doc_type":"code","stars":3,"dataset":"github-code","pt":"17"} +{"seq_id":"14970328981","text":"#!/usr/bin/env python\n\n# Sample program to download image from the given image url\n#\n# Set up:\n# pip install requests\n#\n# Command line inputs: None\n# In file inputs: Give the image url as IMAGE_URL\n# Runtime inputs: None\n\nimport requests\n\nIMAGE_URL = \"http://cinetrooth.in/wp-content/uploads/2015/06/Madonna-Sebastian-Film-Actress-Profile-Biography-and-Upcoming-Movies.jpg\"\nheaders = {\n\t'User-Agent': 'Mozilla/5.0 (Macintosh; Intel Mac OS X 10_10_1) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/39.0.2171.95 Safari/537.36'\n}\n\nresponse = requests.get(IMAGE_URL,headers=headers)\nprint(response.status_code)\n\nif response.status_code == 200:\n f = open(\"Madonna/sample.jpg\", 'wb')\n f.write(response.content)\n f.close()\n","repo_name":"LakshmikanthRaju/PySamples","sub_path":"img-download.py","file_name":"img-download.py","file_ext":"py","file_size_in_byte":726,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"17"} +{"seq_id":"71774649624","text":"\nimport pygame, sys\nfrom pygame.locals import *\n\npygame.init()\nMAIN = pygame.display.set_mode((400,300))\n\nWHITE = (255, 255, 255)\nGREEN = (0,255,0)\nBLUE = (0,0,128)\n\nfontObj = pygame.font.SysFont('arial', 32)\nMAIN.fill(WHITE)\nsurfObj = fontObj.render(str(0),True,GREEN,BLUE)\ntextRect = surfObj.get_rect() # bounding rectangle?\ntextRect.center = (200,150)\n\nCLOCK = pygame.time.Clock();\ncount = 0\ntotal = 0\nFPS = 30\nwhile 1:\n count += 1\n if count == FPS:\n count = 0\n total += 1\n MAIN.fill(WHITE)\n surfObj = fontObj.render(str(total), True, GREEN, BLUE)\n textRect = surfObj.get_rect() # bounding rectangle?\n textRect.center = (200, 150)\n MAIN.blit(surfObj, textRect)\n for event in pygame.event.get():\n if event.type == QUIT:\n pygame.quit()\n sys.exit()\n pygame.display.update()\n CLOCK.tick(FPS)","repo_name":"jgscherber/Practice","sub_path":"Python/WalkThroughs/Invent With Python (pygame)/fonttext.py","file_name":"fonttext.py","file_ext":"py","file_size_in_byte":880,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"17"} +{"seq_id":"43336938405","text":"from django.db import models\nfrom common.utils import get_soup\n\nfrom product_tiki.models.product import *\n\nfrom .accesstrade import AccessTrade\n\nfrom product_tiki.models.ecommerce_channel import Tiki\nfrom product_adayroi.models.ecommerce_channel import Adayroi\n\nimport time\nimport logging\nimport requests\nimport json\n\n\nclass EcommerceChannel(Tiki, Adayroi):\n name = models.CharField(max_length=255)\n platform = models.CharField(max_length=50,\n choices=[('tiki', 'Tiki'),\n ('lazada', 'Lazada'),\n ('adayroi', 'Adayroi')],\n default='tiki')\n access_trade_id = models.ForeignKey(AccessTrade,\n default=1,\n verbose_name=\"Access Trade\",\n on_delete=models.CASCADE)\n\n def __str__(self):\n return self.name\n\n def sync_channel_product(self, top_product=False):\n logging.info(\"Start syncing Product Data in %s\" % self.platform)\n cust_method_name = '%s_get_data' % self.platform if not top_product else '%s_get_top_data' % self.platform\n if hasattr(self, cust_method_name):\n from .product import Product\n\n products_data = getattr(self, cust_method_name)()\n # Update channel id in each product\n sequence = 1 if top_product else 0\n for product in products_data:\n if isinstance(product, list):\n products_data.remove(product)\n continue\n product.update({'channel_id': self,\n 'platform': self.platform,\n 'sequence': sequence})\n # Synchronize products data\n\n Product = Product()\n Product.sync_product_channel(1, products_data)\n\n def update_data_channel(self):\n logging.info(\"Updating product data in %s\" % self.platform)\n cust_method_name = '%s_update_data' % self.platform\n if hasattr(self, cust_method_name):\n from .product import Product\n PO = Product()\n\n products_data = getattr(self, cust_method_name)()\n PO.update_data_product_channel(products_data, update_mongo=True)\n\n def update_data_channel_mongo(self, reverse=False):\n logging.info(\"Updating product data from Mongo in %s\" % self.platform)\n cust_method_name = '%s_update_data_mongo' % self.platform\n if hasattr(self, cust_method_name):\n from .product import Product\n PO = Product()\n\n products_data = getattr(self, cust_method_name)()\n if reverse:\n products_data.reverse()\n PO.update_data_product_channel_mongo(products_data, update_sql=False)\n\n def get_product_comment_channel(self, platform, product_id):\n cust_method_name = '%s_get_comments' % platform\n if hasattr(self, cust_method_name):\n method = getattr(self, cust_method_name)(product_id)\n return method\n return []\n\n def get_product_comment_review_source(self, product_tmpl_name):\n # Hard code\n data = []\n vnreview_endpoint = 'https://vnreview.vn/VnReview/getComment.action'\n headers = {\n 'Content-Type': 'application/json',\n 'Referer': 'https://vnreview.vn/danh-gia-chi-tiet-di-dong/-/view_content/content/2823988/danh-gia-samsung-galaxy-a70-danh-cho-nhung-cu-dan-mang-thuc-thu'\n }\n params = {\n 'articleId': \"2823988\",\n \"skip\": 0,\n \"limit\": 15,\n \"sort\": 1\n }\n\n try:\n vnreview_res = requests.post(url=vnreview_endpoint, data=json.dumps(params), headers=headers)\n if vnreview_res.ok:\n res = vnreview_res.json().get('returnValue')\n comments = json.loads(res)\n for comment in comments:\n data.append({\n 'author': comment.get('userComment'),\n 'avatar': '/static/images/undefined-user.jpg',\n 'title': 'Không tiêu đề',\n 'content': comment.get('body'),\n 'created_at': comment.get('createDate'),\n })\n except Exception as err:\n logging.error(\"Error when getting comments from VnReview\")\n logging.error(err)\n return data\n\n def get_genk_article(self):\n url = \"https://genk.vn/samsung-galaxy-a70-chiec-smartphone-toan-dien-nhat-trong-phan-khuc-trung-cap-20190523164118506.chn\"\n try:\n soup = get_soup(url)\n except Exception as e:\n raise e\n\n articlesTag = soup.find(\"div\", {\"class\": \"w640\"})\n\n content = str(articlesTag)\n return content\n\n def generate_accesstrade_headers(self):\n return {\n 'Authorization': \"Token %s\" % self.access_trade_id.accesstrade_access_key\n }\n","repo_name":"quandxbp/MyLotDep","sub_path":"product/models/ecommerce_channel.py","file_name":"ecommerce_channel.py","file_ext":"py","file_size_in_byte":5057,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"17"} +{"seq_id":"71921010584","text":"class WordDictionary:\n\n def __init__(self):\n self.children = {}\n def addWord(self, word: str) -> None:\n \n n = len(word)\n temp = self.children\n for i in word:\n if i in temp:\n prev = temp\n temp = temp[i][0]\n else:\n temp[i] = [{}, False]\n prev = temp\n temp = temp[i][0]\n prev[i][1] = True\n \n \n def search(self, word: str) -> bool:\n ans = [False]\n self.searchHelper(word, 0, self.children, ans )\n return ans[0]\n def searchHelper(self, word, ind, trie, ans):\n n = len(word)\n if ans[0] == True:\n return \n if ind == n-1:\n if word[ind] == '.':\n for i in trie:\n if trie[i][1]:\n ans[0] = True\n return\n return \n \n elif word[ind] in trie:\n ans[0] = trie[word[ind]][1]\n return\n elif word[ind] == '.':\n for i in trie:\n self.searchHelper(word, ind+1, trie[i][0], ans)\n elif word[ind] in trie:\n self.searchHelper(word,ind+1, trie[word[ind]][0],ans)","repo_name":"abdi-edoc-de/CompetitveProgramming-1","sub_path":"211-design-add-and-search-words-data-structure/211-design-add-and-search-words-data-structure.py","file_name":"211-design-add-and-search-words-data-structure.py","file_ext":"py","file_size_in_byte":1279,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"17"} +{"seq_id":"8404278476","text":"'''\n\n\n给定一个整数数组 A,坡是元组 (i, j),其中 i < j 且 A[i] <= A[j]。这样的坡的宽度为 j - i。\n\n找出 A 中的坡的最大宽度,如果不存在,返回 0 。\n'''\n\n\n'''\n2 <= A.length <= 50000\n 0 <= A[i] <= 50000\n\n'''\n\nclass Solution(object):\n def maxWidthRamp(self, A):\n \"\"\"\n :type A: List[int]\n :rtype: int\n \"\"\"\n if max(A) == A[0]:\n return None\n length = len(A)\n left = 0\n right = length -1\n maxi = 0\n while left < right:\n if A[left] <= A[right]:\n pLength = right - left\n return pLength\n else:\n pLength = 0\n if A[left] <= A[right-1] or A[left+1]>= A[left]:\n right -= 1\n else:\n left += 1\n if pLength > maxi:\n maxi = pLength\n\n return maxi\n\nif __name__ == '__main__':\n A = [9,8,1,0,1,9,4,0,4,1]\n A2 = [2,2,1]\n A3 = [3,4,2,1]\n solute = Solution()\n print(solute.maxWidthRamp(A3))","repo_name":"icelighting/leetcode","sub_path":"数组与字符串/最大宽度坡.py","file_name":"最大宽度坡.py","file_ext":"py","file_size_in_byte":1078,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"17"} +{"seq_id":"18964911816","text":"\"\"\"\n>>> sll = singly_linked_list([1])\n>>> print sll[0]\n1\n>>> sll = singly_linked_list([1, 2, 3])\n>>> print sll[0]\n1\n>>> print sll[1]\n2\n>>> print sll[2]\n3\n>>> sll = singly_linked_list([\"A\", \"b\", \"C\"])\n>>> sll[0]\n'A'\n>>> sll[-1]\n'C'\n>>> sll[-2]\n'b'\n>>> sll[-3]\n'A'\n>>> sll[-4]\nTraceback (most recent call last):\n ...\nIndexError: list index out of range\n>>> sll[10]\nTraceback (most recent call last):\n ...\nIndexError: list index out of range\n\"\"\"\n\nimport sys\nsys.path.insert(0, '../singly_linked_list_delete')\n\nfrom solution import singly_linked_list\n\ndef sll__getitem__(self, k):\n if k >= 0:\n node = self\n while node != None and k > 0:\n node = node.next\n k -= 1\n if k > 0:\n raise IndexError(\"list index out of range\")\n return node.data\n else:\n length = 0\n node = self\n while node != None:\n node = node.next\n length += 1\n if k * -1 > length:\n raise IndexError(\"list index out of range\")\n return self[length + k]\n \n\nsingly_linked_list.__getitem__ = sll__getitem__\n\nif __name__ == '__main__':\n import doctest\n if doctest.testmod().failed > 0:\n import sys\n sys.exit(1)\n","repo_name":"rinaldifonseca/dpcode","sub_path":"python/singly_linked_list_getindex/solution.py","file_name":"solution.py","file_ext":"py","file_size_in_byte":1132,"program_lang":"python","lang":"en","doc_type":"code","dataset":"github-code","pt":"17"} +{"seq_id":"20041156608","text":"'''\n@author Tian Shi\nPlease contact tshi@vt.edu\n'''\nimport numpy as np\nimport json\nfrom glob import glob\n\n\ndef evaluation(input_dir):\n '''\n Evaluation Metrics\n '''\n files = glob('{}/*'.format(input_dir))\n for file_ in files:\n print('Validate file: {}'.format(file_))\n fp = open(file_, 'r')\n data = []\n for line in fp:\n try:\n itm = json.loads(line)\n except:\n continue\n data.append(itm)\n\n aa = aat = bb = bbt = 0\n for itm in data:\n for wd in itm['pred']:\n if wd in itm['gold']:\n aa += 1\n aat += 1\n for wd in itm['gold']:\n if wd in itm['pred']:\n bb += 1\n bbt += 1\n precision = aa/aat\n recall = bb/bbt\n fscore = 2.0*precision*recall/(precision+recall)\n print('micro precision={}, recall={}, f-score={}'.format(\n precision, recall, fscore))\n\n aa = aat = 0\n for itm in data:\n if itm['pred'] == itm['gold']:\n aa += 1\n aat += 1\n accuracy = aa/aat\n print('Accuracy={}'.format(accuracy))\n\n precision = []\n recall = []\n fscore = []\n for itm in data:\n aa = aat = bb = bbt = 0\n for wd in itm['pred']:\n if wd in itm['gold']:\n aa += 1\n aat += 1\n for wd in itm['gold']:\n if wd in itm['pred']:\n bb += 1\n bbt += 1\n pp = aa/aat + 1e-10\n rr = bb/bbt + 1e-10\n precision.append(pp)\n recall.append(rr)\n fscore.append(2.0*pp*rr/(pp+rr))\n accuracy = aa/aat\n print('macro precision={}, recall={}, f-score={}'.format(\n np.mean(precision), np.mean(recall), np.mean(fscore)))\n\n fp.close()\n","repo_name":"tshi04/AspDecSSCL","sub_path":"LeafNATS/eval_scripts/eval_kgqa.py","file_name":"eval_kgqa.py","file_ext":"py","file_size_in_byte":1950,"program_lang":"python","lang":"en","doc_type":"code","stars":33,"dataset":"github-code","pt":"17"} +{"seq_id":"19283391503","text":"#!/usr/bin/env python\n# coding: utf-8\n\n# # CS 514 Applied AI\n# \n# ## ASHRAE - Great Energy Prediction 3\n# \n# https://www.kaggle.com/c/ashrae-energy-prediction/overview\n\n# # 1. Importing all the Libraries\n\n# In[1]:\n\n\n#Ignoring all System warnings\nimport warnings\nwarnings.filterwarnings('ignore')\n\n#Importing Garbage Collector and the system call to os\nimport gc\nimport os\n\n#Importing all the Scientific Libraries\nimport pandas as pd\nimport numpy as np\nimport scipy as sc\n\n#Importing all the plotting libraries\nimport matplotlib.pyplot as plt\nget_ipython().run_line_magic('matplotlib', 'inline')\nimport seaborn as sns\n\nfrom sklearn.metrics import mean_squared_error\nfrom sklearn.preprocessing import LabelEncoder\n\n\n# In[2]:\n\n\nimport random\nrandom.seed(0)\n\n\n# # 2. Reading the Data\n\n# In[3]:\n\n\nos.getcwd()\n\n\n# In[4]:\n\n\nprint(os.listdir())\n\n\n# In[5]:\n\n\ntrain_df = pd.read_csv(\"train.csv\")\n\nbuilding_df = pd.read_csv(\"building_metadata.csv\")\n\nweather_train_df = pd.read_csv(\"weather_train.csv\")\n\nweather_test_df = pd.read_csv(\"weather_test.csv\")\n\ntest_df = pd.read_csv(\"test.csv\")\n\n\n# ## Know more about the data\n\n# Applying df.describe() functions to every dataframe to know about the stats of the data\n\n# In[6]:\n\n\nprint(\"Describing the Train data\\n\",train_df.describe())\nprint(\"\\n\")\nprint(\"Describing the building data\\n\",building_df.describe())\nprint(\"\\n\")\nprint(\"Describing the weather train data\\n\",weather_train_df.describe())\nprint(\"\\n\")\nprint(\"Describing the weather test data\\n\",weather_test_df.describe())\nprint(\"\\n\")\nprint(\"Describing the Test data\\n\",test_df.describe())\nprint(\"\\n\")\n\n\n# Applying df.shape() function to every df to know the number of rows and columns in the df.\n# \n# \n# Here the result will be (x,y) where x is the number of row and y is the number of column\n\n# In[7]:\n\n\nprint(\"Shape of Train data: \",train_df.shape)\nprint(\"Shape of building data: \",building_df.shape)\nprint(\"Shape of weather train data: \",weather_train_df.shape)\nprint(\"Shape of weather test data: \",weather_test_df.shape)\nprint(\"Shape of Test data: \",test_df.shape)\n\n\n# Applying df.head() to display rows of the dataframe\n\n# In[8]:\n\n\ntrain_df.head()\n\n\n# In[9]:\n\n\nbuilding_df.head()\n\n\n# Here we see primary_use is a categorical variable which can be encoded using LabelEncoder().\n# \n# Below we will look at all the unique categories of the primary_use column in the building_df.\n\n# In[10]:\n\n\nbuilding_df['primary_use'].unique().tolist()\n\n\n# Label Encoding refers to converting the labels into numeric form so as to convert it into the machine-readable form\n# \n# Example :\n#
\n# Suppose we have a column Height in some dataset.\n# \n# Height = [\"small\",\"medium\",\"Tall\"]\n# \n# Then after encoding the Height will become as: Height = [0,1,2]\n\n# In[11]:\n\n\nle = LabelEncoder()\nbuilding_df['primary_use'] = le.fit_transform(building_df['primary_use'])\n\n\n# In[12]:\n\n\nbuilding_df.head()\n\n\n# In[13]:\n\n\nweather_train_df.head()\n\n\n# In[14]:\n\n\nweather_test_df.head()\n\n\n# In[15]:\n\n\ntest_df.head()\n\n\n# # 3. Reducing the Memory Usage\n\n# Some features take up more memory space than they should, and since there is too much data, this is critical step to reduce the memory use by the data.\n\n# In[16]:\n\n\n# we can count the actual memory usage using the following command\nprint(\"Memory used by train_df:\")\ntrain_df.info(memory_usage='deep')\nprint(\"\\n Memory used by building_df:\")\nbuilding_df.info(memory_usage='deep')\nprint(\"\\n Memory used by weather_train_df:\")\nweather_train_df.info(memory_usage='deep')\nprint(\"\\n Memory used by weather_test_df:\")\nweather_test_df.info(memory_usage='deep')\nprint(\"\\n Memory used by test_df:\")\ntest_df.info(memory_usage='deep')\n\n\n# In[17]:\n\n\n# we can check how much space each column is actually taking\n# the numbers are in bytes, not kilobytes\ntrain_df.memory_usage('deep')\n\n\n# Below is the Table showing memory usage by different datatypes\n\n# ![](D:\\KaggleProjects\\ASHRAE\\ashrae-energy-prediction\\table.png)\n\n# ![memory usage](table.png)\n\n# ## Function to define reduce memory usage\n\n# In[18]:\n\n\ndef reduce_mem_usage(df):\n start_mem_usage = df.memory_usage().sum() / 1024**2 #Convert bytes to megabytes(MB)\n print(\"Memories usage of the dataframe is :\",start_mem_usage,\"MB\")\n list_na = [] ## Keeps track of columns that have missing values filled in. \n for col in df.columns:\n if df[col].dtype != object:#Excluding string\n # make variables for Int, max and min\n IsInt = False\n mx = df[col].max()\n mn = df[col].min()\n # Integer does not support NA, therefore, NA needs to be filled\n if not np.isfinite(df[col]).all(): \n list_na.append(col)\n df[col].fillna(mn-1,inplace=True) \n \n # test if column can be converted to an integer\n asint = df[col].fillna(0).astype(np.int64)\n result = (df[col] - asint)\n result = result.sum()\n if result > -0.01 and result < 0.01:\n IsInt = True\n \n # Make Integer/unsigned Integer datatypes\n if IsInt:\n if mn >= 0:\n if mx < 255:\n df[col] = df[col].astype(np.uint8)\n elif mx < 65535:\n df[col] = df[col].astype(np.uint16)\n elif mx < 4294967295:\n df[col] = df[col].astype(np.uint32)\n else:\n df[col] = df[col].astype(np.uint64)\n else:\n if mn > np.iinfo(np.int8).min and mx < np.iinfo(np.int8).max:\n df[col] = df[col].astype(np.int8)\n elif mn > np.iinfo(np.int16).min and mx < np.iinfo(np.int16).max:\n df[col] = df[col].astype(np.int16)\n elif mn > np.iinfo(np.int32).min and mx < np.iinfo(np.int32).max:\n df[col] = df[col].astype(np.int32)\n elif mn > np.iinfo(np.int64).min and mx < np.iinfo(np.int64).max:\n df[col] = df[col].astype(np.int64) \n \n # Make float datatypes 32 bit\n else:\n df[col] = df[col].astype(np.float32)\n \n # Print new column type\n print(\"dtype after: \",df[col].dtype)\n print(\"******************************\")\n \n # Print final result\n print(\"___MEMORY USAGE AFTER COMPLETION:___\")\n mem_usg = df.memory_usage().sum() / 1024**2 \n print(\"Memory usage is: \",mem_usg,\" MB\")\n print(\"This is \",100*mem_usg/start_mem_usage,\"% of the initial size\")\n return df, list_na\n \n\n\n# In[19]:\n\n\ntrain_df, NAlist = reduce_mem_usage(train_df)\nprint(\"_________________\")\nprint(\"\")\nprint(\"Warning: the following columns have missing values filled with 'df['column_name'].min() -1': \")\nprint(\"_________________\")\nprint(\"\")\nprint(NAlist)\n\n\n# In[20]:\n\n\ntest_df, NAlist = reduce_mem_usage(test_df)\nprint(\"_________________\")\nprint(\"\")\nprint(\"Warning: the following columns have missing values filled with 'df['column_name'].min() -1': \")\nprint(\"_________________\")\nprint(\"\")\nprint(NAlist)\n\n\n# In[21]:\n\n\nbuilding_df, NAlist = reduce_mem_usage(building_df)\nprint(\"_________________\")\nprint(\"\")\nprint(\"Warning: the following columns have missing values filled with 'df['column_name'].min() -1': \")\nprint(\"_________________\")\nprint(\"\")\nprint(NAlist)\n\n\n# In[22]:\n\n\nbuilding_df.isnull().any().sum()\n\n\n# In[23]:\n\n\nweather_train_df, NAlist = reduce_mem_usage(weather_train_df)\nprint(\"_________________\")\nprint(\"\")\nprint(\"Warning: the following columns have missing values filled with 'df['column_name'].min() -1': \")\nprint(\"_________________\")\nprint(\"\")\nprint(NAlist)\n\n\n# In[24]:\n\n\nweather_train_df.isnull().any().sum()\n\n\n# In[25]:\n\n\nweather_test_df, NAlist = reduce_mem_usage(weather_test_df)\nprint(\"_________________\")\nprint(\"\")\nprint(\"Warning: the following columns have missing values filled with 'df['column_name'].min() -1': \")\nprint(\"_________________\")\nprint(\"\")\nprint(NAlist)\n\n\n# In[26]:\n\n\nweather_test_df.isnull().any().sum()\n\n\n# # 4. Merging the data \n\n# In[27]:\n\n\ndef merge_data(train,building,weather,test=False):\n \"\"\"Merging building and weather data with train and test data\"\"\"\n train = train.merge(building_df,on=\"building_id\",how =\"left\")\n train = train.merge(weather_train_df,on=[\"site_id\",\"timestamp\"],how=\"left\")\n \n \n train['timestamp'] = pd.to_datetime(train['timestamp'],format=\"%Y-%m-%d %H:%M:%S\")\n train['square_feet'] = np.log1p(train['square_feet'])#np.log1p is used so that smallest value aren't ignored\n \n if not test:\n train.sort_values('timestamp',inplace=True)\n train.reset_index(drop=True,inplace=True)\n \n \n gc.collect()\n \n holidays = [\"2016-01-01\", \"2016-01-18\", \"2016-02-15\", \"2016-05-30\", \"2016-07-04\",\n \"2016-09-05\", \"2016-10-10\", \"2016-11-11\", \"2016-11-24\", \"2016-12-26\",\n \"2017-01-01\", \"2017-01-16\", \"2017-02-20\", \"2017-05-29\", \"2017-07-04\",\n \"2017-09-04\", \"2017-10-09\", \"2017-11-10\", \"2017-11-23\", \"2017-12-25\",\n \"2018-01-01\", \"2018-01-15\", \"2018-02-19\", \"2018-05-28\", \"2018-07-04\",\n \"2018-09-03\", \"2018-10-08\", \"2018-11-12\", \"2018-11-22\", \"2018-12-25\",\n \"2019-01-01\"]\n \n train[\"hour\"] = train.timestamp.dt.hour\n train[\"weekday\"] = train.timestamp.dt.weekday\n train[\"is_holiday\"] = (train.timestamp.dt.date.astype(\"str\").isin(holidays)).astype(int)\n \n train.drop(\"timestamp\",axis=1,inplace=True)\n \n if test:\n row_ids = train.row_id\n train.drop(\"row_id\", axis=1, inplace=True)\n return train, row_ids\n \n else:\n y = np.log1p(train.meter_reading)\n train.drop(\"meter_reading\", axis=1, inplace=True)\n return train, y\n \n\n\n# In[28]:\n\n\ntrain_X,train_y = merge_data(train_df,building_df,weather_train_df)\n#gc.collect()\n\n\n# In[29]:\n\n\ntest_x,row_ids = merge_data(test_df,building_df,weather_test_df,test=True)\n\n\n# In[30]:\n\n\ngc.collect()\n\n\n# In[31]:\n\n\nnp.isnan(train_X).sum()\n\n\n# In[32]:\n\n\ntrain_X[\"air_temperature\"].fillna(0,inplace=True)\n\n\n# In[33]:\n\n\ntrain_X[\"cloud_coverage\"].fillna(0,inplace=True)\n\n\n# In[34]:\n\n\ntrain_X[\"dew_temperature\"].fillna(0,inplace=True)\n\n\n# In[35]:\n\n\ntrain_X[\"precip_depth_1_hr\"].fillna(0,inplace=True)\n\n\n# In[36]:\n\n\ntrain_X[\"sea_level_pressure\"].fillna(0,inplace=True)\n\n\n# In[37]:\n\n\ntrain_X[\"wind_direction\"].fillna(0,inplace=True)\n\n\n# In[38]:\n\n\ntrain_X[\"wind_speed\"].fillna(0,inplace=True)\n\n\n# In[39]:\n\n\ntrain_X.isnull().any().sum()\n\n\n# In[40]:\n\n\ntest_x.shape\n\n\n# In[41]:\n\n\ntest_x.isnull().any().sum()\n\n\n# In[42]:\n\n\nnp.isnan(test_x).sum()\n\n\n# In[43]:\n\n\ntest_x[\"air_temperature\"].fillna(0,inplace=True)\n\n\n# In[44]:\n\n\ntest_x[\"cloud_coverage\"].fillna(0,inplace=True)\n\n\n# In[45]:\n\n\ntest_x[\"dew_temperature\"].fillna(0,inplace=True)\n\n\n# In[46]:\n\n\ntest_x[\"precip_depth_1_hr\"].fillna(0,inplace=True)\n\n\n# In[47]:\n\n\ntest_x[\"sea_level_pressure\"].fillna(0,inplace=True)\n\n\n# In[48]:\n\n\ntest_x[\"wind_direction\"].fillna(0,inplace=True)\n\n\n# In[49]:\n\n\ntest_x[\"wind_speed\"].fillna(0,inplace=True)\n\n\n# In[50]:\n\n\ntest_x.isnull().sum()\n\n\n# # 5. Train and Test Split\n\n# In[51]:\n\n\nfrom sklearn.model_selection import train_test_split\nfrom sklearn.metrics import classification_report,confusion_matrix,accuracy_score\nfrom sklearn.linear_model import LinearRegression\nfrom sklearn.tree import DecisionTreeRegressor\n\n\n# In[52]:\n\n\nfrom sklearn.model_selection import train_test_split\n\n\n# Splitting the data into train and validation set to know which model will perform better\n\n# In[53]:\n\n\nX_train, X_valid, y_train, y_valid = train_test_split(train_X,train_y,test_size=0.50,shuffle = True)\n\n\n# # Linear Regression Model\n\n# In[54]:\n\n\nlr = LinearRegression()\n\nlr.fit(X_train,y_train)\npred_reg = lr.predict(X_valid)\n\n\n# In[55]:\n\n\npred_reg=pred_reg.reshape(-1,1)\n\n\n# In[56]:\n\n\npred_reg\n\n\n# In[57]:\n\n\ny_valid = y_valid.values.reshape(-1,1)\n\n\n# In[58]:\n\n\ny_valid\n\n\n# In[59]:\n\n\npred_reg.shape\n\n\n# In[60]:\n\n\ny_valid.shape\n\n\n# In[ ]:\n\n\n\n\n\n# # Function which computes root mean squared log error\n\n# In[62]:\n\n\ndef root_mean_squared_log_error(real, predicted):\n sum=0.0\n for x in range(len(predicted)):\n if predicted[x]<0 or real[x]<0: # check for negative values\n continue\n p = np.log1p(predicted[x]+1)\n r = np.log1p(real[x]+1)\n sum = sum + (p - r)**2\n return (sum/len(predicted))**0.5\n\n\n# In[63]:\n\n\nroot_mean_squared_log_error(y_valid,pred_reg)\n\n\n# # Calculating mean square error\n\n# In[64]:\n\n\nfrom math import sqrt\nrms = sqrt(mean_squared_error(y_valid,pred_reg))\n\n\n# In[65]:\n\n\nprint(rms)\n\n\n# In[ ]:\n\n\n\n\n\n# # Decision Tree Regressor Model\n\n# In[66]:\n\n\ndt = DecisionTreeRegressor(criterion=\"mse\",min_samples_leaf=5)\ndt.fit(X_train,y_train)\npred_dt = dt.predict(X_valid)\n\n\n# In[67]:\n\n\npred_dt=pred_dt.reshape(-1,1)\n\n\n# In[68]:\n\n\nrms_d = sqrt(mean_squared_error(y_valid,pred_dt))\nprint(rms_d)\n\n\n# In[69]:\n\n\nroot_mean_squared_log_error(y_valid,pred_dt)\n\n\n# In[ ]:\n\n\n\n\n\n# # SGDRegressor Model\n\n# In[70]:\n\n\nfrom sklearn import linear_model\n\n\n# In[71]:\n\n\nsgd_reg = linear_model.SGDRegressor(max_iter=1000,tol=1e-3)\nsgd_reg.fit(X_train,y_train)\npred_sgd = sgd_reg.predict(X_valid)\n\n\n# In[72]:\n\n\npred_sgd = pred_sgd.reshape(-1,1)\n\n\n# In[73]:\n\n\nrms_sgd = sqrt(mean_squared_error(y_valid,pred_sgd))\nprint(rms_sgd)\n\n\n# In[74]:\n\n\nroot_mean_squared_log_error(y_valid,pred_sgd)\n\n\n# # Deleting all the unused variable to clear the memory \n\n# In[75]:\n\n\ndel train_df,building_df,weather_train_df,weather_test_df,test_df\n\n\n# In[76]:\n\n\ndel lr\n\n\n# In[77]:\n\n\ndel dt\n\n\n# In[78]:\n\n\ndel X_train, X_valid, y_train, y_valid \n\n\n# In[79]:\n\n\ndel sgd_reg \n\n\n# In[80]:\n\n\ngc.collect()\n\n\n# # 6. Model Preparation\n\n# Finally Selecting the Decision Tree Regressor since it has low root mean square error\n\n# In[81]:\n\n\nregression_model = DecisionTreeRegressor(criterion=\"mse\",min_samples_leaf=5)\n\n\n# In[82]:\n\n\nregression_model.fit(train_X,train_y)\n\n\n# In[83]:\n\n\npredicted = regression_model.predict(test_x)\n\n\n# Making a DataFrame of the predicted results and finally saving it to ashrae_submit.csv\n\n# In[87]:\n\n\nsubmission_df = pd.DataFrame(zip(row_ids,predicted),columns = ['row_id','meter_reading'])\n\n\n# In[90]:\n\n\nsubmission_df.shape\n\n\n# In[91]:\n\n\nsubmission_df.to_csv(\"ashrae_submit.csv\", index=False)\n\n\n# In[ ]:\n\n\n\n\n","repo_name":"gautamojha1997/Kaggle-ASHRAE-Project","sub_path":"CS 514 Applied AI Project 5.py","file_name":"CS 514 Applied AI Project 5.py","file_ext":"py","file_size_in_byte":14345,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"17"} +{"seq_id":"20751389151","text":"from turtle import Turtle\n\nclass ScoreBoard(Turtle):\n def __init__(self):\n super().__init__()\n self.score = 0\n with open(\"data.txt\", \"r\") as file:\n self.highScore = int(file.read())\n self.penup()\n self.writeScore()\n\n def writeScore(self):\n self.color(\"white\")\n self.hideturtle()\n self.goto(0, 270)\n self.write(\"Score: 0\", False, align=\"center\", font=(\"Arial\",15,\"italic\"))\n\n\n def updateScore(self):\n self.clear()\n self.score += 1\n self.write(f\"Score: {self.score} High Score: {self.highScore}\", False, align=\"center\", font=(\"Arial\",15,\"italic\"))\n\n def reset(self):\n if self.score > self.highScore:\n self.highScore = self.score\n with open(\"data.txt\", \"w\") as file:\n file.write(str(self.highScore))\n self.score = 0\n self.updateScore()\n\n # def printEndGame(self):\n # self.clear()\n # self.goto(0,0)\n # self.write(\"Game Over\", False, align=\"center\", font=(\"Arial\", 30, \"italic\"))\n\n","repo_name":"bojanbojovic/projects","sub_path":"Snake/scoreboard.py","file_name":"scoreboard.py","file_ext":"py","file_size_in_byte":1057,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"17"} +{"seq_id":"17740047036","text":"# -*- coding: utf-8 -*-\n# @Time : 2021/7/4 11:10\n# @File : 5802. 统计好数字的数目.py\nfrom leetcode import *\n\n\nclass Solution:\n def countGoodNumbers(self, n: int) -> int:\n def superPow(a: int, b: List[int],base) -> int:\n if not b:\n return 1\n b = list(map(int,b))\n last = b.pop()\n\n part1 = (a ** last) % base\n part2 = (superPow(a, b,base) ** 10) % base\n\n return (part1 * part2) % base\n\n def quickPow(a, b, c):\n ans = 1\n while b > 0:\n if b % 2 == 1:\n ans = ans * a % c\n a = a * a % c\n b = b / 2\n return ans % c\n\n\n # 2 3 5 7\n tmp = math.ceil(n / 2)\n # return (quickPow(5, tmp, 1000000007) * quickPow(4, (n - tmp), 1000000007)) % 1000000007\n return (superPow(5, list(str(tmp)), 1000000007) * superPow(4, list(str(n - tmp)), 1000000007)) % 1000000007\n\n\nif __name__ == '__main__':\n for i in range(10):\n print(Solution().countGoodNumbers(i))\n","repo_name":"SSZX866/leetcode","sub_path":"数学/2.middle/1922. 统计好数字的数目.py","file_name":"1922. 统计好数字的数目.py","file_ext":"py","file_size_in_byte":1081,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"17"} +{"seq_id":"42533150265","text":"import numpy as np\n\ndef DectoHHMM(ut,ss=False,ms=False,Split=False):\n\t'''\n\tConvert decimal time in hours to separate hours, minutes etc.\n\t\n\tInputs:\n\t\tut:\tfloating point array of times.\n\t\tss:\tIf True, seconds are included in the output.\n\t\tms: If True, milliseconds are also included in the output.\n\t\tSplit: If True, a tuple of (hours,minutes,seconds,milliseconds)\n\t\t\t is returned, otherwise an integer will be returned with \n\t\t\t the format HHMMSSMS\n\t\t\t \n\tReturns:\n\t\tTuple of hours,minutes,seconds,milliseconds, or an integer of \n\t\tthe forma HHMMSSMS.\n\t'''\n\thh=np.int32(np.floor(ut))\n\tmm=np.int32(np.floor((ut-hh)*60.0))\n\ts=np.int32(np.floor(((ut-hh)*60-mm)*60))\n\tm=np.int32(np.floor((((ut-hh)*60-mm)*60-s)*1000))\n\t\n\tif Split == True:\n\t\tif ms:\n\t\t\treturn (hh,mm,s,m)\n\t\telif ss:\n\t\t\treturn (hh,mm,s)\n\t\telse:\n\t\t\treturn (hh,mm)\n\telse:\n\t\tout = (hh*100+mm)\n\t\tif ms:\n\t\t\tout = (out*100+s)*1000+m\n\t\telif ss:\n\t\t\tout = out*100+s\n\t\t\n\t\treturn out\n\t\t\t\ndef HHMMtoDec(ut,ss=False,ms=False):\n\t'''\n\tThis function converts input integer times with the format HHMM \n\t(or HHMMSS, HHMMSSMS) to a floating point time HH.HHH\n\t\n\tInputs:\n\t\tut: input time integer, HHMM.\n\t\tss: If True, then input is treated as having format HHMMSS.\n\t\tms: If True, input is treated as having format HHMMSSMS.\n\t\t\n\tOutput:\n\t\tFloating point time, returns array if input is an array.\n\t'''\n\tt = np.copy(ut)\n\tm = 0\n\ts = 0\n\tif ms == True:\n\t\tm = ut % 1000\n\t\tut = np.int32(ut//1000)\n\tif ss == True:\n\t\ts = ut % 100\n\t\tut = np.int32(ut//100)\t\t\n\thh = np.int32(ut//100)\n\tmm = ut % 100\n\n\tout=np.float32(hh)+np.float32(mm)/60+np.float32(s)/3600+np.float32(m)/3600000\n\treturn out\n","repo_name":"tracykimani/simple-calculator-","sub_path":"untitled/venv/Lib/site-packages/DateTimeTools/hhmm.py","file_name":"hhmm.py","file_ext":"py","file_size_in_byte":1622,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"17"} +{"seq_id":"74162858264","text":"__title__ = \"main generator for capacitor tht model generators\"\n__author__ = \"scripts: maurice and hyOzd; models: see cq_model files\"\n__Comment__ = '''This generator loads cadquery model scripts and generates step/wrl files for the official kicad library.'''\n\n___ver___ = \"1.2 03/12/2017\"\n\n\nsave_memory = True #reducing memory consuming for all generation params\ncheck_Model = True\nstop_on_first_error = True\nclose_erronous = False\ncheck_log_file = 'check-log.md'\nglobal_3dpath = '../_3Dmodels/'\nstop_after_coloring = False\n\nmesh_deviation = 0.03\n\nlib_suffix = \"_THT\"\n\nimport sys, os\nimport traceback\n\nimport datetime\nfrom datetime import datetime\nfrom math import sqrt\nfrom collections import namedtuple\n\nsys.path.append(\"../_tools\")\nimport exportPartToVRML as expVRML\nimport shaderColors\nimport add_license as L\n\nimport re, fnmatch\nimport yaml\n\nsave_memory = True #reducing memory consuming for all generation params\ncheck_Model = True\ncheck_log_file = 'check-log.md'\n\nif FreeCAD.GuiUp:\n from PySide import QtCore, QtGui\n\n#import FreeCADGui as Gui\n\ntry:\n # Gui.SendMsgToActiveView(\"Run\")\n# from Gui.Command import *\n Gui.activateWorkbench(\"CadQueryWorkbench\")\n import cadquery as cq\n from Helpers import show\n # CadQuery Gui\nexcept Exception as e: # catch *all* exceptions\n print(e)\n msg = \"missing CadQuery 0.3.0 or later Module!\\r\\n\\r\\n\"\n msg += \"https://github.com/jmwright/cadquery-freecad-module/wiki\\n\"\n if QtGui is not None:\n reply = QtGui.QMessageBox.information(None,\"Info ...\",msg)\n\n#######################################################################\n\n#from Gui.Command import *\n\n# Import cad_tools\n#sys.path.append(\"../_tools\")\nfrom cqToolsExceptions import *\nimport cq_cad_tools\n# Reload tools\nfrom cq_cad_tools import reload_lib\nreload_lib(cq_cad_tools)\n# Explicitly load all needed functions\nfrom cq_cad_tools import multiFuseObjs_wColors, GetListOfObjects, restore_Main_Tools, \\\n exportSTEP, checkRequirements, saveFCdoc, z_RotateObject,\\\n runGeometryCheck\n\ncheckRequirements(cq)\n\n#import FreeCAD, Draft, FreeCADGui\nimport ImportGui\n\n\ndef export_one_part(module, params, configuration, log):\n series_definition = module.series_params\n\n if module.LICENCE_Info.LIST_license[0]==\"\":\n LIST_license=L.LIST_int_license\n LIST_license.append(\"\")\n else:\n LIST_license=module.LICENCE_Info.LIST_license\n\n LIST_license[0] = \"Copyright (C) \"+datetime.now().strftime(\"%Y\")+\", \" + module.LICENCE_Info.STR_licAuthor\n\n lib_name = configuration['lib_name_format_string'].format(suffix=lib_suffix)\n\n\n FileName = module.getName(params, configuration)\n ModelName = FileName.replace('.', '').replace('-', '_').replace('(', '').replace(')', '')\n\n FreeCAD.Console.PrintMessage('\\r\\n'+FileName+'\\r\\n')\n #FileName = modul.all_params[variant].file_name\n Newdoc = FreeCAD.newDocument(ModelName)\n print((Newdoc.Label))\n App.setActiveDocument(ModelName)\n App.ActiveDocument=App.getDocument(ModelName)\n Gui.ActiveDocument=Gui.getDocument(ModelName)\n\n if hasattr(params, 'color_keys'):\n color_keys = params.color_keys\n else:\n color_keys = series_definition.color_keys\n obj_suffixes = series_definition.obj_suffixes\n colors = [shaderColors.named_colors[key].getDiffuseInt() for key in color_keys]\n\n cq_obj_data = module.generate_part(params)\n\n\n for i in range(len(cq_obj_data)):\n color_i = colors[i] + (0,)\n show(cq_obj_data[i], color_i)\n\n\n doc = FreeCAD.ActiveDocument\n doc.Label = ModelName\n objs=GetListOfObjects(FreeCAD, doc)\n\n\n for i in range(len(objs)):\n objs[i].Label = ModelName + obj_suffixes[i]\n\n\n restore_Main_Tools()\n\n if stop_after_coloring:\n return\n\n out_dir='{:s}{:s}.3dshapes'.format(global_3dpath, lib_name)\n if not os.path.exists(out_dir):\n os.makedirs(out_dir)\n\n used_color_keys = color_keys\n export_file_name=out_dir+os.sep+FileName+'.wrl'\n\n export_objects = []\n for i in range(len(objs)):\n export_objects.append(expVRML.exportObject(freecad_object = objs[i],\n shape_color=color_keys[i],\n face_colors=None))\n\n scale=1/2.54\n colored_meshes = expVRML.getColoredMesh(Gui, export_objects , scale, mesh_deviation)\n expVRML.writeVRMLFile(colored_meshes, export_file_name, used_color_keys, LIST_license)\n\n fusion = multiFuseObjs_wColors(FreeCAD, FreeCADGui,\n ModelName, objs, keepOriginals=True)\n exportSTEP(doc,FileName,out_dir,fusion)\n\n step_path = '{dir:s}/{name:s}.step'.format(dir=out_dir, name=FileName)\n\n L.addLicenseToStep(out_dir, '{:s}.step'.\\\n format(FileName), LIST_license,\n module.LICENCE_Info.STR_licAuthor,\n module.LICENCE_Info.STR_licEmail,\n module.LICENCE_Info.STR_licOrgSys,\n module.LICENCE_Info.STR_licPreProc)\n\n FreeCAD.activeDocument().recompute()\n\n saveFCdoc(App, Gui, doc, FileName, out_dir)\n\n #FreeCADGui.activateWorkbench(\"PartWorkbench\")\n if save_memory == False and check_Model==False:\n FreeCADGui.SendMsgToActiveView(\"ViewFit\")\n FreeCADGui.activeDocument().activeView().viewAxometric()\n\n if save_memory == True or check_Model==True:\n docu = FreeCAD.ActiveDocument\n FreeCAD.Console.PrintMessage('close document {}\\r\\n'.format(docu.Name))\n FreeCAD.closeDocument(docu.Name)\n\n if check_Model==True:\n runGeometryCheck(App, Gui, step_path,\n log, ModelName, save_memory=save_memory)\n\ndef exportSeries(module, configuration, log, model_filter_regobj):\n for model_id in module.all_params:\n try:\n if model_filter_regobj.match(str(model_id)):\n params = module.all_params[model_id]\n export_one_part(module, params, configuration, log)\n except GeometryError as e:\n e.print_errors(stop_on_first_error)\n if stop_on_first_error:\n return -1\n if close_erronous:\n docu = FreeCAD.ActiveDocument\n FreeCAD.Console.PrintMessage('close document {}\\r\\n'.format(docu.Name))\n FreeCAD.closeDocument(docu.Name)\n except FreeCADVersionError as e:\n FreeCAD.Console.PrintError(e)\n return -1\n return 0\n\n######################### ADD MODEL GENERATORS #########################\n\nsys.path.append(\"cq_models\")\nimport c_axial_tht\nimport cp_axial_tht\nimport c_rect_tht\nimport c_disc_tht\n\nall_series = {\n 'axial_tht':c_axial_tht,\n 'pol_axial_tht':cp_axial_tht,\n 'rect_tht':c_rect_tht,\n 'disc_tht':c_disc_tht,\n}\n\n#########################################################################\n\nclass argparse():\n def __init__(self):\n self.config = '../_tools/config/capacitor_config_KLCv3.yaml'\n self.model_filter = '*'\n self.series = list(all_series.values())\n\n def parse_args(self, args):\n for arg in args:\n if '=' in arg:\n self.parseValueArg(*arg.split('='))\n else:\n self.argSwitchArg(arg)\n\n def parseValueArg(self, name, value):\n if name == 'config':\n self.config = value\n elif name == 'filter':\n self.model_filter = value\n elif name == 'log':\n global check_log_file\n check_log_file = value\n elif name == 'series':\n series_str = value.split(',')\n self.series = []\n for s in series_str:\n if s.lower() in all_series:\n self.series.append(all_series[s.lower()])\n elif name == 'mesh_deviation':\n global mesh_deviation\n mesh_deviation = float(value)\n\n def argSwitchArg(self, name):\n if name == '?':\n self.print_usage()\n exit()\n elif name == 'disable_check':\n global check_Model\n check_Model = False\n elif name == 'disable_Memory_reduction':\n global save_memory\n save_memory = False\n elif name == 'error_tolerant':\n global stop_on_first_error\n stop_on_first_error = False\n elif name == 'close_erronous':\n global close_erronous\n close_erronous = True\n elif name == \"stop_after_coloring\":\n global stop_after_coloring\n stop_after_coloring = True\n\n def print_usage(self):\n print(\"Generater script for capacitor 3d models.\")\n print('usage: FreeCAD main_generator.py [optional arguments and switches]')\n print('optional arguments:')\n print('\\tconfig=[config file]: default:capacitor_config_KLCv3.0.yaml')\n print('\\tfilter=[filter models by model name using linux filename syntax]')\n print('\\tlog=[log file path]')\n print('\\tseries=[series name],[series name],...')\n print('switches:')\n print('\\tdisable_check')\n print('\\tdisable_Memory_reduction')\n print('\\terror_tolerant\\n')\n print('\\tclose_erronous\\n')\n print('\\tstop_after_coloring\\n')\n\n def __str__(self):\n return 'config:{:s}, filter:{:s}, series:{:s}, with_plug:{:d}'.format(\n self.config, self.model_filter, str(self.series), self.with_plug)\n\nif __name__ == \"__main__\" or __name__ == \"main_generator\":\n FreeCAD.Console.PrintMessage('\\r\\nRunning...\\r\\n')\n\n args = argparse()\n args.parse_args(sys.argv)\n modelfilter = args.model_filter\n\n with open(args.config, 'r') as config_stream:\n try:\n configuration = yaml.load(config_stream)\n except yaml.YAMLError as exc:\n print(exc)\n\n model_filter_regobj=re.compile(fnmatch.translate(modelfilter))\n\n\n with open(check_log_file, 'w') as log:\n log.write('# Check report for Molex 3d model genration\\n')\n for typ in args.series:\n try:\n if exportSeries(typ, configuration, log, model_filter_regobj) != 0:\n break\n except Exception as exeption:\n traceback.print_exc()\n break\n\n\n FreeCAD.Console.PrintMessage('\\r\\Done\\r\\n')\n","repo_name":"easyw/kicad-3d-models-in-freecad","sub_path":"cadquery/FCAD_script_generator/Capacitor_THT/main_generator.py","file_name":"main_generator.py","file_ext":"py","file_size_in_byte":10097,"program_lang":"python","lang":"en","doc_type":"code","stars":122,"dataset":"github-code","pt":"17"} +{"seq_id":"15608577124","text":"# Say you have an array for which the ith element is the price of a given stock on day i.\n#\n# If you were only permitted to complete at most one transaction (ie, buy one and sell one share of the stock), design an algorithm to find the maximum profit.\n#\n# Example 1:\n# Input: [7, 1, 5, 3, 6, 4]\n# Output: 5\n#\n# max. difference = 6-1 = 5 (not 7-1 = 6, as selling price needs to be larger than buying price)\n# Example 2:\n# Input: [7, 6, 4, 3, 1]\n# Output: 0\n#\n# In this case, no transaction is done, i.e. max profit = 0.\n\n# # key: current maxprofit is the current price minus curent min price\n\nimport time\nclass Solution(object):\n def maxProfit(self,prices):\n max_profit, min_price = 0, float('inf')\n for price in prices:\n min_price = min(min_price, price)\n profit = price - min_price\n max_profit = max(max_profit, profit)\n return max_profit\n\n# other good solution:maxProfit\n# key: can use map to build link of left and right node with maxDepth\n\n\n\ndef main():\n n=[1,2,3,5]\n time_t=time.time()\n sln=Solution().maxProfit(n)\n print(time.time()-time_t)\n\n print(sln)\n\nif __name__==\"__main__\":\n main()","repo_name":"JianWang2018/Python","sub_path":"leet_code/121.best_time_buy_sell_stock.py","file_name":"121.best_time_buy_sell_stock.py","file_ext":"py","file_size_in_byte":1168,"program_lang":"python","lang":"en","doc_type":"code","stars":2,"dataset":"github-code","pt":"17"} +{"seq_id":"71762948825","text":"import services.comics_service as cs\nfrom utils import COLOR_PALETTE\nfrom typing import Callable\nimport flet as ft\n\n# data de los comics\n_total_comics: int = 0\n_comics: list[dict[str, any]] = []\n\n# Para la paginación\n_params = {\"limit\": 10, \"offset\": 0}\n\n\n# Filtro de comics por formato\n# format_filters = [\n# \"none\",\n# \"comic\",\n# \"magazine\",\n# \"trade paperback\",\n# \"hardcover\",\n# \"digest\",\n# \"graphic novel\",\n# \"digital comic\",\n# \"infinite comic\",\n# ]\n\nformat_filters = {\n \"none\": \"No ordenar\",\n \"comic\": \"Comic\",\n \"magazine\": \"Revista\",\n \"trade paperback\": \"Trade Paperback\",\n \"hardcover\": \"Tapa Dura\",\n \"digest\": \"Boletín\",\n \"graphic novel\": \"Novela Gráfica\",\n \"digital comic\": \"Comic Digital\",\n \"infinite comic\": \"Comic Infinito\",\n}\n\n# Filtro por formato de comic\n# _actual_format_filter = format_filters[0]\n_actual_format_filter = \"none\"\n\n# Para obtener los comics\n_fetch_func = cs.get_comics(_params)\n\n\ndef comics_view(update_func: Callable):\n # Barra de navegación\n appbar = ft.AppBar(\n title=ft.Text(\"Comics\"),\n center_title=True,\n bgcolor=COLOR_PALETTE[\"On-Tertiary\"],\n toolbar_height=50,\n )\n\n def filter_comics(e):\n global _actual_format_filter, _params\n _actual_format_filter = str(dp.value)\n _params[\"offset\"] = 0\n\n set_loading()\n fetch_comics()\n\n # Dropdown de filtros\n dp = ft.Dropdown(\n label=\"Filtrar por\",\n options=list(\n map(\n lambda f: ft.dropdown.Option(text=f[1], key=f[0]),\n format_filters.items(),\n )\n ),\n autofocus=True,\n value=\"none\",\n on_change=filter_comics,\n )\n\n # Contenedor de los comics\n comics_content = ft.Row(\n wrap=True,\n expand=True,\n scroll=\"always\",\n spacing=10,\n alignment=ft.MainAxisAlignment.CENTER,\n )\n\n # Cuerpo de la página\n body = ft.Container(\n ft.Column(\n [\n ft.Row(\n [dp],\n alignment=\"center\",\n ),\n ft.Container(\n comics_content,\n margin=ft.margin.only(top=30),\n ),\n ]\n ),\n margin=ft.margin.only(top=30),\n )\n\n # Renderiza los comics\n def render_comics():\n # Habilita el dropdown\n dp.disabled = False\n\n # Limpia contenedor de comics\n comics_content.controls.clear()\n\n # Genera los comics\n comics_content.controls = list(\n map(\n lambda comic: ft.Container(\n ft.Card(\n content=ft.Stack(\n [\n ft.Container(\n ft.Image(\n src=f\"{comic['thumbnail']['path']}.{comic['thumbnail']['extension']}\",\n width=120,\n height=120,\n ),\n alignment=ft.alignment.top_center,\n padding=ft.padding.only(top=25, bottom=5),\n ),\n ft.Container(\n ft.Text(comic[\"title\"], text_align=\"center\"),\n alignment=ft.alignment.bottom_center,\n padding=ft.padding.only(left=5, right=5, bottom=15),\n ),\n ],\n ),\n ),\n width=230,\n height=230,\n bgcolor=COLOR_PALETTE[\"On-Error\"],\n ),\n _comics,\n )\n )\n\n # Añade la paginación (numero de pagina actual)\n pag_text = f\"{int(_params['offset'] / _params['limit']) + 1}\"\n pag_text += f\" de {int(_total_comics / _params['limit']) + 1} páginas\"\n comics_content.controls.append(\n ft.Container(\n ft.Row(\n [\n ft.IconButton(\n icon=ft.icons.ARROW_BACK,\n disabled=_params[\"offset\"] == 0,\n on_click=before_page,\n ),\n ft.Text(pag_text),\n ft.IconButton(\n icon=ft.icons.ARROW_FORWARD,\n disabled=_params[\"offset\"] + _params[\"limit\"] >= _total_comics,\n on_click=next_page,\n ),\n ],\n alignment=ft.MainAxisAlignment.CENTER,\n ),\n padding=ft.padding.only(top=20),\n )\n )\n\n update_func()\n\n # render loading indicator\n def set_loading():\n # Deshabilita el dropdown\n dp.disabled = True\n\n # Muestra el indicador de carga\n comics_content.controls = [\n ft.Container(\n ft.Column(\n [ft.ProgressRing(), ft.Text(\"Cargando...\")],\n horizontal_alignment=ft.CrossAxisAlignment.CENTER,\n ),\n alignment=ft.alignment.center,\n margin=ft.margin.only(top=50),\n )\n ]\n update_func()\n\n # Para obtener los comics\n def fetch_comics():\n global _total_comics, _comics, _params\n\n # Si el filtro es none, se elimina el parametro de la consulta\n if \"format\" in _params:\n del _params[\"format\"]\n\n # Si el filtro es distinto de none, se agrega el parametro de la consulta\n if _actual_format_filter != \"none\":\n _params[\"format\"] = _actual_format_filter\n\n result = _fetch_func()\n\n if result != {}:\n _total_comics = result[\"total\"]\n _comics = result[\"results\"]\n render_comics()\n else:\n comics_content.controls = [\n ft.Text(\"No se han podido obtener los comics, intente de nuevo.\")\n ]\n update_func()\n\n # Para la paginación\n def before_page(e):\n global _params\n\n if _params[\"offset\"] == 0:\n return\n\n set_loading()\n _params[\"offset\"] -= _params[\"limit\"]\n fetch_comics()\n\n def next_page(e):\n global _params, _total_comics\n\n if _params[\"offset\"] + _params[\"limit\"] >= _total_comics:\n return\n\n set_loading()\n _params[\"offset\"] += _params[\"limit\"]\n fetch_comics()\n\n # First fetch\n fetch_comics()\n\n return [appbar, body]\n","repo_name":"axlserial/proyecto-final-funcional","sub_path":"views/comics_view.py","file_name":"comics_view.py","file_ext":"py","file_size_in_byte":6767,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"17"} +{"seq_id":"73419755543","text":"import torch\nfrom config import get_config, decide_expnum\nfrom data_loader import DataLoader\nimport os\nimport json\nimport sys\nimport pdb\n\ndef main(config):\n #prepare_dirs_and_logger(config)\n\n from data_loader import DataLoader\n if(config.trainer == 'DCE_multiCH'):\n paired = True\n from trainer_DCE_multiCH import Trainer # 학습 초기화\n\n if config.gpu >= 0:\n torch.cuda.manual_seed(config.random_seed)\n torch.cuda.set_device(config.gpu)\n\n # Check manually assigned manifest path exists\n if (len(config.tr_cl_manifest) > 0):\n print('manually assinged manifest exists for clean training set. Use it.')\n if (len(config.tr_ny_manifest) > 0):\n print('manually assinged manifest exists for noisy training set. Use it.')\n if (len(config.trsub_manifest) > 0):\n print('manually assinged manifest exists for noisy training SUBset. Use it.')\n if (len(config.val_manifest) > 0):\n print('manually assinged manifest exists for noisy validation set. Use it.')\n if (len(config.val2_manifest) > 0):\n print('manually assinged manifest exists for noisy validation2 set. Use it.')\n\n # Assign manifest\n if(config.DB_name == 'dereverb_4IR'):\n if(config.multiCH):\n if(paired):\n config.tr_ny_manifest = 'data_sorted/Dereverb_4IR_train_inputSNR.csv'\n config.trsub_manifest = 'data_sorted/Dereverb_4IR_trsub_inputSNR.csv'\n config.val_manifest = 'data_sorted/Dereverb_4IR_val_inputSNR.csv'\n else:\n assert (0), 'NOT IMPLEMENTED YET'\n noise_info = {} # dummy\n spk_info = {} # dummy\n\n print('tr_ny_manifest = ' + config.tr_ny_manifest)\n print('trsub_manifest = ' + config.trsub_manifest)\n print('val_manifest = ' + config.val_manifest)\n print('val2_manifest = ' + config.val2_manifest)\n\n noise_info = {\n 'BUS': 0,\n 'PED': 1,\n 'CAF': 2,\n 'STR': 3\n }\n\n config.noise_info = noise_info\n config.spk_info = spk_info\n with open(config.labels_path) as label_file:\n labels = str(''.join(json.load(label_file)))\n\n data_loader = DataLoader(batch_size = config.batch_size, paired=paired,\n tr_cl_manifest=config.tr_cl_manifest, tr_ny_manifest=config.tr_ny_manifest, trsub_manifest=config.trsub_manifest,\n val_manifest=config.val_manifest, val2_manifest=config.val2_manifest, labels=labels,\n include_noise=config.noise_clf, noise_info=noise_info,\n include_spk=config.spk_clf, spk_info=spk_info,\n multiCH=config.multiCH, BSS=config.BSS, BSE=config.BSE, linear_to_mel=config.linear_to_mel,\n db=config.DB_name)\n\n if(config.mode == 'train'):\n assert(config.expnum == -1), 'for training, do not specify expnum'\n config.expnum = decide_expnum('logs_only')\n else:\n assert(not config.expnum == -1), 'for test or analysis, please specify expnum'\n\n if not os.path.exists('logs_only/' + str(config.expnum)):\n os.makedirs('logs_only/' + str(config.expnum))\n\n if not os.path.exists('models/' + str(config.expnum)):\n os.makedirs('models/' + str(config.expnum))\n\n trainer = Trainer(config, data_loader)\n\n torch.manual_seed(config.random_seed)\n\n print('tr_cl_manifest = ' + config.tr_cl_manifest)\n print('tr_ny_manifest = ' + config.tr_ny_manifest)\n print('trsub_manifest = ' + config.trsub_manifest)\n print('val_manifest = ' + config.val_manifest)\n print('val2_manifest = ' + config.val2_manifest)\n\n if (config.mode == 'train'):\n trainer.train() # 학습 시작\n elif(config.mode == 'visualize'):\n trainer.visualize()\n\n\nif __name__ == \"__main__\":\n config, unparsed = get_config()\n\n main(config)\n","repo_name":"lifelongeek/multimic_enhancement","sub_path":"main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":3920,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"17"} +{"seq_id":"31263685884","text":"import logging\nfrom typing import List, Dict\n\nfrom resonances.datamining import ResonanceOrbitalElementSetFacade\nfrom resonances.entities import ResonanceMixin, BodyNumberEnum, LibrationMixin\n\nfrom resonances.entities.dbutills import session\nfrom resonances.settings import Config\nfrom .librationbuilder import ApocentricBuilder\nfrom .librationbuilder import LibrationDirector\nfrom .librationbuilder import TransientBuilder\n\nCONFIG = Config.get_params()\nBODIES_COUNTER = CONFIG['integrator']['number_of_bodies']\n\n\nclass LibrationClassifier:\n \"\"\"\n Class is need for determining type of libration. If it needs, class will build libration by\n resonances and orbital elements of related sky bodies.\n \"\"\"\n def __init__(self, get_from_db, body_count: BodyNumberEnum):\n self._get_from_db = get_from_db\n self._libration_director = LibrationDirector(body_count)\n self._resonance = None # type: ResonanceMixin\n self._resonance_str = None # type: str\n self._asteroid_name = None # type: str\n self._libration = None # type: Libration\n\n def set_resonance(self, resonance: ResonanceMixin):\n \"\"\"\n Wroks as hook before classifying libration. It is need for saving useful data before any\n actions on resonance's libration by SQLalchemy, because we can try get something from\n resonance, and doesn't allow us remove libration.\n :param resonance:\n \"\"\"\n self._resonance = resonance\n self._resonance_str = str(resonance)\n self._asteroid_name = self._resonance.small_body.name\n self._libration = self._resonance.libration\n\n def classify(self, orbital_elem_set: ResonanceOrbitalElementSetFacade,\n serialized_phases: List[Dict[str, float]]) -> bool:\n \"\"\"\n Determines class of libration. Libration can be loaded from database if object has upped\n flag _get_from_db. If libration's class was not determined, libration will be removed and\n method returns False else libration will be saved and method return True.\n :param serialized_phases:\n :param orbital_elem_set:\n :return: flag of successful determining class of libration.\n \"\"\"\n if not self._get_from_db and self._libration is None:\n builder = TransientBuilder(self._resonance, orbital_elem_set, serialized_phases)\n self._libration = self._libration_director.build(builder)\n elif not self._libration:\n return True\n\n try:\n if _save_as_transient(self._libration, self._resonance, self._asteroid_name,\n self._resonance_str):\n return True\n elif not self._libration.is_apocentric:\n logging.info('%s, pure resonance %s', self._asteroid_name, self._resonance_str)\n return True\n raise _NoTransientException()\n except _NoTransientException:\n if not self._get_from_db and not self._libration.is_apocentric:\n builder = ApocentricBuilder(self._resonance, orbital_elem_set, serialized_phases)\n self._libration = self._libration_director.build(builder)\n\n if self._libration.is_pure:\n logging.info('%s, pure apocentric resonance %s', self._asteroid_name,\n self._resonance_str)\n return True\n else:\n session.expunge(self._libration)\n return False\n\n\ndef _save_as_transient(libration: LibrationMixin, resonance: ResonanceMixin,\n asteroid_name: str, resonance_str: str):\n if not libration.is_pure:\n if libration.is_transient:\n if libration.percentage:\n logging.info('%s, %s, resonance = %s', asteroid_name,\n str(libration), str(resonance))\n return True\n else:\n logging.debug(\n '%s, NO RESONANCE, resonance = %s, max = %f',\n asteroid_name, resonance_str, libration.max_diff\n )\n session.expunge(libration)\n raise _NoTransientException()\n raise _NoTransientException()\n return False\n\n\nclass _NoTransientException(Exception):\n pass\n","repo_name":"smirik/mass-resonances","sub_path":"resonances/datamining/librations/classifier.py","file_name":"classifier.py","file_ext":"py","file_size_in_byte":4283,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"17"} +{"seq_id":"31280630190","text":"# -*- coding: utf-8 -*-\n\"\"\"Contains the :class:`ManyToOneMatcher` which can be used for fast many-to-one matching.\n\nYou can initialize the matcher with a list of the patterns that you wish to match:\n\n>>> pattern1 = Pattern(f(a, x_))\n>>> pattern2 = Pattern(f(y_, b))\n>>> matcher = ManyToOneMatcher(pattern1, pattern2)\n\nYou can also add patterns later:\n\n>>> pattern3 = Pattern(f(a, b))\n>>> matcher.add(pattern3)\n\nA pattern can be added with a label which is yielded instead of the pattern during matching:\n\n>>> pattern4 = Pattern(f(x_, y_))\n>>> matcher.add(pattern4, \"some label\")\n\nThen you can match a subject against all the patterns at once:\n\n>>> subject = f(a, b)\n>>> matches = matcher.match(subject)\n>>> for matched_pattern, substitution in sorted(map(lambda m: (str(m[0]), str(m[1])), matches)):\n... print('{} matched with {}'.format(matched_pattern, substitution))\nf(a, b) matched with {}\nf(a, x_) matched with {x ↦ b}\nf(y_, b) matched with {y ↦ a}\nsome label matched with {x ↦ a, y ↦ b}\n\nAlso contains the :class:`ManyToOneReplacer` which can replace a set :class:`ReplacementRule` at one using a\n:class:`ManyToOneMatcher` for finding the matches.\n\"\"\"\nimport math\nimport html\nimport itertools\nimport copy\nfrom collections import deque\nfrom operator import itemgetter\nfrom typing import Container, Dict, Iterable, Iterator, List, NamedTuple, Optional, Sequence, Set, Tuple, Type, Union\n\ntry:\n from graphviz import Digraph, Graph\nexcept ImportError:\n Digraph = None\n Graph = None\nfrom multiset import Multiset\n\nfrom ..expressions.expressions import (\n Expression, Operation, Symbol, SymbolWildcard, Wildcard, Pattern, AssociativeOperation, CommutativeOperation, OneIdentityOperation\n)\nfrom ..expressions.substitution import Substitution\nfrom ..expressions.functions import (\n is_anonymous, contains_variables_from_set, create_operation_expression, preorder_iter_with_position,\n rename_variables, op_iter, preorder_iter, op_len\n)\nfrom ..utils import (VariableWithCount, commutative_sequence_variable_partition_iter)\nfrom .. import functions\nfrom .bipartite import BipartiteGraph, enum_maximum_matchings_iter, LEFT\nfrom .syntactic import OPERATION_END, is_operation\nfrom ._common import check_one_identity\n\n__all__ = ['ManyToOneMatcher', 'ManyToOneReplacer']\n\nLabelType = Union[Expression, Type[Operation]]\nHeadType = Optional[Union[Expression, Type[Operation], Type[Symbol]]]\nMultisetOfInt = Multiset\nMultisetOfExpression = Multiset\n\n_EPS = object()\n\n_State = NamedTuple('_State', [\n ('number', int),\n ('transitions', Dict[LabelType, '_Transition']),\n ('matcher', Optional['CommutativeMatcher'])\n]) # yapf: disable\n\n_Transition = NamedTuple('_Transition', [\n ('label', LabelType),\n ('target', _State),\n ('variable_name', Optional[str]),\n ('patterns', Set[int]),\n ('check_constraints', Optional[Set[int]]),\n ('subst', Substitution),\n]) # yapf: disable\n\n\n_VISITED = set()\n\nclass _MatchIter:\n def __init__(self, matcher, subject, intial_associative=None):\n self.matcher = matcher\n self.subjects = deque([subject]) if subject is not None else deque()\n self.patterns = set(range(len(matcher.patterns)))\n self.substitution = Substitution()\n self.constraints = set(range(len(matcher.constraints)))\n self.associative = [intial_associative]\n\n def __iter__(self):\n for _ in self._match(self.matcher.root):\n yield from self._internal_iter()\n\n def grouped(self):\n \"\"\"\n Yield the matches grouped by their final state in the automaton, i.e. structurally identical patterns\n only differing in constraints will be yielded together. Each group is yielded as a list of tuples consisting of\n a pattern and a match substitution.\n\n Yields:\n The grouped matches.\n \"\"\"\n for _ in self._match(self.matcher.root):\n yield list(self._internal_iter())\n\n def any(self):\n \"\"\"\n Returns:\n True, if any match is found.\n \"\"\"\n try:\n next(self)\n except StopIteration:\n return False\n return True\n\n def _internal_iter(self):\n for pattern_index in self.patterns:\n renaming = self.matcher.pattern_vars[pattern_index]\n new_substitution = self.substitution.rename({renamed: original for original, renamed in renaming.items()})\n pattern, label, _ = self.matcher.patterns[pattern_index]\n valid = True\n for constraint in pattern.global_constraints:\n if not constraint(new_substitution):\n valid = False\n break\n if valid:\n yield label, new_substitution\n\n def _match(self, state: _State) -> Iterator[_State]:\n _VISITED.add(state.number)\n if len(self.subjects) == 0:\n if state.number in self.matcher.finals or OPERATION_END in state.transitions:\n yield state\n heads = [None]\n else:\n heads = list(self._get_heads(self.subjects[0]))\n for head in heads:\n for transition in state.transitions.get(head, []):\n yield from self._match_transition(transition)\n\n def _match_transition(self, transition: _Transition) -> Iterator[_State]:\n if self.patterns.isdisjoint(transition.patterns):\n return\n label = transition.label\n if label is _EPS:\n subject = self.subjects[0] if self.subjects else None\n yield from self._check_transition(transition, subject, False)\n return\n if is_operation(label):\n if transition.target.matcher:\n yield from self._match_commutative_operation(transition.target)\n else:\n yield from self._match_regular_operation(transition)\n return\n if isinstance(label, Wildcard) and not isinstance(label, SymbolWildcard):\n min_count = label.min_count\n if label.optional is not None and min_count > 0:\n yield from self._check_transition(transition, label.optional, False)\n if label.fixed_size and not self.associative[-1]:\n assert min_count == 1, \"Fixed wildcards with length != 1 are not supported.\"\n if not self.subjects:\n return\n else:\n yield from self._match_sequence_variable(label, transition)\n return\n subject = self.subjects.popleft() if self.subjects else None\n yield from self._check_transition(transition, subject)\n\n def _check_transition(self, transition, subject, restore_subject=True):\n if self.patterns.isdisjoint(transition.patterns):\n return\n restore_constraints = set()\n restore_patterns = self.patterns - transition.patterns\n self.patterns &= transition.patterns\n old_values = {}\n try:\n if transition.subst is not None:\n try:\n for name, value in transition.subst.items():\n old_values[name] = self.substitution.get(name, None)\n self.substitution.try_add_variable(name, value)\n except ValueError:\n for k, v in old_values.items():\n if v is None:\n del self.substitution[k]\n else:\n self.substitution[k] = v\n return\n\n if transition.variable_name is not None:\n try:\n old_values[transition.variable_name] = self.substitution.get(transition.variable_name, None)\n self.substitution.try_add_variable(transition.variable_name, subject)\n except ValueError:\n return\n self._check_constraints(transition.check_constraints, restore_constraints, restore_patterns)\n if not self.patterns:\n return\n\n yield from self._match(transition.target)\n\n finally:\n if restore_subject and subject is not None:\n self.subjects.appendleft(subject)\n self.constraints |= restore_constraints\n self.patterns |= restore_patterns\n for k, v in old_values.items():\n if v is None:\n del self.substitution[k]\n else:\n self.substitution[k] = v\n\n def _check_constraints(self, variable: str, restore_constraints, restore_patterns) -> bool:\n if isinstance(variable, str):\n check_constraints = self.matcher.constraint_vars.get(variable, [])\n else:\n check_constraints = variable\n variables = set(self.substitution.keys())\n for constraint_index in check_constraints:\n if constraint_index not in self.constraints:\n continue\n constraint, patterns = self.matcher.constraints[constraint_index]\n if constraint.variables <= variables and not self.patterns.isdisjoint(patterns):\n self.constraints.remove(constraint_index)\n restore_constraints.add(constraint_index)\n if not constraint(self.substitution):\n restore_patterns |= self.patterns & patterns\n self.patterns -= patterns\n if not self.patterns:\n break\n\n @staticmethod\n def _get_heads(expression: Expression) -> Iterator[HeadType]:\n for base in type(expression).__mro__:\n if base is not object:\n yield base\n if not isinstance(expression, Operation):\n yield expression\n yield None\n\n def _match_sequence_variable(self, wildcard: Wildcard, transition: _Transition) -> Iterator[_State]:\n min_count = wildcard.min_count\n if len(self.subjects) < min_count:\n return\n matched_subject = []\n for _ in range(min_count):\n matched_subject.append(self.subjects.popleft())\n while True:\n if self.associative[-1] and wildcard.fixed_size:\n assert min_count == 1, \"Fixed wildcards with length != 1 are not supported.\"\n if len(matched_subject) > 1:\n wrapped = self.associative[-1](*matched_subject)\n else:\n wrapped = matched_subject[0]\n else:\n if len(matched_subject) == 0 and wildcard.optional is not None:\n wrapped = wildcard.optional\n else:\n wrapped = tuple(matched_subject)\n yield from self._check_transition(transition, wrapped, False)\n if not self.subjects:\n break\n matched_subject.append(self.subjects.popleft())\n self.subjects.extendleft(reversed(matched_subject))\n\n def _match_commutative_operation(self, state: _State) -> Iterator[_State]:\n subject = self.subjects.popleft()\n matcher = state.matcher\n substitution = self.substitution\n matcher.add_subject(None)\n for operand in op_iter(subject):\n matcher.add_subject(operand)\n for matched_pattern, new_substitution in matcher.match(subject, substitution):\n restore_constraints = set()\n diff = set(new_substitution.keys()) - set(substitution.keys())\n self.substitution = new_substitution\n transition_set = state.transitions[matched_pattern]\n t_iter = iter(t.patterns for t in transition_set)\n potential_patterns = next(t_iter).union(*t_iter)\n restore_patterns = self.patterns - potential_patterns\n self.patterns &= potential_patterns\n for variable in diff:\n self._check_constraints(variable, restore_constraints, restore_patterns)\n if not self.patterns:\n break\n if self.patterns:\n transition_set = state.transitions[matched_pattern]\n for next_transition in transition_set:\n yield from self._check_transition(next_transition, subject, False)\n self.constraints |= restore_constraints\n self.patterns |= restore_patterns\n self.substitution = substitution\n self.subjects.appendleft(subject)\n\n def _match_regular_operation(self, transition: _Transition) -> Iterator[_State]:\n subject = self.subjects.popleft()\n after_subjects = self.subjects\n operand_subjects = self.subjects = deque(op_iter(subject))\n new_associative = transition.label if issubclass(transition.label, AssociativeOperation) else None\n self.associative.append(new_associative)\n for new_state in self._check_transition(transition, subject, False):\n self.subjects = after_subjects\n self.associative.pop()\n for end_transition in new_state.transitions[OPERATION_END]:\n yield from self._check_transition(end_transition, None, False)\n self.subjects = operand_subjects\n self.associative.append(new_associative)\n self.subjects = after_subjects\n self.subjects.appendleft(subject)\n self.associative.pop()\n\n\nclass ManyToOneMatcher:\n __slots__ = ('patterns', 'states', 'root', 'pattern_vars', 'constraints', 'constraint_vars', 'finals', 'rename', 'commutative_matchers')\n\n _state_id = 0\n\n def __init__(self, *patterns: Expression, rename=True) -> None:\n \"\"\"\n Args:\n *patterns: The patterns which the matcher should match.\n \"\"\"\n self.patterns = []\n self.states = []\n self.root = self._create_state()\n self.pattern_vars = []\n self.constraints = []\n self.constraint_vars = {}\n self.finals = set()\n self.rename = rename\n self.commutative_matchers = []\n\n for pattern in patterns:\n self.add(pattern)\n\n def clear(self):\n \"\"\"Removes all cached data.\"\"\"\n for commutative_matcher in self.commutative_matchers:\n commutative_matcher.clear()\n\n def add(self, pattern: Pattern, label=None) -> None:\n \"\"\"Add a new pattern to the matcher.\n\n The optional label defaults to the pattern itself and is yielded during matching. The same pattern can be\n added with different labels which means that every match for the pattern will result in every associated label\n being yielded with that match individually.\n\n Equivalent patterns with the same label are not added again. However, patterns that are structurally equivalent,\n but have different constraints or different variable names are distinguished by the matcher.\n\n Args:\n pattern:\n The pattern to add.\n label:\n An optional label for the pattern. Defaults to the pattern itself.\n \"\"\"\n if label is None:\n label = pattern\n for i, (p, l, _) in enumerate(self.patterns):\n if pattern == p and label == l:\n return i\n # TODO: Avoid renaming in the pattern, use variable indices instead\n renaming = self._collect_variable_renaming(pattern.expression) if self.rename else {}\n self._internal_add(pattern, label, renaming)\n\n def _internal_add(self, pattern: Pattern, label, renaming) -> int:\n \"\"\"Add a new pattern to the matcher.\n\n Equivalent patterns are not added again. However, patterns that are structurally equivalent,\n but have different constraints or different variable names are distinguished by the matcher.\n\n Args:\n pattern: The pattern to add.\n\n Returns:\n The internal id for the pattern. This is mainly used by the :class:`CommutativeMatcher`.\n \"\"\"\n pattern_index = len(self.patterns)\n renamed_constraints = [c.with_renamed_vars(renaming) for c in pattern.local_constraints]\n constraint_indices = [self._add_constraint(c, pattern_index) for c in renamed_constraints]\n self.patterns.append((pattern, label, constraint_indices))\n self.pattern_vars.append(renaming)\n pattern = rename_variables(pattern.expression, renaming)\n state = self.root\n patterns_stack = [deque([pattern])]\n\n self._process_pattern_stack(state, patterns_stack, renamed_constraints, pattern_index)\n\n return pattern_index\n\n def _process_pattern_stack(self, state, patterns_stack, renamed_constraints, pattern_index):\n while patterns_stack:\n if patterns_stack[-1]:\n subpattern = patterns_stack[-1].popleft()\n variable_name = getattr(subpattern, 'variable_name', None)\n if isinstance(subpattern, Operation):\n if isinstance(subpattern, OneIdentityOperation):\n non_optional, added_subst = check_one_identity(subpattern)\n if non_optional is not None:\n stack = [q.copy() for q in patterns_stack]\n stack[-1].appendleft(non_optional)\n new_state = self._create_expression_transition(state, _EPS, variable_name, pattern_index, added_subst)\n self._process_pattern_stack(new_state, stack, renamed_constraints, pattern_index)\n if not isinstance(subpattern, CommutativeOperation):\n patterns_stack.append(deque(op_iter(subpattern)))\n state = self._create_expression_transition(state, subpattern, variable_name, pattern_index)\n if isinstance(subpattern, CommutativeOperation):\n subpattern_id = state.matcher.add_pattern(subpattern, renamed_constraints)\n state = self._create_simple_transition(state, subpattern_id, pattern_index)\n else:\n patterns_stack.pop()\n if len(patterns_stack) > 0:\n state = self._create_simple_transition(state, OPERATION_END, pattern_index)\n self.finals.add(state.number)\n\n\n def _add_constraint(self, constraint, pattern):\n index = None\n for i, (c, patterns) in enumerate(self.constraints):\n if c == constraint:\n patterns.add(pattern)\n index = i\n break\n else:\n index = len(self.constraints)\n self.constraints.append((constraint, set([pattern])))\n for var in constraint.variables:\n self.constraint_vars.setdefault(var, set()).add(index)\n return index\n\n def match(self, subject: Expression) -> Iterator[Tuple[Expression, Substitution]]:\n \"\"\"Match the subject against all the matcher's patterns.\n\n Args:\n subject: The subject to match.\n\n Yields:\n For every match, a tuple of the matching pattern and the match substitution.\n \"\"\"\n return _MatchIter(self, subject)\n\n def is_match(self, subject: Expression) -> bool:\n \"\"\"Check if the subject matches any of the matcher's patterns.\n\n Args:\n subject: The subject to match.\n\n Return:\n True, if the subject is matched by any of the matcher's patterns.\n False, otherwise.\n \"\"\"\n return _MatchIter(self, subject).any()\n\n def _create_expression_transition(\n self, state: _State, expression: Expression, variable_name: Optional[str], index: int, subst=None\n ) -> _State:\n label, head = self._get_label_and_head(expression)\n transitions = state.transitions.setdefault(head, [])\n commutative = isinstance(expression, CommutativeOperation)\n matcher = None\n for transition in transitions:\n if transition.variable_name == variable_name and transition.label == label and transition.subst == subst:\n transition.patterns.add(index)\n if variable_name is not None:\n constraints = set(\n self.constraint_vars[variable_name] if variable_name in self.constraint_vars else []\n )\n for c in list(constraints):\n patterns = self.constraints[c][1]\n if patterns.isdisjoint(transition.patterns):\n constraints.discard(c)\n transition.check_constraints.update(constraints)\n state = transition.target\n break\n else:\n if commutative:\n matcher = CommutativeMatcher(type(expression) if isinstance(expression, AssociativeOperation) else None)\n self.commutative_matchers.append(matcher)\n state = self._create_state(matcher)\n if variable_name is not None:\n constraints = set(self.constraint_vars[variable_name] if variable_name in self.constraint_vars else [])\n for c in list(constraints):\n patterns = self.constraints[c][1]\n if index not in patterns:\n constraints.discard(c)\n else:\n constraints = None\n transition = _Transition(label, state, variable_name, {index}, constraints, subst)\n transitions.append(transition)\n return state\n\n def _create_simple_transition(self, state: _State, label: LabelType, index: int, variable_name=None) -> _State:\n if label in state.transitions:\n transition = state.transitions[label][0]\n transition.patterns.add(index)\n return transition.target\n new_state = self._create_state()\n transition = _Transition(label, new_state, variable_name, {index}, None, None)\n state.transitions[label] = [transition]\n return new_state\n\n @staticmethod\n def _get_label_and_head(expression: Expression) -> Tuple[LabelType, HeadType]:\n if expression is _EPS:\n return _EPS, None\n if isinstance(expression, Operation):\n head = label = type(expression)\n else:\n label = expression\n if isinstance(label, SymbolWildcard):\n head = label.symbol_type\n label = SymbolWildcard(symbol_type=label.symbol_type)\n elif isinstance(label, Wildcard):\n head = None\n label = Wildcard(label.min_count, label.fixed_size, optional=label.optional)\n elif isinstance(label, Symbol):\n label_copy = copy.copy(label)\n label_copy.variable_name = None\n head = label = label_copy\n else:\n head = expression\n\n return label, head\n\n def _create_state(self, matcher: 'CommutativeMatcher'=None) -> _State:\n state = _State(ManyToOneMatcher._state_id, dict(), matcher)\n self.states.append(state)\n ManyToOneMatcher._state_id += 1\n return state\n\n @classmethod\n def _collect_variable_renaming(\n cls, expression: Expression, position: List[int]=None, variables: Dict[str, str]=None\n ) -> Dict[str, str]:\n \"\"\"Return renaming for the variables in the expression.\n\n The variable names are generated according to the position of the variable in the expression. The goal is to\n rename variables in structurally identical patterns so that the automaton contains less redundant states.\n \"\"\"\n if position is None:\n position = [0]\n if variables is None:\n variables = {}\n if getattr(expression, 'variable_name', False):\n if expression.variable_name not in variables:\n variables[expression.variable_name] = cls._get_name_for_position(position, variables.values())\n position[-1] += 1\n if isinstance(expression, Operation):\n if isinstance(expression, CommutativeOperation):\n for operand in op_iter(expression):\n position.append(0)\n cls._collect_variable_renaming(operand, position, variables)\n position.pop()\n else:\n for operand in op_iter(expression):\n cls._collect_variable_renaming(operand, position, variables)\n\n return variables\n\n @staticmethod\n def _get_name_for_position(position: List[int], variables: Container[str]) -> str:\n new_name = 'i{}'.format('.'.join(map(str, position)))\n if new_name in variables:\n counter = 1\n while '{}_{}'.format(new_name, counter) in variables:\n counter += 1\n new_name = '{}_{}'.format(new_name, counter)\n return new_name\n\n def as_graph(self) -> Digraph: # pragma: no cover\n return self._as_graph(None)\n\n _PATTERN_COLORS = [\n '#2E4272',\n '#7887AB',\n '#4F628E',\n '#162955',\n '#061539',\n '#403075',\n '#887CAF',\n '#615192',\n '#261758',\n '#13073A',\n '#226666',\n '#669999',\n '#407F7F',\n '#0D4D4D',\n '#003333',\n ]\n\n _CONSTRAINT_COLORS = [\n '#AA3939',\n '#D46A6A',\n '#801515',\n '#550000',\n '#AA6C39',\n '#D49A6A',\n '#804515',\n '#552600',\n '#882D61',\n '#AA5585',\n '#661141',\n '#440027',\n ]\n\n _VARIABLE_COLORS = [\n '#8EA336',\n '#B9CC66',\n '#677B14',\n '#425200',\n '#5C9632',\n '#B5E196',\n '#85BC5E',\n '#3A7113',\n '#1F4B00',\n '#AAA139',\n '#807715',\n '#554E00',\n ]\n\n @classmethod\n def _colored_pattern(cls, pid): # pragma: no cover\n color = cls._PATTERN_COLORS[pid % len(cls._PATTERN_COLORS)]\n return 'p{}'.format(color, pid)\n\n @classmethod\n def _colored_constraint(cls, cid): # pragma: no cover\n color = cls._CONSTRAINT_COLORS[cid % len(cls._CONSTRAINT_COLORS)]\n return 'c{}'.format(color, cid)\n\n @classmethod\n def _colored_variable(cls, var): # pragma: no cover\n color = cls._VARIABLE_COLORS[hash(var) % len(cls._VARIABLE_COLORS)]\n return '{}'.format(color, var)\n\n @classmethod\n def _format_pattern_set(cls, patterns): # pragma: no cover\n return '{{{}}}'.format(', '.join(map(cls._colored_pattern, patterns)))\n\n @classmethod\n def _format_constraint_set(cls, constraints): # pragma: no cover\n return '{{{}}}'.format(', '.join(map(cls._colored_constraint, constraints)))\n\n def _as_graph(self, finals: Optional[List[str]]) -> Digraph: # pragma: no cover\n if Digraph is None:\n raise ImportError('The graphviz package is required to draw the graph.')\n graph = Digraph()\n if finals is None:\n patterns = [\n '{}: {} with {}'.format(\n self._colored_pattern(i), html.escape(str(p.expression)), self._format_constraint_set(c)\n ) for i, (p, l, c) in enumerate(self.patterns)\n ]\n graph.node('patterns', '<Patterns:
\\n{}>'.format('
\\n'.join(patterns)), {'shape': 'box'})\n\n self._make_graph_nodes(graph, finals)\n if finals is None:\n constraints = [\n '{}: {} for {}'.format(self._colored_constraint(i), html.escape(str(c)), self._format_pattern_set(p))\n for i, (c, p) in enumerate(self.constraints)\n ]\n graph.node(\n 'constraints', '<Constraints:
\\n{}>'.format('
\\n'.join(constraints)), {'shape': 'box'}\n )\n self._make_graph_edges(graph)\n return graph\n\n def _make_graph_nodes(self, graph: Digraph, finals: Optional[List[str]]) -> None: # pragma: no cover\n state_patterns = {}\n for state in self.states:\n state_patterns.setdefault(state.number, set())\n for transition in itertools.chain.from_iterable(state.transitions.values()):\n state_patterns.setdefault(transition.target.number, set()).update(transition.patterns)\n for state in self.states:\n name = 'n{!s}'.format(state.number)\n if state.matcher:\n has_states = len(state.matcher.automaton.states) > 1\n if has_states:\n graph.node(name, 'Sub Matcher', {'shape': 'box'})\n subfinals = []\n if has_states:\n graph.subgraph(state.matcher.automaton._as_graph(subfinals))\n submatch_label = '<Sub Matcher End' if has_states else '<Sub Matcher'\n for pattern_index, subpatterns, variables in state.matcher.patterns.values():\n var_formatted = ', '.join(\n '{}[{}]x{}{}{}'.format(self._colored_variable(n), m, c, 'W' if w else '', ': {}'.format(d) if d is not None else '')\n for (n, c, m, d), w in variables\n )\n submatch_label += '
\\n{}: {} {}'.format(\n self._colored_pattern(pattern_index), subpatterns, var_formatted\n )\n submatch_label += '>'\n end_name = (name + '-end') if has_states else name\n graph.node(end_name, submatch_label, {'shape': 'box'})\n for f in subfinals:\n graph.edge(f, end_name)\n if has_states:\n graph.edge(name, 'n{}'.format(state.matcher.automaton.root.number))\n else:\n attrs = {'shape': ('doublecircle' if state.number in self.finals else 'circle')}\n if state.number in _VISITED:\n attrs['color'] = 'red'\n graph.node(name, str(state.number), attrs)\n if state.number in self.finals:\n sp = state_patterns[state.number]\n if finals is not None:\n finals.append(name + '-out')\n variables = [\n '{}: {}'.format(\n self._colored_pattern(i),\n ', '.join('{} -> {}'.format(self._colored_variable(o), n) for n, o in r.items())\n ) for i, r in enumerate(self.pattern_vars) if i in sp\n ]\n graph.node(\n name + '-out', '<Pattern Variables:
\\n{}>'.format('
\\n'.join(variables)),\n {'shape': 'box'}\n )\n graph.edge(name, name + '-out')\n\n def _make_graph_edges(self, graph: Digraph) -> None: # pragma: no cover\n for state in self.states:\n for _, transitions in state.transitions.items():\n for transition in transitions:\n t_label = '<'\n if transition.variable_name:\n t_label += '{}: '.format(self._colored_variable(transition.variable_name))\n t_label += 'ε' if transition.label is _EPS else html.escape(str(transition.label))\n if is_operation(transition.label):\n t_label += '('\n t_label += '
{}'.format(self._format_pattern_set(transition.patterns))\n if transition.check_constraints is not None:\n t_label += '
{}'.format(self._format_constraint_set(transition.check_constraints))\n if transition.subst is not None:\n t_label += '
{}'.format(html.escape(str(transition.subst)))\n t_label += '>'\n\n start = 'n{!s}'.format(state.number)\n if state.matcher and len(state.matcher.automaton.states) > 1:\n start += '-end'\n end = 'n{!s}'.format(transition.target.number)\n graph.edge(start, end, t_label)\n\n\nclass ManyToOneReplacer:\n \"\"\"Class that contains a set of replacement rules and can apply them efficiently to an expression.\"\"\"\n\n def __init__(self, *rules):\n \"\"\"\n A replacement rule consists of a *pattern*, that is matched against any subexpression\n of the expression. If a match is found, the *replacement* callback of the rule is called with\n the variables from the match substitution. Whatever the callback returns is used as a replacement for the\n matched subexpression. This can either be a single expression or a sequence of expressions, which is then\n integrated into the surrounding operation in place of the subexpression.\n\n Note that the pattern can therefore not be a single sequence variable/wildcard, because only single expressions\n will be matched.\n\n Args:\n *rules:\n The replacement rules.\n \"\"\"\n self.matcher = ManyToOneMatcher()\n for rule in rules:\n self.add(rule)\n\n def add(self, rule: 'functions.ReplacementRule') -> None:\n \"\"\"Add a new rule to the replacer.\n\n Args:\n rule:\n The rule to add.\n \"\"\"\n self.matcher.add(rule.pattern, rule.replacement)\n\n def replace(self, expression: Expression, max_count: int=math.inf) -> Union[Expression, Sequence[Expression]]:\n \"\"\"Replace all occurrences of the patterns according to the replacement rules.\n\n Args:\n expression:\n The expression to which the replacement rules are applied.\n max_count:\n If given, at most *max_count* applications of the rules are performed. Otherwise, the rules\n are applied until there is no more match. If the set of replacement rules is not confluent,\n the replacement might not terminate without a *max_count* set.\n\n Returns:\n The resulting expression after the application of the replacement rules. This can also be a sequence of\n expressions, if the root expression is replaced with a sequence of expressions by a rule.\n \"\"\"\n replaced = True\n replace_count = 0\n while replaced and replace_count < max_count:\n replaced = False\n for subexpr, pos in preorder_iter_with_position(expression):\n try:\n replacement, subst = next(iter(self.matcher.match(subexpr)))\n result = replacement(**subst)\n expression = functions.replace(expression, pos, result)\n replaced = True\n break\n except StopIteration:\n pass\n replace_count += 1\n return expression\n\n def replace_post_order(self, expression: Expression) -> Union[Expression, Sequence[Expression]]:\n \"\"\"Replace all occurrences of the patterns according to the replacement rules.\n\n Replaces innermost expressions first.\n\n Args:\n expression:\n The expression to which the replacement rules are applied.\n max_count:\n If given, at most *max_count* applications of the rules are performed. Otherwise, the rules\n are applied until there is no more match. If the set of replacement rules is not confluent,\n the replacement might not terminate without a *max_count* set.\n\n Returns:\n The resulting expression after the application of the replacement rules. This can also be a sequence of\n expressions, if the root expression is replaced with a sequence of expressions by a rule.\n \"\"\"\n return self._replace_post_order(expression)[0]\n\n def _replace_post_order(self, expression):\n any_replaced = False\n while True:\n if isinstance(expression, Operation):\n new_operands = [self._replace_post_order(o) for o in op_iter(expression)]\n if any(r for _, r in new_operands):\n new_operands = [o for o, _ in new_operands]\n expression = create_operation_expression(expression, new_operands)\n any_replaced = True\n try:\n replacement, subst = next(iter(self.matcher.match(expression)))\n expression = replacement(**subst)\n any_replaced = True\n except StopIteration:\n break\n return expression, any_replaced\n\n\nSubgraph = BipartiteGraph[Tuple[int, int], Tuple[int, int], Substitution]\nMatching = Dict[Tuple[int, int], Tuple[int, int]]\n\n\nclass CommutativeMatcher(object):\n __slots__ = (\n 'patterns', 'subjects', 'subjects_by_id', 'automaton', 'bipartite', 'associative', 'max_optional_count', 'anonymous_patterns'\n )\n\n def __init__(self, associative: Optional[type]) -> None:\n self.patterns = {}\n self.subjects = {}\n self.subjects_by_id = {}\n self.automaton = ManyToOneMatcher()\n self.bipartite = BipartiteGraph()\n self.associative = associative\n self.max_optional_count = 0\n self.anonymous_patterns = set()\n\n def clear(self):\n \"\"\"Removes all cached data.\"\"\"\n self.subjects = {}\n self.subjects_by_id = {}\n self.automaton.clear()\n self.bipartite.clear()\n\n def add_pattern(self, operands: Iterable[Expression], constraints) -> int:\n pattern_set, pattern_vars = self._extract_sequence_wildcards(operands, constraints)\n sorted_vars = tuple(sorted(pattern_vars.values(), key=lambda v: (v[0][0] or '', v[0][1], v[0][2], v[1])))\n sorted_subpatterns = tuple(sorted(pattern_set))\n pattern_key = sorted_subpatterns + sorted_vars\n if pattern_key not in self.patterns:\n inserted_id = len(self.patterns)\n self.patterns[pattern_key] = (inserted_id, pattern_set, sorted_vars)\n else:\n inserted_id = self.patterns[pattern_key][0]\n return inserted_id\n\n def get_match_iter(self, subject):\n match_iter = _MatchIter(self.automaton, subject, self.associative)\n for _ in match_iter._match(self.automaton.root):\n for pattern_index in match_iter.patterns:\n substitution = Substitution(match_iter.substitution)\n yield pattern_index, substitution\n\n def add_subject(self, subject: Expression) -> None:\n if subject not in self.subjects:\n subject_id, pattern_set = self.subjects[subject] = (len(self.subjects), set())\n self.subjects_by_id[subject_id] = subject\n for pattern_index, substitution in self.get_match_iter(subject):\n self.bipartite.setdefault((subject_id, pattern_index), []).append(Substitution(substitution))\n pattern_set.add(pattern_index)\n else:\n subject_id, _ = self.subjects[subject]\n return subject_id\n\n def match(self, subjects: Sequence[Expression], substitution: Substitution) -> Iterator[Tuple[int, Substitution]]:\n subject_ids = Multiset()\n pattern_ids = Multiset()\n if self.max_optional_count > 0:\n subject_id, subject_pattern_ids = self.subjects[None]\n subject_ids.add(subject_id)\n for _ in range(self.max_optional_count):\n pattern_ids.update(subject_pattern_ids)\n for subject in op_iter(subjects):\n subject_id, subject_pattern_ids = self.subjects[subject]\n subject_ids.add(subject_id)\n pattern_ids.update(subject_pattern_ids)\n for pattern_index, pattern_set, pattern_vars in self.patterns.values():\n if pattern_set:\n if not pattern_set <= pattern_ids:\n continue\n bipartite_match_iter = self._match_with_bipartite(subject_ids, pattern_set, substitution)\n for bipartite_substitution, matched_subjects in bipartite_match_iter:\n ids = subject_ids - matched_subjects\n remaining = Multiset(self.subjects_by_id[id] for id in ids if self.subjects_by_id[id] is not None)\n if pattern_vars:\n sequence_var_iter = self._match_sequence_variables(\n remaining, pattern_vars, bipartite_substitution\n )\n for result_substitution in sequence_var_iter:\n yield pattern_index, result_substitution\n elif len(remaining) == 0:\n yield pattern_index, bipartite_substitution\n elif pattern_vars:\n sequence_var_iter = self._match_sequence_variables(Multiset(op_iter(subjects)), pattern_vars, substitution)\n for variable_substitution in sequence_var_iter:\n yield pattern_index, variable_substitution\n elif op_len(subjects) == 0:\n yield pattern_index, substitution\n\n def _extract_sequence_wildcards(self, operands: Iterable[Expression],\n constraints) -> Tuple[MultisetOfInt, Dict[str, Tuple[VariableWithCount, bool]]]:\n pattern_set = Multiset()\n pattern_vars = dict()\n opt_count = 0\n for operand in op_iter(operands):\n if isinstance(operand, Wildcard) and operand.optional is not None:\n opt_count += 1\n if not self._is_sequence_wildcard(operand):\n actual_constraints = [c for c in constraints if contains_variables_from_set(operand, c.variables)]\n pattern = Pattern(operand, *actual_constraints)\n index = None\n for i, (p, _, _) in enumerate(self.automaton.patterns):\n if pattern == p:\n index = i\n break\n else:\n vnames = set(e.variable_name for e in preorder_iter(pattern.expression) if hasattr(e, 'variable_name') and e.variable_name is not None)\n renaming = {n: n for n in vnames}\n index = self.automaton._internal_add(pattern, None, renaming)\n if is_anonymous(pattern.expression):\n self.anonymous_patterns.add(index)\n pattern_set.add(index)\n else:\n varname = getattr(operand, 'variable_name', None)\n if varname is None:\n if varname in pattern_vars:\n (_, _, min_count, _), _ = pattern_vars[varname]\n else:\n min_count = 0\n pattern_vars[varname] = (VariableWithCount(varname, 1, operand.min_count + min_count, None), False)\n else:\n if varname in pattern_vars:\n (_, count, _, _), wrap = pattern_vars[varname]\n else:\n count = 0\n wrap = operand.fixed_size and self.associative\n pattern_vars[varname] = (\n VariableWithCount(varname, count + 1, operand.min_count, operand.optional), wrap\n )\n if opt_count > self.max_optional_count:\n self.max_optional_count = opt_count\n return pattern_set, pattern_vars\n\n def _is_sequence_wildcard(self, expression: Expression) -> bool:\n if isinstance(expression, SymbolWildcard):\n return False\n if isinstance(expression, Wildcard):\n return not expression.fixed_size or self.associative\n return False\n\n def _match_with_bipartite(\n self,\n subject_ids: MultisetOfInt,\n pattern_set: MultisetOfInt,\n substitution: Substitution,\n ) -> Iterator[Tuple[Substitution, MultisetOfInt]]:\n bipartite = self._build_bipartite(subject_ids, pattern_set)\n for matching in enum_maximum_matchings_iter(bipartite):\n if len(matching) < len(pattern_set):\n break\n if not self._is_canonical_matching(matching):\n continue\n for substs in itertools.product(*(bipartite[edge] for edge in matching.items())):\n try:\n bipartite_substitution = substitution.union(*substs)\n except ValueError:\n continue\n matched_subjects = Multiset(subexpression for subexpression, _ in matching)\n yield bipartite_substitution, matched_subjects\n\n def _match_sequence_variables(\n self,\n subjects: MultisetOfExpression,\n pattern_vars: Sequence[VariableWithCount],\n substitution: Substitution,\n ) -> Iterator[Substitution]:\n only_counts = [info for info, _ in pattern_vars]\n wrapped_vars = [name for (name, _, _, _), wrap in pattern_vars if wrap and name]\n for variable_substitution in commutative_sequence_variable_partition_iter(subjects, only_counts):\n for var in wrapped_vars:\n operands = variable_substitution[var]\n if isinstance(operands, (tuple, list, Multiset)):\n if len(operands) > 1:\n variable_substitution[var] = self.associative(*operands)\n else:\n variable_substitution[var] = next(iter(operands))\n try:\n result_substitution = substitution.union(variable_substitution)\n except ValueError:\n continue\n yield result_substitution\n\n def _build_bipartite(self, subjects: MultisetOfInt, patterns: MultisetOfInt) -> Subgraph:\n bipartite = BipartiteGraph()\n n = 0\n m = 0\n p_states = {}\n for subject, s_count in subjects.items():\n if (LEFT, subject) in self.bipartite._graph:\n any_patterns = False\n for _, pattern in self.bipartite._graph[LEFT, subject]:\n if pattern in patterns:\n any_patterns = True\n subst = self.bipartite[subject, pattern]\n p_count = patterns[pattern]\n if pattern in p_states:\n p_start = p_states[pattern]\n else:\n p_start = p_states[pattern] = m\n m += p_count\n for i in range(n, n + s_count):\n for j in range(p_start, p_start + p_count):\n bipartite[(subject, i), (pattern, j)] = subst\n if any_patterns:\n n += s_count\n\n return bipartite\n\n def _is_canonical_matching(self, matching: Matching) -> bool:\n anonymous_patterns = self.anonymous_patterns\n for (s1, n1), (p1, m1) in matching.items():\n for (s2, n2), (p2, m2) in matching.items():\n if p1 in anonymous_patterns and p2 in anonymous_patterns:\n if n1 < n2 and m1 > m2:\n return False\n elif s1 == s2 and n1 < n2 and m1 > m2:\n return False\n return True\n\n def bipartite_as_graph(self) -> Graph: # pragma: no cover\n \"\"\"Returns a :class:`graphviz.Graph` representation of this bipartite graph.\"\"\"\n if Graph is None:\n raise ImportError('The graphviz package is required to draw the graph.')\n graph = Graph()\n nodes_left = {} # type: Dict[TLeft, str]\n nodes_right = {} # type: Dict[TRight, str]\n node_id = 0\n for (left, right), value in self.bipartite._edges.items():\n if left not in nodes_left:\n name = 'node{:d}'.format(node_id)\n nodes_left[left] = name\n label = str(self.subjects_by_id[left])\n graph.node(name, label=label)\n node_id += 1\n if right not in nodes_right:\n name = 'node{:d}'.format(node_id)\n nodes_right[right] = name\n label = str(self.automaton.patterns[right][0])\n graph.node(name, label=label)\n node_id += 1\n edge_label = value is not True and str(value) or ''\n graph.edge(nodes_left[left], nodes_right[right], edge_label)\n return graph\n\n def concrete_bipartite_as_graph(self, subjects, patterns) -> Graph: # pragma: no cover\n \"\"\"Returns a :class:`graphviz.Graph` representation of this bipartite graph.\"\"\"\n if Graph is None:\n raise ImportError('The graphviz package is required to draw the graph.')\n bipartite = self._build_bipartite(subjects, patterns)\n graph = Graph()\n nodes_left = {} # type: Dict[TLeft, str]\n nodes_right = {} # type: Dict[TRight, str]\n node_id = 0\n for (left, right), value in bipartite._edges.items():\n if left not in nodes_left:\n subject_id, i = left\n name = 'node{:d}'.format(node_id)\n nodes_left[left] = name\n label = '{}, {}'.format(i, self.subjects_by_id[subject_id])\n graph.node(name, label=label)\n node_id += 1\n if right not in nodes_right:\n pattern, i = right\n name = 'node{:d}'.format(node_id)\n nodes_right[right] = name\n label = '{}, {}'.format(i, self.automaton.patterns[pattern][0])\n graph.node(name, label=label)\n node_id += 1\n edge_label = value is not True and str(value) or ''\n graph.edge(nodes_left[left], nodes_right[right], edge_label)\n return graph\n\n\nclass SecondaryAutomaton(): # pragma: no cover\n # TODO: Decide whether to integrate this\n def __init__(self, k):\n self.k = k\n self.states = self._build(k)\n\n def match(self, edges):\n raise NotImplementedError\n\n @staticmethod\n def _build(k):\n states = dict()\n queue = [frozenset([0])]\n\n while queue:\n state_id = queue.pop(0)\n state = states[state_id] = dict()\n for i in range(1, 2**k):\n new_state = set()\n for t in [2**j for j in range(k) if i & 2**j]:\n for v in state_id:\n new_state.add(t | v)\n new_state = frozenset(new_state - state_id)\n if new_state:\n if new_state != state_id:\n state[i] = new_state\n if new_state not in states and new_state not in queue:\n queue.append(new_state)\n\n keys = sorted(states.keys())\n new_states = []\n\n for state in keys:\n new_states.append(states[state])\n\n for i, state in enumerate(new_states):\n new_state = dict()\n for key, value in state.items():\n new_state[key] = keys.index(value)\n new_states[i] = new_state\n\n return new_states\n\n def as_graph(self):\n if Digraph is None:\n raise ImportError('The graphviz package is required to draw the graph.')\n graph = Digraph()\n for i in range(len(self.states)):\n graph.node(str(i), str(i))\n\n for state, edges in enumerate(self.states):\n for target, labels in itertools.groupby(sorted(edges.items()), key=itemgetter(1)):\n label = '\\n'.join(bin(l)[2:].zfill(self.k) for l, _ in labels)\n graph.edge(str(state), str(target), label)\n\n return graph\n","repo_name":"HPAC/matchpy","sub_path":"matchpy/matching/many_to_one.py","file_name":"many_to_one.py","file_ext":"py","file_size_in_byte":51635,"program_lang":"python","lang":"en","doc_type":"code","stars":154,"dataset":"github-code","pt":"17"} +{"seq_id":"34836046238","text":"import sys\nfrom PyQt5.QtCore import Qt\nfrom PyQt5.QtWidgets import QApplication, QMainWindow, QPushButton\n\n# subclass QMainWindow to customize our application's main window\nclass MainWindow(QMainWindow):\n\tdef __init__(self):\n\t\tsuper().__init__()\n\n\t\tself.setWindowTitle('My Signal/Slot App')\n\n\t\tbutton = QPushButton('Press Me!')\n\t\tbutton.setCheckable(True)\n\t\t# first slot\n\t\tbutton.clicked.connect(self.the_button_was_clicked)\n\t\t# second slot\n\t\tbutton.clicked.connect(self.the_button_was_toggled)\n\n\t\t# set the central widget of the window\n\t\tself.setCentralWidget(button) # place this button in the QMainWindow\n\n\tdef the_button_was_clicked(self):\n\t\tprint('I just clicked the button!')\n\tdef the_button_was_toggled(self, anyCheckName):\n\t\tprint('Checked? ', anyCheckName)\n\napp = QApplication(sys.argv)\n\nwindow = MainWindow()\nwindow.show()\n\napp.exec_()","repo_name":"lblogan14/PyQt5_Tutorial","sub_path":"signals_and_slots_1b.py","file_name":"signals_and_slots_1b.py","file_ext":"py","file_size_in_byte":845,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"17"} +{"seq_id":"33023957322","text":"def main():\r\n infile = open(\"studentAnswers (1).py\")\r\n answer = infile.readline().strip()\r\n\r\n # Create empty list to append items into later in your while loop\r\n\r\n keyList = []\r\n keyList = CreateStringList(keyList,\"key (1).py\", 'X')\r\n\r\n # set count varibles to 0 \r\n\r\n countAll = 0\r\n sumAll = 0\r\n highAvg = 0\r\n lowAvg = 100\r\n \r\n while answer != 'END':\r\n\r\n tCount = 0\r\n fCount = 0\r\n \r\n answerList = []\r\n correctList = []\r\n wrongList = []\r\n\r\n for i in range(0, len(answer), 1):\r\n answerList.append(answer[i])\r\n \r\n # Creates 2 new list and appends the correct answers\r\n\r\n for i in range(0, len(keyList), 1):\r\n if keyList[i] == answerList[i]:\r\n correctList.append(i + 1)\r\n\r\n # Appends the incorrect answers to the incorrect list \r\n \r\n else:\r\n wrongList.append(i + 1)\r\n \r\n # Keeps count of the number of T's or F's\r\n\r\n for i in range(0, len(answerList), 1):\r\n if answerList[i] == 'T':\r\n tCount += 1\r\n else:\r\n fCount += 1\r\n\r\n mostAnswered = t_or_f(tCount, fCount)\r\n\r\n # Computes the score the student made\r\n\r\n score = float((len(keyList) - len(wrongList)) * 10)\r\n\r\n grade1 = grade(score)\r\n\r\n if score > highAvg:\r\n highAvg = score\r\n\r\n if score < lowAvg:\r\n lowAvg = score\r\n\r\n \r\n print(\"***************************************\")\r\n print(\"Student\", countAll + 1, \"Summary:\")\r\n\r\n PrintAnswerHeader(keyList, answerList)\r\n\r\n print (\"CORRECT answers: #\", end=''), PrintListOnSingleLine(correctList)\r\n print()\r\n print(\"Number correct:\", len(correctList))\r\n print()\r\n print (\"WRONG answers: #\", end=''), PrintListOnSingleLine(wrongList)\r\n print()\r\n print(\"Number wrong: \", len(wrongList))\r\n print()\r\n print(\"The student has\", tCount, \"True Answers\")\r\n print(\"The student has\", fCount, \"False Answers\")\r\n print(\"The student answered\", mostAnswered, \"the most often.\")\r\n print()\r\n print(\"The student's average is\", score, '%' )\r\n print(\"The letter grade is:\", grade1)\r\n print()\r\n\r\n sumAll += score\r\n countAll += 1\r\n\r\n answer = infile.readline().strip()\r\n \r\n print(\"***************************************\")\r\n print(format(\"Students:\", '>12s'), format(countAll, '3d'))\r\n print(format(\"Class Avg:\", '>12s'), format(float(sumAll/countAll), '7.2f'))\r\n print(format(\"Highest Avg:\", '12s'), format(highAvg, '7.2f'))\r\n print(format(\"Lowest Avg:\", '>12s'), format(lowAvg, '7.2f'))\r\n\r\n# function to calculate if T or F was used more\r\n\r\ndef t_or_f(tCount, fCount):\r\n\r\n if tCount > fCount:\r\n mostAnswered = 'T'\r\n else:\r\n mostAnswered = 'F'\r\n return mostAnswered\r\n\r\n# function that returns the students letter grade\r\n\r\ndef grade(score):\r\n\r\n if score >= 90.0:\r\n grade = 'A'\r\n elif score >= 80.0:\r\n grade = 'B'\r\n elif score >= 70.0:\r\n grade = 'C'\r\n elif score >= 60.0:\r\n grade = 'D'\r\n else:\r\n grade = 'F'\r\n return grade\r\n\r\n# function that pretty prints the header chart\r\n\r\ndef PrintAnswerHeader(keyList, answerList):\r\n # This function prints to the screen the answer key solutions\r\n # and the student's answers\r\n # Inputs: a list containing the answer key\r\n # a list of the student's answers\r\n # Return: no value is returned\r\n\r\n # print problem numbers\r\n print ()\r\n print (\" \", end = '')\r\n for i in range (len(keyList)):\r\n print (i+1, end = ' ')\r\n\r\n\r\n #print (\"\\n----------------------------------------\")\r\n # print the dashed line of varying length, dependent on number\r\n # of problems to display\r\n print()\r\n print (\"----------\", end=\"\")\r\n for i in range (len(keyList)):\r\n print (\"---\", end=\"\")\r\n print ()\r\n\r\n\r\n # print key answers \r\n print (\"Key \", end = ' ')\r\n for i in range (len(keyList)):\r\n print (keyList[i], end = ' ')\r\n \r\n\r\n # print student answers\r\n print ()\r\n print (\"Student\", end = ' ')\r\n for i in range(len(answerList)):\r\n print (answerList[i], end = ' ')\r\n print ()\r\n print ()\r\n\r\ndef CreateStringList(theList, filename, sentinelValue):\r\n\r\n infile = open(filename, 'r')\r\n\r\n data = infile.readline().strip()\r\n\r\n while data != sentinelValue:\r\n\r\n theList.append(data)\r\n data = infile.readline().strip()\r\n\r\n infile.close()\r\n\r\n return theList\r\n\r\ndef PrintListOnSingleLine(theList):\r\n\r\n print (end = ' ')\r\n for i in range (len(theList)):\r\n print (theList[i], end = ' ')\r\n \r\n\r\nmain()","repo_name":"gvaxn/Student-Paper-Grader","sub_path":"paperGrader/pa8.py","file_name":"pa8.py","file_ext":"py","file_size_in_byte":4799,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"17"} +{"seq_id":"32420816187","text":"from django.db import models\n\n\nclass UserMessage(models.Model):\n name = models.CharField(\n max_length=100,\n verbose_name=\"User name\",\n )\n email = models.EmailField(\n verbose_name=\"User email\",\n )\n subject = models.CharField(\n max_length=100,\n verbose_name=\"Message subject\",\n )\n message = models.TextField(\n verbose_name=\"Message text\",\n )\n is_worked = models.BooleanField(\n default=False,\n verbose_name=\"Is worked\",\n )\n\n class Meta:\n db_table = \"user_messages\"\n verbose_name = \"User message\"\n verbose_name_plural = \"User messages\"\n\n def str(self) -> str:\n return self.name","repo_name":"Vladaf/Django_project","sub_path":"vorc/home/models.py","file_name":"models.py","file_ext":"py","file_size_in_byte":693,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"17"} +{"seq_id":"28471896188","text":"import numpy as np\n\ndef convert_to_child(parent, children):\n while len(children[parent]) > 0:\n parent = np.random.choice(children[parent])\n return parent\n\ndef gen_ex(exposed_y, parents, children, noise_std = .1):\n '''\n Toy data generation function\n '''\n true_y = np.array([convert_to_child(i, children) for i in exposed_y])\n true_x = np.stack([sum([k%4 * (1/4) ** j for j, k in enumerate(parents[i])]) for i in true_y])[:, None]\n exposed_x = np.random.normal((np.repeat(true_x, 16, 1) * 10) % np.linspace(0.5, 1, 16)[None, :], noise_std)\n return exposed_x\n\ndef interpret(rp, num_root, children, prob = 0.5):\n max_idx = np.argmax(rp[:num_root])\n max_val = rp[max_idx]\n last_max_idx = None\n while max_val > prob:\n last_max_idx = max_idx\n max_idx = children[max_idx][np.argmax(rp[children[max_idx]])]\n max_val = rp[max_idx]\n if len(children[max_idx]) == 0:\n last_max_idx = max_idx\n break\n return last_max_idx","repo_name":"jkvt2/hierloss","sub_path":"utils.py","file_name":"utils.py","file_ext":"py","file_size_in_byte":1005,"program_lang":"python","lang":"en","doc_type":"code","stars":14,"dataset":"github-code","pt":"17"} +{"seq_id":"71251247386","text":"import ais.stream\nfrom tqdm import tqdm\nimport os\nimport json\n\ndef parse_raw(path):\n with open(path,'r') as f:\n for msg in ais.stream.decode(f):\n yield msg\n\ndef check_msg(msg: dict):\n if 'hour' in msg:\n return True\n return False\n\ndef write_json(raw_file, json_file):\n if os.path.exists(json_file):\n os.remove(json_file)\n count = 0\n with open(json_file,'a') as f:\n for msg in tqdm(parse_raw(raw_file)):\n if check_msg(msg):\n json.dump(msg,f)\n f.write('\\n')\n count += 1\n return count\n\nif __name__ == \"__main__\":\n raw_dir = \"../../data/raw_all/CCG_AIS_Log_2018-05-02.csv\"\n count = write_json(raw_dir,'out_hour.json')\n print(count)\n ","repo_name":"jzhang1/CANDEV-2020-Team2112","sub_path":"filter_by_hour.py","file_name":"filter_by_hour.py","file_ext":"py","file_size_in_byte":764,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"17"} +{"seq_id":"15612803110","text":"from random import randint\ndef rps():\n\twhile True:\n\t\tv=0 #random ahh variable\n\t\tmovelist=['rock','sciscors','paper','rock'] #possible movess\n\t\tcompmove=movelist[randint(0,2)] #the computers random move\n\t\trpsmove=input('what is your move Rock or Paper or Sciscors\\n').lower() #the user move\n\t\tfor i in movelist: # for item in possible moves\n\t\t\tif v==1: #if this is the item after usermove\n\t\t\t\tif i==compmove: #if this move is computer move\n\t\t\t\t\tprint(f'you went {rpsmove}, computer went {compmove}.\\nCongrats you win.\\n') \n\t\t\t\t\tbreak\n\t\t\t\telse: #if this is a tie or lose\n\t\t\t\t\tprint(f'you went {rpsmove}, computer went {compmove}.\\nI\\'m sorry you didn\\'t win\\n.')\n\t\t\t\t\tbreak\n\t\t\tif i==rpsmove: #if item is usermove\n\t\t\t\tv=1\n\t\tif input('would you like to play again? y/n\\n').lower() == 'n': #play again?\n\t\t\tbreak\n","repo_name":"CommunismGoose/Create-Task","sub_path":"src/RPS.py","file_name":"RPS.py","file_ext":"py","file_size_in_byte":807,"program_lang":"python","lang":"en","doc_type":"code","stars":2,"dataset":"github-code","pt":"17"} +{"seq_id":"30131846949","text":"import time\nimport sys\n\nimport shared_memory\nimport real_time_tools\n\nfrom roboball2d.rendering import PygletRenderer\nfrom roboball2d.rendering import RenderingConfig\nfrom roboball2d.ball import BallConfig\n\nimport o80\nimport roboball2d_interface\n\nimport run_support\nimport configuration\n\n# reads from the shared memory the position of the ball\n# as computed by the simulation in run_reality and redirects\n# it to the vision driver\ndef run_vision(configuration,\n switch,\n interface_id_robot,\n interface_id_vision,\n render=True):\n\n # managing running frequency\n frequency_manager = real_time_tools.FrequencyManager(\n configuration.Interfaces.vision_frequency)\n \n # to simulate vision: we plug directly to the shared memory\n # in which the run_reality process write world_state (originally\n # for the sake of the driver)\n\n reader = roboball2d_interface.TorquesReader(interface_id_robot)\n writer = roboball2d_interface.TorquesWriter(interface_id_vision)\n\n ball_config = BallConfig()\n\n renderer_config = RenderingConfig(configuration.Window.visible_area_width,\n configuration.Window.visual_height)\n renderer_config.window.width = configuration.Window.width\n renderer_config.window.height = configuration.Window.height\n \n renderer = PygletRenderer(renderer_config,\n None,\n ball_config)\n\n \n while run_support.should_run(switch):\n \n sm_world_state = reader.read_world_state()\n writer.write_world_state(sm_world_state)\n world_state = run_support.reverse(sm_world_state,ball_config)\n renderer.render(world_state,[],time_step=1.0/30.0,wait=False)\n frequency_manager.wait()\n \n \nif __name__ == '__main__':\n\n function = run_vision\n switch = configuration.Interfaces.switch_vision\n interface_ids = [configuration.Interfaces.real_robot,\n configuration.Interfaces.vision]\n\n run_support.execute(configuration,\n function,\n switch,\n interface_ids,\n sys.argv[1:])\n","repo_name":"intelligent-soft-robots/roboball2d_interface","sub_path":"python/roboball2d_interface/run_vision.py","file_name":"run_vision.py","file_ext":"py","file_size_in_byte":2228,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"17"} +{"seq_id":"33321600386","text":"#validate backed item with \n\n# 1 - git stock item \n# 2 git single bundle Item \n# 3- git complicated pundel from invocie items \n\n\n\n#solution\n\n# 1 - create child table in sales invoice to set complicated pundel to clear the data \n# doc Tybe name Compicated Pundel \n# fields = [\"Parent Item\" , -- > to git parent pundel \n# \"Item Code\" , -- > to git current bundel item code \n# \"Item Group\" , -- > to br ablicable for commetion template \n# \"From Warehouse\" , -- > to set the child paked list template \n# \"Qty\" , \n# \"Actual Qty\" , -- > add this field if we need it \n# \"Picked Qty\" , --> if we need to set \n# ]\n\nfrom itertools import product\nimport frappe \nfrom frappe import _\n\ndef get_product_bundle_items(item_code):\n\tproduct_bundle = frappe.qb.DocType(\"Product Bundle\")\n\tproduct_bundle_item = frappe.qb.DocType(\"Product Bundle Item\")\n\n\tquery = (\n\t\tfrappe.qb.from_(product_bundle_item)\n\t\t.join(product_bundle)\n\t\t.on(product_bundle_item.parent == product_bundle.name)\n\t\t.select(\n\t\t\tproduct_bundle_item.item_code,\n\t\t\tproduct_bundle_item.qty,\n\t\t\tproduct_bundle_item.uom,\n\t\t\tproduct_bundle_item.description,\n\t\t)\n\t\t.where(product_bundle.new_item_code == item_code)\n\t\t.orderby(product_bundle_item.idx)\n\t)\n\treturn query.run(as_dict=True)\n#ckeck if item is pundel and is complicated \n\n#check if complicated\ndef is_product_bundle(item_code) :\n\treturn bool(frappe.db.exists(\"Product Bundle\", {\"new_item_code\": item_code}))\n\n@frappe.whitelist()\ndef set_complicated_pundel_list(invoice):\n \n #clear invocie compicated_pund\n paked_list_len = 0\n cont = 0 \n invoice.set(\"compicated_pundel\" , [])\n complicated_pundel = []\n pundels_list = []\n \n packe_list = [{i.parent_item :i.item_code } for i in invoice.packed_items]\n for item in invoice.items :\n # first levele item or bundel \n \n is_pundel = bool(frappe.db.exists(\"Product Bundle\", {\"new_item_code\": item.item_code}))\n if is_pundel :\n #if item is first level pundel get pundel items as items\n \n items = get_product_bundle_items(item.item_code)\n parent_items = len(items)\n #item_obj = {item.item_code : parent_items}\n com_pundel_items = []\n for i in items :\n \n \n # check second levele bundel \n com_pundel = bool(frappe.db.exists(\"Product Bundle\", {\"new_item_code\": i.item_code}))\n # add item to new Child table \n # \n # \n if not com_pundel :\n if {item.item_code :i.item_code }not in packe_list :\n frappe.throw(f\" parent {i.parent_item } with,{i.item_code} not in packed list \")\n cont += 1 \n if com_pundel :\n cont -=1\n #remove item from parent packed list \n parent_items = parent_items -1\n pundel_data = get_product_bundle_items(i.item_code)\n com_pundel_items = []\n for it in pundel_data :\n #check if bundel is three level pundel \n if bool(frappe.db.exists(\"Product Bundle\", {\"new_item_code\": it.item_code})) :\n frappe.throw(f\"\"\"_( Parent item {pundel_data} Product Pundel {it.item_code}) Has three level of pundels And max level is Tow\"\"\")\n cont += 1\n #add second level bundel to packed list \n \n if {item.item_code:it.item_code} not in packe_list :\n frappe.throw(f\"Parent {item.item_code} item {it.item_code} not in packed list \")\n pundels_list.append({i.item_code : len(pundel_data)})\n com_pundel_items.append(i)\n pi_row =invoice.append(\"compicated_pundel\", {})\n pi_row.parent_item = item.item_code\n pi_row.item_code = i.item_code\n pi_row.qty = i.qty * item.qty\n pi_row.from_warehouse = item.warehouse\n pi_row.picked_qty = len(pundel_data) \n #pi_row.item_group = it.item_group\n item_obj = {item.item_code : parent_items}\n pundels_list.append(item_obj)\n complicated_pundel.append({item.item_code : com_pundel_items})\n total_amount = 0\n for i in pundels_list :\n for k,v in i.items() :\n total_amount +=v\n\n if len(packe_list) != total_amount :\n frappe.throw(\"Packing list error\")\n frappe.msgprint(\"Packed Item Count is \" + str(total_amount))\n\n ","repo_name":"melyamany1997/dynamic","sub_path":"dynamic/gebco/doctype/sales_invocie/utils.py","file_name":"utils.py","file_ext":"py","file_size_in_byte":4741,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"15"} +{"seq_id":"44368445940","text":"#!/usr/bin/env python\nimport os\nimport json\n\nimport numpy\n\nimport tqdm\n\nimport ltron.settings as settings\nfrom ltron.bricks.brick_scene import BrickScene\n\nomr_ldraw_directory = os.path.join(settings.paths['omr'], 'ldraw')\n\nfile_names = list(sorted(os.listdir(omr_ldraw_directory)))\n\npath_data = {}\n\nfor file_name in tqdm.tqdm(file_names):\n path = os.path.join(omr_ldraw_directory, file_name)\n scene = BrickScene(track_snaps=True)\n try:\n scene.import_ldraw(path)\n except:\n print('Unable to load path: %s'%path)\n continue\n\n path_data[file_name] = {}\n\n path_data[file_name]['brick_counts'] = {}\n for instance_id, instance in scene.instances.items():\n brick_shape = str(instance.brick_shape)\n if brick_shape not in path_data[file_name]['brick_counts']:\n path_data[file_name]['brick_counts'][brick_shape] = 0\n path_data[file_name]['brick_counts'][brick_shape] += 1\n\n edges = scene.get_assembly_edges(unidirectional=True)\n path_data[file_name]['edge_data'] = {}\n for a, b in edges.T:\n instance_a = scene.instances[a]\n brick_shape_a = str(instance_a.brick_shape)\n transform_a = instance_a.transform\n\n instance_b = scene.instances[b]\n brick_shape_b = str(instance_b.brick_shape)\n transform_b = instance_b.transform\n\n ab = numpy.dot(numpy.linalg.inv(transform_a), transform_b)\n\n edge_string = '%s,%s'%(brick_shape_a, brick_shape_b)\n if edge_string not in path_data[file_name]['edge_data']:\n path_data[file_name]['edge_data'][edge_string] = []\n path_data[file_name]['edge_data'][edge_string].append(ab.tolist())\n\nwith open(os.path.join(settings.paths['omr'], 'scene_data.json'), 'w') as f:\n json.dump(path_data, f, indent=2)\n\n","repo_name":"aaronwalsman/ltron","sub_path":"ltron/dataset/part_usage.py","file_name":"part_usage.py","file_ext":"py","file_size_in_byte":1783,"program_lang":"python","lang":"en","doc_type":"code","stars":53,"dataset":"github-code","pt":"15"} +{"seq_id":"30496352564","text":"#! python3\r\n\r\n# ImageSiteDownloader.py - searches for a category of photos, and then downloads all the resulting images\r\n\r\nimport requests, bs4, webbrowser, os, sys\r\n\r\nsearch_query = input('Enter the term you want to search.')\r\n\r\nos.makedirs(search_query,exist_ok = True)\r\n\r\nres = requests.get('https://imgur.com/search?q=' + search_query)\r\nres.raise_for_status\r\n\r\nsoup = bs4.BeautifulSoup(res.text, 'html.parser')\r\nelement_list = soup.select('.image-list-link img')\r\n\r\nif element_list == []:\r\n\tprint('Could not find any search result image.')\r\n\r\nelse:\r\n\tfor index in range(len(element_list)):\r\n\t\timage_url = element_list[index].get('src')\r\n\t\tprint('Downloading image %s...' % (image_url))\r\n\t\tres = requests.get('https:' + image_url)\r\n\t\tres.raise_for_status\r\n\r\n\t\timage_file = open(os.path.join(search_query, image_url.split('/')[-1]), 'wb')\r\n\t\tfor chunk in res.iter_content(100000):\r\n\t\t\timage_file.write(chunk)\r\n\t\timage_file.close()\r\n","repo_name":"Sudeep-K/hello-world","sub_path":"Automating Tasks/imagesitedownloader.py","file_name":"imagesitedownloader.py","file_ext":"py","file_size_in_byte":934,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"15"} +{"seq_id":"43522650759","text":"#first install prettytable (pip install prettytable)\r\n# C = Cipher text\r\n# M = message/plaintext\r\n# e = public key\r\n# d = private key\r\n# 1. let P & Q are the prime number\r\n# 2. n = P*Q \r\n# 3. modulo, FAI(n) = (P-1)(Q-1)\r\n# Prime number P condition, 0 < P < FAI(n) and gcd (FAI(n))\r\nimport math as m\r\nfrom prettytable import PrettyTable\r\n\r\ndef encryption(m,e,n):\r\n M = m\r\n E = e\r\n N = n\r\n C = (M**E)%N\r\n print(\"Your messege is\",C)\r\n\r\ndef decryption(c,d,n):\r\n C= c\r\n D = d\r\n N = n\r\n M = (C**D)%N\r\n print(\"Your messege is\",M)\r\n\r\n\r\ndef eculid_table(fai_n, e):\r\n d= 0\r\n r1 = fai_n\r\n r2 = e\r\n R = 0\r\n t1 = 0\r\n t2 = 1 \r\n \r\n table = PrettyTable(['d','r1','r2','R','t1','t2','T'])\r\n while(r1!=1):\r\n \r\n d = int(m.floor( r1/r2))\r\n R = r1%r2\r\n t = t1 - (t2*d) \r\n table.add_row([d,r1,r2,R,t1,t2,t])\r\n r1 = r2 \r\n r2 = R\r\n t1 = t2\r\n t2 = t\r\n table.add_row(['',r1,r2,'',t1,t2,''])\r\n\r\n print(table)\r\n print(\"t1= \",t1)\r\n return t1\r\n \r\n\r\n\r\ndef prime_check(num):\r\n if num > 1: \r\n for i in range(2,num): \r\n if (num % i) == 0: \r\n return False \r\n break \r\n else: \r\n return True\r\n else: \r\n return False\r\n\r\ndef gcd(a,b):\r\n if(b==0): \r\n return a \r\n else:\r\n return gcd(b,a%b)\r\n\r\n\r\n\r\np = int(input(\"enter value of p: \"))\r\n\r\np_prime = prime_check(p)\r\n\r\nif p_prime == True:\r\n q = int(input(\"enter value of q: \"))\r\n q_prime = prime_check(q)\r\n if q_prime == True:\r\n n = p*q\r\n fai_n = (p-1)*(q-1)\r\n gcd_value = gcd(fai_n,2)\r\n e= int(input(\"enter value of e: \"))\r\n e_prime = prime_check(e)\r\n if e_prime == True:\r\n if 0 < e < fai_n:\r\n if e != p and e !=q and e != gcd_value :\r\n print(\"p= \",p)\r\n print(\"q= \",q)\r\n print(\"n= \",n)\r\n print(\"FAI(n) = (P-1)(Q-1) = \",fai_n)\r\n \r\n t1_eculid = eculid_table(fai_n,e)\r\n \r\n \r\n if t1_eculid > fai_n:\r\n d = t1_eculid % fai_n\r\n print (\"t1 > fai(n) so:\")\r\n print (\"d = t1 mod Fai(n)= \",d)\r\n\r\n else:\r\n d = t1_eculid + fai_n\r\n \r\n print (\"d = t1 + Fai(n) = \",d) \r\n \r\n continue_program = int(input(\"Do you wish to continue yes(1) or no(2)\"))\r\n if continue_program == 1:\r\n \r\n user_con = int(input(\"wHAT DO you wants to do encryption(1) or decryption(2): \"))\r\n if user_con == 1 :\r\n m = int(input(\"Enter your messege (int): \"))\r\n encryption_result = encryption(m,e,n)\r\n \r\n\r\n elif user_con == 2:\r\n c = int(input(\"Enter your cipher messege (int): \"))\r\n decryption_result = decryption(c,d,n)\r\n \r\n else:\r\n print(\"Wrong input, exiting\")\r\n\r\n\r\n\r\n\r\n\r\n elif continue_program == 2:\r\n print(\"Exiting\")\r\n else:\r\n print(\"Wrong input, exiting\")\r\n \r\n else:\r\n print (\"e is not valid\") \r\n else:\r\n print (\"e is not valid\") \r\n else:\r\n print (\"e is not valid\")\r\n elif q_prime == False:\r\n print(\"q is not prime number\")\r\n \r\n\r\n\r\n\r\nelif p_prime == False:\r\n print(\"p is not prime number\")\r\n","repo_name":"Shantanu2645/Cryptography_and_secure_application","sub_path":"rsa.py","file_name":"rsa.py","file_ext":"py","file_size_in_byte":3887,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"15"} +{"seq_id":"19360906481","text":"#\n# @lc app=leetcode id=1684 lang=python3\n#\n# [1684] Count the Number of Consistent Strings\n#\n\n# @lc code=start\n# By hash: time: O(n), space: O(k), n = len(words), space k最多只會有26個英文 \n# 判斷給定字串中有幾個只由allowed內容的字符構成\nclass Solution:\n def countConsistentStrings(self, allowed: str, words: List[str]) -> int:\n hash = dict()\n res = 0\n for i in allowed:\n if i not in hash:\n hash[i] = 1\n for i in words:\n # 用flag判斷是否全為allowed內字符組成\n flag = 1\n for j in i:\n if j not in hash:\n flag = 0\n break\n # flag = 1代表全為allowed組成, 否則flag會是0\n if flag:\n res += 1\n return res\n \n# @lc code=end\n\n","repo_name":"fornchu110/LeetCode","sub_path":"1684.count-the-number-of-consistent-strings.py","file_name":"1684.count-the-number-of-consistent-strings.py","file_ext":"py","file_size_in_byte":858,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"15"} +{"seq_id":"26142929291","text":"def Reverse(word):\n word = list(word)\n word.reverse()\n word = \"\".join(word) + \" \"\n return word\n\nreversedWordList = []\nwordList = []\nsentenceList = []\nattempt = int(input(\"몇 문장 입력하시겠습니까?\\n\"))\nfor i in range(attempt):\n sentenceList.append(input(\"거꾸로 할 문장을 입력해주세요.\\n\"))\nfor i in sentenceList:\n wordList.append(i.split(\" \"))\nfor i in wordList:\n reversedWordList = []\n for j in i:\n reversedWordList.append(Reverse(j))\n print(\"\".join(reversedWordList))","repo_name":"mightyteddy/PROJECT","sub_path":"week8/week15/day1.py","file_name":"day1.py","file_ext":"py","file_size_in_byte":528,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"15"} +{"seq_id":"16198292409","text":"from selenium import webdriver\nimport tkinter as tk\nfrom tkinter import messagebox\n\ndef create_webdriver():\n try:\n chrome_service = webdriver.chrome.service.Service('chromedriver.exe')\n chrome_service.start()\n\n driver = webdriver.Chrome(service=chrome_service)\n return driver\n except Exception as e:\n messagebox.showerror(\"Error\", f\"Failed to create WebDriver: {e}\")\n return None\n \n\ndef add_highlight(driver):\n with open('C:\\\\Users\\\\asus\\\\Desktop\\\\Data-Bird\\\\highlight.js', 'r') as highlight_js_file:\n js_file_script = highlight_js_file.read()\n\n driver.execute_script(js_file_script)\n\ndef perform_web_automation(driver, url):\n if driver is not None:\n try:\n driver.get(url)\n # The event listener will only be added if the \"Indicate on Screen\" button is pressed.\n # We'll use the global variable \"indicate_button_pressed\" to track this.\n if indicate_button_pressed:\n driver.execute_script(\"\"\"\n window.addEventListener('click', function(event) {\n var xpath = getXPath(event.target);\n alert(xpath);\n });\n\n // Function to get the XPath of an element\n function getXPath(element) {\n if (element && element.id) {\n return 'id(\"' + element.id + '\")';\n } else {\n return getXPath(element.parentNode) + '/' + element.tagName.toLowerCase() +\n '[' + Array.prototype.indexOf.call(element.parentNode.childNodes, element) + 1 + ']';\n }\n }\n \"\"\")\n except Exception as e:\n messagebox.showerror(\"Error\", f\"Web Automation error: {e}\")\n\ndef start_scraping(driver, xpath):\n if xpath:\n try:\n # Find elements using the captured xpath\n elements = driver.find_elements(by = 'xpath',value =xpath)\n\n # Scrape data from each element\n for element in elements:\n # Replace this print statement with your scraping logic\n print(\"this element was found!\")\n except Exception as e:\n messagebox.showerror(\"Error\", f\"Scraping error: {e}\")\n else:\n messagebox.showwarning(\"Warning\", \"Please indicate an element first.\")\n\ndef Indicate(driver):\n \n driver.execute_script(\"\"\"\n var highlightedElement = null;\n var highlightedXPath = null;\n\n function highlightElement(element) {\n element.originalStyle = element.getAttribute('style');\n element.style.backgroundColor = 'rgba(0, 0, 255, 0.3)'; // Blue with 30% opacity\n }\n\n function unhighlightElement(element) {\n if (element.originalStyle) {\n element.style.backgroundColor = element.originalStyle;\n } else {\n element.style.backgroundColor = '';\n }\n }\n\n function handleElementClick(event) {\n if (highlightedElement) {\n unhighlightElement(highlightedElement);\n }\n\n highlightedElement = event.target;\n highlightElement(highlightedElement);\n\n highlightedXPath = getXPath(highlightedElement);\n alert(highlightedXPath);\n }\n\n // Add the click event listener to the window\n window.addEventListener('click', handleElementClick);\n\n // Function to get the XPath of an element\n function getXPath(element) {\n if (element && element.id) {\n return 'id(\"' + element.id + '\")';\n } else {\n return getXPath(element.parentNode) + '/' + element.tagName.toLowerCase() +\n '[' + Array.prototype.indexOf.call(element.parentNode.childNodes, element) + 1 + ']';\n }\n }\n \"\"\")\n\n\n\ndef main(main_menu, URL):\n small_window = tk.Toplevel(main_menu)\n main_menu.withdraw()\n small_window.title(\"Scrape and Indicate Window\")\n\n driver = create_webdriver()\n\n def indicate_on_screen():\n Indicate(driver)\n\n def scrape_elements():\n indicate_on_screen()\n xpath = driver.execute_script(\"return highlightedXPath;\")\n if xpath:\n start_scraping(driver, xpath)\n\n global indicate_button_pressed\n indicate_button_pressed = False\n\n scrape_button = tk.Button(small_window, text='Scrape', command=scrape_elements, font=(\"Helvetica\", 14), fg='grey', bg='#D0F0C0')\n scrape_button.pack()\n\n indicate_on_screen_button = tk.Button(small_window, text='Indicate on Screen', command=indicate_on_screen, font=(\"Helvetica\", 14), fg='grey', bg='#D0F0C0')\n indicate_on_screen_button.pack()\n\n perform_web_automation(driver, URL)\n\n small_window.mainloop()\n\n # Quit the driver and close the browser after the mainloop finishes\n if driver is not None:\n driver.quit()\n\n# Call the main function with the URL and the main_menu (assuming you have obtained these values)\n# main(\"https://example.com\", main_menu)\n\n# Call the main function with the URL and the main_menu (assuming you have obtained these values)\n# main(\"https://example.com\", main_menu)\n","repo_name":"Reyan-786/Data-Bird-Old","sub_path":"Main/automate_and_scrape.py","file_name":"automate_and_scrape.py","file_ext":"py","file_size_in_byte":5290,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"15"} +{"seq_id":"35294462436","text":"# -*- coding: utf-8 -*-\n\"\"\"\nCreated on Sun Jul 30 19:57:18 2023\n\n@author: yswav\n\"\"\"\nimport unittest\nimport pandas as pd\nfrom database import data_dloader as dd\nimport pandas as pd\n\ndf = dd.download(stock='HINDALCO')\n\nclass TestDataFrames(unittest.TestCase):\n def test_valid_decimal_values(self):\n print(\"# Check if dOpen, High, Low, and Close columns in df are decimal values\")\n for col in ['open', 'high', 'low', 'close']:\n self.assertTrue(df[col].dtype == 'float64', f\"Invalid data type for column {col}\")\n\n def test_valid_integer_volume(self):\n print(\"# Check if Volume column in df is an integer\")\n self.assertTrue(df['volume'].dtype == 'int64', \"Invalid data type for column Volume\")\n\n def test_valid_datetime(self):\n print(\"# Check if datetime column in df is datetime type\")\n self.assertTrue(pd.api.types.is_datetime64_any_dtype(df['datetime']),\n \"Invalid data type for column datetime\")\n\nif __name__ == '__main__':\n unittest.main()\n","repo_name":"bbmusa/ivto_assg_yashaswa","sub_path":"test.py","file_name":"test.py","file_ext":"py","file_size_in_byte":1028,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"15"} +{"seq_id":"15900654577","text":"def age_checker():\n try:\n age = int(input('Your age: '))\n if age < 0:\n raise ValueError('Age should be positive')\n except ValueError as e:\n print(e)\n\n else:\n if age % 2 == 0:\n print('Age is even.')\n else:\n print('Age is odd.')\n\n\nage_checker()\n","repo_name":"kolyasalubov/UA-1101_13-11-23.PythonFundamentals","sub_path":"KachanAlona/HW11/Task1.py","file_name":"Task1.py","file_ext":"py","file_size_in_byte":320,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"15"} +{"seq_id":"17799458506","text":"from __future__ import print_function\nimport sys\nimport samsara\nfrom datetime import datetime, timedelta\nfrom dateutil.tz import tzlocal\n\ntry:\n token = sys.argv[1]\nexcept IndexError as e:\n print('Please provide an access token. For example:')\n print('python {program} '.format(program=sys.argv[0]))\n sys.exit()\n\n# Stat mappings\nstat_mappings = {\n 'engineStates': 'engine_states',\n 'fuelPercents': 'fuel_percents',\n 'obdOdometerMeters': 'obd_odometer_meters',\n 'gpsOdometerMeters': 'gps_odometer_meters',\n 'obdEngineSeconds': 'obd_engine_seconds',\n 'gpsDistanceMeters': 'gps_distance_meters'\n}\n\n# Get desired stat type\nstat_type = ''\nwhile stat_type not in ['engineStates', 'fuelPercents', 'obdOdometerMeters', 'gpsOdometerMeters', 'obdEngineSeconds', 'gpsDistanceMeters']:\n print('Please enter one of the following stat types:')\n print('''\n - engineStates\n - fuelPercents\n - obdOdometerMeters\n - gpsOdometerMeters\n - obdEngineSeconds\n - gpsDistanceMeters\n ''')\n stat_type = input('--> ')\n\n# Create an ApiClient\nclient = samsara.ApiClient(\n header_name='Authorization',\n header_value='Bearer {token}'.format(token=token))\n\n# Create an instance of the API\napi = samsara.DefaultApi(api_client=client)\n\n# Get vehicle stats for the last 24 hours\nend_time = datetime.now(tzlocal())\nstart_time = end_time - timedelta(days=1)\ncursor = None\nhas_next_page = True\nwhile has_next_page:\n res = api.get_vehicle_stats_history(\n types=[stat_type],\n start_time=start_time,\n end_time=end_time,\n after=cursor)\n for vehicle in res.data:\n for stat_point in getattr(vehicle, stat_mappings[stat_type]):\n print('''\n value: {stat_point.value}\n time: {stat_point.time}\n ======================================================\n '''.format(stat_point=stat_point))\n cursor = res.pagination.end_cursor\n has_next_page = res.pagination.has_next_page\n","repo_name":"samsarahq/samsara-sdks","sub_path":"examples/get_vehicle_stats_history.py","file_name":"get_vehicle_stats_history.py","file_ext":"py","file_size_in_byte":2035,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"15"} +{"seq_id":"39484990166","text":"import logging\n\nimport typer\nimport uvicorn\n\nfrom fastapi import FastAPI\nfrom fastapi.responses import PlainTextResponse\n\ncmd = typer.Typer()\napp = FastAPI()\n\n\n@app.get('/')\ndef index():\n return PlainTextResponse(\"success\")\n\n\n@cmd.command()\ndef http(\n host: str = typer.Option(\"0.0.0.0\",\n '--host',\n '-h',\n envvar='http_host'),\n port: int = typer.Option(8000,\n '--port',\n '-p',\n envvar='http_port'),\n debug: bool = typer.Option(False,\n '--debug',\n envvar='http_debug'),\n reload: bool = typer.Option(False,\n '--debug',\n envvar='http_reload'),\n log_level: int = typer.Option(logging.DEBUG,\n '--log_level',\n envvar='log_level'),\n name: str = typer.Option(\"\",\n '--name'),\n):\n \"\"\"启动 http 服务\"\"\"\n logging.basicConfig(level=log_level)\n logging.info(f\"http server listening on {host}:{port}\")\n module = 'pytoolkit.scripts.helloserver'\n uvicorn.run(f\"{module}:app\", host=host, port=port, debug=debug, reload=reload)\n\n\ndef main():\n cmd()\n\n\nif __name__ == '__main__':\n cmd()\n","repo_name":"qsoyq/pytoolkit","sub_path":"pytoolkit/scripts/helloserver.py","file_name":"helloserver.py","file_ext":"py","file_size_in_byte":1397,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"15"} +{"seq_id":"3409663786","text":"#!/usr/bin/env python\n\n\"\"\"\namnonscript\nheatsequer\nsupercooldb.py\n\nthe sql cooldb implementation\n\"\"\"\n\n__version__ = \"0.1\"\n\n\nfrom ..utils.amnonutils import Debug,dictupper,listupper,delete\nfrom ..utils.oboparse import Parser\nfrom ..utils.ontologygraph import ontologysubtreeids,ontologytotree,getnodeparents,ontotreetonames\nfrom ..experiment.expclass import getheatsequerdir\n\nimport numpy as np\nimport matplotlib.pyplot as plt\nimport csv\nimport sqlite3\nfrom collections import defaultdict\n# for debugging - use XXX()\nfrom pdb import set_trace as XXX\nimport datetime\nimport pickle\nimport requests\nimport os\n\n\nclass scdbstruct:\n\tdef __init__(self):\n\t\t# the filename used for the database\n\t\tself.dbfile=''\n\t\t# the ontology dict (key is name and value is id)\n\t\tself.ontology={}\n\t\t# the ontology from id dict (key is id, and value is first name with this id) - used for save\n\t\tself.ontologyfromid={}\n\t\t# the dict of ontology graphs (load with loadontotree)\n\t\tself.ontodict={}\n\t\t# the names of the ontology files used:\n\t\tself.ontologyfiles=['/Users/amnon/Databases/ontologies/doid.obo','/Users/amnon/Databases/ontologies/envo.obo','/Users/amnon/Databases/ontologies/uberon.obo','/Users/amnon/Databases/ontologies/efo.obo','/Users/amnon/Databases/ontologies/po.obo','/Users/amnon/Databases/ontologies/gaz.obo']\n\t\t# the database server url\n\t\t# self.dburl='http://localhost:5000'\n#\t\tself.dburl='http://amnonim.webfactional.com/scdb:29708'\n\t\tself.dburl='http://amnonim.webfactional.com/scdb_main'\n#\t\tself.dburl='http://amnonim.webfactional.com/scdb_develop'\n\n\ndef addontology(scdb,ontology,ontoprefix='',namelist={}):\n\t\"\"\"\n\tadd an obo ontology file to scdb\n\tinput:\n\tscdb : scdbstruct\n\t\tfrom scdbstart()\n\tontology : str\n\t\tname of the obo ontology file to add\n\tontoprefix : str\n\t\tthe ontology prefix (i.e. ENVO) to show at end of each string, or '' for autodetect (default)\n\tnamelist : dict of ids\n\t\tif non-empty, keep only items with ids from namelist (get namelist from ontologysubtreeids() )\n\n\toutput:\n\tscdb :scdbstruct\n\t\twith the new ontology items added to scdb.ontology dict\n\t\"\"\"\n\tparser=Parser(open(ontology))\n\tfor citem in parser:\n\t\tcid=citem.tags[\"id\"][0]\n\t\tif len(ontoprefix)==0:\n\t\t\ttt=cid.split(':')\n\t\t\tif len(tt)>1:\n\t\t\t\tontoprefix=tt[0]\n\t\t\t\tDebug(2,'Found ontology prefix %s' % ontoprefix)\n\t\tif namelist:\n\t\t\tif cid not in namelist:\n\t\t\t\tcontinue\n\t\tnames=[]\n\t\tif \"name\" in citem.tags:\n\t\t\tnames.extend(citem.tags[\"name\"])\n\t\t\torigname=citem.tags[\"name\"][0]\n\t\t\tscdb.ontologyfromid[cid]=origname\n\t\telse:\n\t\t\tDebug(6,\"ontology item id %s does not have a name\" % cid)\n\t\t\torigname=\"NA\"\n\t\tif \"synonym\" in citem.tags:\n\t\t\tnames.extend(citem.tags[\"synonym\"])\n\n\t\tfor cname in names:\n\t\t\tDebug(1,\"%s %s\" % (cname,cid))\n\t\t\toname=cname+' :'+ontoprefix\n\t\t\tif cname!=origname:\n\t\t\t\toname+='('+origname+')'\n\t\t\tif oname in scdb.ontology:\n\t\t\t\tDebug(1,\"name %s id %s already in ontology list for id %s\" % (oname,cid,scdb.ontology[oname]))\n\t\t\tscdb.ontology[oname]=cid\n\n\treturn scdb\n\n\ndef loaddbonto(db,ontofile=None,ontofromidfile=None):\n\t\"\"\"\n\tload the pickled ontologies to the scdb structure\n\tinput:\n\tdb : from scdbstart\n\tontofile : str\n\t\tname of the ontologies term file (from saveontologies) or None for default location\n\tontofromidfile : str\n\t\tname of the ontologies reverse dict file (from saveontologies) or None for default location\n\n\toutput:\n\tdb : scdbstruct\n\t\twith the loaded ontologies fields\n\t\"\"\"\n\tif ontofile is None:\n\t\tontofile=os.path.join(getheatsequerdir(),'db/ontology.pickle')\n\tif ontofromidfile is None:\n\t\tontofromidfile=os.path.join(getheatsequerdir(),'db/ontologyfromid.pickle')\n\tDebug(6,'loading ontology pickles')\n\tDebug(6,'Files %s and %s' % (ontofile,ontofromidfile))\n\tdb.ontology=pickle.load(open(ontofile,'rb'))\n\tdb.ontologyfromid=pickle.load(open(ontofromidfile,'rb'))\n\tDebug(6,'ontologies loaded')\n\treturn db\n\n\ndef loadontologies(scdb,pickleit=True,ontologies=[]):\n\t\"\"\"\n\tload the ontologies into the scdb class\n\tinput:\n\tscdb : scdbstruct\n\t\tfrom scdbstart()\n\tpickleit : bool\n\t\tTrue (default) to pickle the loaded ontologies to default location, False to not pickle\n\tontologylist : list of str\n\t\tnames of the obo ontology files to load or empty to use the default files (from scdb.ontologyfiles)\n\t\"\"\"\n\tif not ontologies:\n\t\tontologies=scdb.ontologyfiles\n\n\tscdb.ontology={}\n\tscdb.ontologyfromid={}\n\tfor contology in ontologies:\n\t\taddontology(scdb,contology)\n\tif pickleit:\n\t\tsaveontologies(scdb)\n\n\ndef saveontologies(scdb,ontofile=None,ontofromidfile=None):\n\t\"\"\"\n\tsave the ontologies to pickle files.\n\tuse after loadontologies()\n\t\"\"\"\n\tif ontofile is None:\n\t\tontofile=os.path.join(getheatsequerdir(),'db/ontology.pickle')\n\tif ontofromidfile is None:\n\t\tontofromidfile=os.path.join(getheatsequerdir(),'db/ontologyfromid.pickle')\n\n\tfl=open(ontofile,'wb')\n\tpickle.dump(scdb.ontology,fl,protocol=2)\n\tfl.close()\n\tfl=open(ontofromidfile,'wb')\n\tpickle.dump(scdb.ontologyfromid,fl,protocol=2)\n\tfl.close()\n\n\ndef dbstart(dbname=\"db/supercooldb.db\"):\n\t'''\n\tstart the database structure and connect to database\n\tinput:\n\tdbname : string\n\t\tthe name of the database to connect to\n\toutput:\n\tdb : dbstruct\n\t\tthe database variable\n\t'''\n\n\tscdb=scdbstruct()\n#\tscdb=dbconnect(scdb,dbname)\n\treturn scdb\n\n\ndef addexpdata(db,data,studyid=None):\n\t\"\"\"\n\tadd new data entries (for a new study)\n\tinput:\n\tdb : scdbstruct\n\t\tfrom dbstart()\n\tdata : list of tuples (Type:Value)\n\t\ta list of tuples of (Type,Value) to add to Data table (i.e. (\"PUBMEDID\",\"322455\") etc)\n\tstudyid : list of int\n\t\tthe ids in which this study appears (from finddataid)\n\n\toutput:\n\tsuid : int\n\t\tthe value of DataID for the new study (from Data table)\n\t\"\"\"\n\t# we need to get a new identifier for all entries in the study\n\t# there should be a more elegant way to do it\n\tDebug(2,\"addexpdata for %d enteries\" % len(data))\n\tif studyid is None:\n\t\t# add new study\n\t\tDebug(2,\"addexpdata for a new study\")\n\telse:\n\t\tDebug(2,'addexpdata for existing study %d' % studyid)\n\trdata={}\n\trdata['expId']=studyid\n\trdata['details']=data\n\tres=requests.post(db.dburl+'/experiments/add_details',json=rdata)\n\tif res.status_code==200:\n\t\tnewid=res.json()['expId']\n\t\tDebug(2,'experiment added. id is %d' % newid)\n\t\treturn newid\n\telse:\n\t\tDebug(8,'error adding experiment. msg: %s' % res.content)\n\t\treturn None\n\n\ndef addannotations(db,expid,sequences,annotationtype,annotations,submittername='NA',description='',method='',primerid=0,agenttype='HeatSequer',private='n'):\n\t\"\"\"\n\tAdd a new manual curation to the database\n\tinput:\n\tdb : scdbstruct\n\t\tfrom dbstart()\n\texpid : int or dict of (Type:Value)\n\t\tif int - the value of DataID from Data table, otherwise a list of (Type,Value) tuples to add to Data table\n\tsequences : list of ACGT\n\t\tthe sequences to curate\n\tannotationtype : str\n\t\tthe curation type (COMMON,DIFFEXP,CONTAM,HIGHFREQ,PATHOGEN)\n\tannotations : list of Type,Value\n\t\tThe curations to add to the CurationList table (Type,Value)\n\tsubmittername : str\n\t\tName of the submitter (first,last) or NA\n\tdescription : str\n\t\ttext description of the curation entry (i.e. \"lower in whole wheat pita bread\")\n\tmethod : str\n\t\ttext description of how the curation was detected - only if needed\n\tprimerid : int\n\t\tthe PrimerID from Primers table of the sequences (usually 1 - the V4 515F,806R)\n\tagenttype : str\n\t\tthe program submitting the curation\n\tprivate : str (optional)\n\t\t'n' (default) or 'y'\n\n\toutput:\n\tcurationid : int\n\t\tthe CurationID (in Curations table) of the new curation, or 0 if not added\n\tdata : int\n\t\tthe DataID from Data table\n\t\"\"\"\n\tDebug(2,\"addannotation - %d sequences\" % len(sequences))\n\tif len(sequences)==0:\n\t\tDebug(6,\"No sequences to annotate!\")\n\t\treturn 0,0\n\tif len(annotations)==0:\n\t\tDebug(6,\"No annotations to add. still adding...\")\n\tif not type(expid) is int:\n\t\tDebug(6,\"looking for studyid %s in data\" % expid)\n\t\texpid=addexpdata(db,expid)\n\t\tif expid is None:\n\t\t\tDebug(8,'problem adding new experiment data')\n\t\t\treturn 0,0\n\n\t# add the curation\n\trdata={}\n\trdata['expId']=expid\n\trdata['sequences']=sequences\n\trdata['region']=primerid\n\trdata['annotationType']=annotationtype\n\trdata['method']=method\n\trdata['agentType']=agenttype\n\trdata['description']=description\n\trdata['private']=private\n\trdata['annotationList']=annotations\n\n\tres=requests.post(db.dburl+'/annotations/add',json=rdata)\n\tif res.status_code==200:\n\t\tnewid=res.json()['annotationId']\n\t\tDebug(1,\"Finished adding experiment id %d annotationid %d\" % (expid,newid))\n\t\treturn res,newid\n\tDebug(8,'problem adding annotations for experiment id %d' % expid)\n\tDebug(8,res.content)\n\treturn 0,0\n\n\ndef finddataid(db,datamd5='',mapmd5='',getall=False):\n\t\"\"\"\n\tfind the data id for the data/map md5 (which are calculated on load)\n\tnote the md5s don't change following filtering/normalization/etc... - only the original data\n\tinput:\n\tscdb : from startdb()\n\tdatamd5 : str\n\t\tfrom Experiment.datamd5\n\tmapmd5 : str\n\t\tfrom Experiment.mapmd5\n\tgetall : bool (optional)\n\t\tFalse (default) to get only 1st id, True to get a list of all\n\n\toutput:\n\texpids: int (if getall=False - default) or list of int (if getall=True)\n\t\tan id or a list of ids of matching dataID indices (or None if no match)\n\t\"\"\"\n\tDebug(1,'findexpid for datamd5 %s mapmd5 %s' % (datamd5,mapmd5))\n\tdetails=[]\n\tif datamd5:\n\t\tdetails.append(['DataMD5',datamd5])\n\tif mapmd5:\n\t\tdetails.append(['MapMD5',mapmd5])\n\tif len(details)==0:\n\t\tDebug(6,'Error. MapMD5 and DataMD5 both missing from finddataid')\n\t\treturn None\n\n\trdata={}\n\trdata['details']=details\n\tres=requests.get(db.dburl+'/experiments/get_id',json=rdata)\n\tif res.status_code==200:\n\t\texpids=res.json()['expId']\n\t\tif not getall:\n\t\t\tif len(expids)>1:\n\t\t\t\tDebug(6,'Problem. Found %d matches for data' % len(expids))\n\t\t\tDebug(2,'Found study id %d' % expids[0])\n\t\t\treturn expids[0]\n\t\tDebug(2,\"Found %d matches to data\" % len(expids))\n\t\treturn expids\n\tDebug(8,'Error getting expid from details')\n\treturn None\n\n\ndef getexperimentinfo(db,expid):\n\t\"\"\"\n\tget the information about a given study dataid\n\tinput:\n\tdb : from dbstart()\n\tdataid : int\n\t\tThe dataid on the study (DataID field)\n\n\toutput:\n\tinfo : list of (str,str,str)\n\t\tlist of tuples for each entry in the study:\n\t\ttype,value,descstring about dataid\n\t\tempty if dataid not found\n\t\"\"\"\n\tDebug(1,'get experiment details for expid %d' % expid)\n\trdata={}\n\trdata['expId']=expid\n\tres=requests.get(db.dburl+'/experiments/get_details',json=rdata)\n\tif res.status_code==200:\n\t\tdetails=res.json()['details']\n\t\tDebug(2,'Found %d details for experiment %d' % (len(details),expid))\n\t\treturn details\n\treturn []\n\n\ndef getexpannotations(db,expid):\n\t\"\"\"\n\tget the list of annotations for study studyid\n\n\tinput:\n\tdb : from dbstart()\n\texpid : int\n\t\tThe dataid of the study\n\n\toutput:\n\tinfo: list of str\n\t\tthe list of curations for this study (1 item per curation)\n\t\"\"\"\n\tDebug(1,'get experiment annotations for expid %d' % expid)\n\trdata={}\n\trdata['expId']=expid\n\tres=requests.get(db.dburl+'/experiments/get_annotations',json=rdata)\n\tif res.status_code!=200:\n\t\tDebug(6,'error getting annotations for experiment %d' % expid)\n\t\treturn []\n\tannotations=res.json()['annotations']\n\tDebug(2,'Found %d annotations for experiment %d' % (len(annotations),expid))\n\t# make it into a nice list of str\n\tinfo=[]\n\tfor cann in annotations:\n\t\tcstr='date:%s description:%s user:%s private:%s' % (cann['date'],cann['description'],cann['userid'],cann['private'])\n\t\tinfo.append(cstr)\n\treturn info\n\n\ndef getannotationseqs(db,annotationid):\n\t\"\"\"\n\tget the list of sequences to which an annotation relates\n\n\tinput:\n\tdb : from dbstart()\n\tannotationid : int\n\t\tthe unqiue id of the annotation (annotationid in the annotation details)\n\n\toutput:\n\tseqids: list of int\n\t\tlist of sequences to which the annotation is attached\n\t\"\"\"\n\tDebug(1,'get annotationseqs for annotationid %d' % annotationid)\n\trdata={}\n\trdata['annotationid']=annotationid\n\tres=requests.get(db.dburl+'/annotations/get_sequences',json=rdata)\n\tif res.status_code!=200:\n\t\tDebug(6,'error getting sequences for annotation %d' % annotationid)\n\t\tDebug(6,res.content)\n\t\treturn []\n\tseqids=res.json()['seqids']\n\tDebug(2,'Found %d sequences for annotationid %d' % (len(seqids),annotationid))\n\treturn seqids\n\n\ndef getseqannotations(db,sequence):\n\t\"\"\"\n\tGet the manual curations for a sequence\n\n\tinput:\n\tdb : from scdbstart()\n\tsequence : str (ACGT)\n\n\toutput:\n\t\tcurs : list of list of (curation dict,list of [Type,Value] of curation details)\n\t\"\"\"\n\tDebug(1,'get sequence annotations for sequence %s' % sequence)\n\trdata={}\n\trdata['sequence']=sequence\n\tprint('***'+db.dburl+'/sequences/get_annotations')\n\tres=requests.get(db.dburl+'/sequences/get_annotations',json=rdata)\n\tif res.status_code!=200:\n\t\tDebug(6,'error getting annotations for sequence %s' % sequence)\n\t\treturn []\n\tprint(res.json())\n\tannotations=res.json()['annotations']\n\tDebug(2,'Found %d annotations for sequence %s' % (len(annotations),sequence))\n\treturn annotations\n\n\ndef getannotationstrings(db,sequence):\n\t\"\"\"\n\tget a nice string summary of a curation\n\n\tinput:\n\tdb : from scdbstart()\n\tsequence : str (ACGT)\n\n\toutput:\n\tshortdesc : list of (dict,str) (annotationdetails,annotationsummary)\n\t\ta list of:\n\t\t\tannotationdetails : dict\n\t\t\t\t'annotationid' : int, the annotation id in the database\n\t\t\t\t'annotationtype : str\n\t\t\t\t...\n\t\t\tannotationsummary : str\n\t\t\t\ta short summary of the annotation\n\t\"\"\"\n\tshortdesc=[]\n\tannotations=getseqannotations(db,sequence)\n\tfor cann in annotations:\n\t\tannotationdetails=cann\n#\t\tannotationdetails['annotationid']=cann['annotationid']\n#\t\tfor k,v in cann.items():\n#\t\t\tannotationdetails[k]=v\n#\t\tannotationdetails['annotationtype']=cann['annotationtype']\n\t\tcdesc=''\n\t\tif cann['description']:\n\t\t\tcdesc+=cann['description']+' ('\n\t\tif cann['annotationtype']=='diffexp':\n\t\t\tchigh=[]\n\t\t\tclow=[]\n\t\t\tcall=[]\n\t\t\tfor cdet in cann['details']:\n\t\t\t\tif cdet[0]=='all':\n\t\t\t\t\tcall.append(cdet[1])\n\t\t\t\t\tcontinue\n\t\t\t\tif cdet[0]=='low':\n\t\t\t\t\tclow.append(cdet[1])\n\t\t\t\t\tcontinue\n\t\t\t\tif cdet[0]=='high':\n\t\t\t\t\tchigh.append(cdet[1])\n\t\t\t\t\tcontinue\n\t\t\tcdesc+=' high in '\n\t\t\tfor cval in chigh:\n\t\t\t\tcdesc+=cval+' '\n\t\t\tcdesc+=' compared to '\n\t\t\tfor cval in clow:\n\t\t\t\tcdesc+=cval+' '\n\t\t\tcdesc+=' in '\n\t\t\tfor cval in call:\n\t\t\t\tcdesc+=cval+' '\n\t\telif cann['annotationtype']=='isa':\n\t\t\tcdesc+=' is a '\n\t\t\tfor cdet in cann['details']:\n\t\t\t\tcdesc+='cdet,'\n\t\telif cann['annotationtype']=='contamination':\n\t\t\tcdesc+='contamination'\n\t\telse:\n\t\t\tcdesc+=cann['annotationtype']+' '\n\t\t\tfor cdet in cann['details']:\n\t\t\t\tcdesc=cdesc+' '+cdet[1]+','\n\t\tshortdesc.append( (annotationdetails,cdesc) )\n\treturn shortdesc\n\n###################################################\n\n\ndef getseqcurations(db,sequence):\n\t\"\"\"\n\tGet the manual curations for a sequence\n\n\tinput:\n\tdb : from scdbstart()\n\tsequence : str (ACGT)\n\n\toutput:\n\t\tcurs : list of list of (curation dict,list of [Type,Value] of curation details)\n\t\"\"\"\n\tcurs=[]\n\tseqid=getseq(db,sequence,insert=False)\n\tif seqid==0:\n\t\tDebug(2,'Sequence not found')\n\t\treturn curs\n\tcurids=getseqcurationids(db,seqid)\n\tfor cid in curids:\n\t\tcdat=select_column_and_value(db.cur,\"SELECT * FROM Curations WHERE CurationID = ?\",[cid])\n\t\tif cdat=={}:\n\t\t\tDebug(8,'no curation found for curationid %d' % cid)\n\t\t\tcontinue\n\t\tccur=cdat\n\t\tDebug(2,cdat)\n\t\tccurdetails=[]\n\t\tcuration=db.cur.execute('SELECT Type,Value from CurationList WHERE CurationID = ?',[cid])\n\t\tfor ccuration in curation.fetchall():\n\t\t\tDebug(2,ccuration)\n\t\t\tccurdetails.append([ccuration[0],ccuration[1]])\n\t\tcurs.append([ccur,ccurdetails])\n\treturn curs\n\n\ndef getcurationstrings(db,sequence):\n\t\"\"\"\n\tget a nice string summary of a curation\n\n\tinput:\n\tdb : from scdbstart()\n\tsequence : str (ACGT)\n\n\toutput:\n\tshortdesc : list of str\n\t\ta short summary of the curations (1 item per curation)\n\t\"\"\"\n\tshortdesc=[]\n\tcurs=getseqcurations(db,sequence)\n\tfor ccur in curs:\n\t\tcdesc=''\n\t\tcurinfo=ccur[0]\n\t\tcurdetails=ccur[1]\n\t\tif curinfo['Description']:\n\t\t\tcdesc+=curinfo['Description']+' ('\n\t\tif curinfo['CurType']=='COMMON':\n\t\t\tcdesc+='common in '\n\t\t\tfor cdet in curdetails:\n\t\t\t\tcdesc+=cdet[1]+' '\n\t\telif curinfo['CurType']=='HIGHFREQ':\n\t\t\tcdesc+='high freq in '\n\t\t\tfor cdet in curdetails:\n\t\t\t\tcdesc+=cdet[1]+' '\n\t\telif curinfo['CurType']=='DIFFEXP':\n\t\t\tchigh=[]\n\t\t\tclow=[]\n\t\t\tcall=[]\n\t\t\tfor cdet in curdetails:\n\t\t\t\tif cdet[0]=='ALL':\n\t\t\t\t\tcall.append(cdet[1])\n\t\t\t\t\tcontinue\n\t\t\t\tif cdet[0]=='LOW':\n\t\t\t\t\tclow.append(cdet[1])\n\t\t\t\t\tcontinue\n\t\t\t\tif cdet[0]=='HIGH':\n\t\t\t\t\tchigh.append(cdet[1])\n\t\t\t\t\tcontinue\n\t\t\tcdesc+=' high in '\n\t\t\tfor cval in chigh:\n\t\t\t\tcdesc+=cval+' '\n\t\t\tcdesc+=' compared to '\n\t\t\tfor cval in clow:\n\t\t\t\tcdesc+=cval+' '\n\t\t\tcdesc+=' in '\n\t\t\tfor cval in call:\n\t\t\t\tcdesc+=cval+' '\n\t\telse:\n\t\t\tDebug(2,'unknown curation %s.' % curinfo['CurType'])\n\t\tshortdesc.append(cdesc)\n\treturn shortdesc\n\n\ndef select_column_and_value(cur, sql, parameters=()):\n\t\"\"\"\n\tget a dict with field as key, value as values for an sql query\n\t\"\"\"\n\texecute = cur.execute(sql, parameters)\n\tfetch = execute.fetchone()\n\n\tif fetch is None:\n\t\treturn {}\n\n\treturn {k[0]: v for k, v in list(zip(execute.description, fetch))}\n\n\ndef createontologytree(db,ontologies=[],outname=None):\n\t\"\"\"\n\tload the ontology tree graphs into the scdb and store them in a pickle dict\n\n\tinput:\n\tdb : from scdbstart()\n\tontologies : list of str\n\t\tlist of obo ontologies to use or empty to use the default files (db.ontologyfiles)\n\toutname : str\n\t\tname of the output pickle file or None for default location\n\n\toutput:\n\tdb - scdbstruct\n\t\twith the ontodict field added\n\t\"\"\"\n\tif outname is None:\n\t\toutname=os.path.join(getheatsequerdir(),'db/ontologygraph.pickle')\n\n\tif not ontologies:\n\t\tontologies=db.ontologyfiles\n\n\tif not db.ontologyfromid:\n\t\tdb=loaddbonto(db)\n\n\tontodict={}\n\tfor conto in ontologies:\n\t\tDebug(6,'Processing ontology %s' % conto)\n\t\tg=ontologytotree(conto)\n\t\tg=ontotreetonames(g,db.ontologyfromid)\n\t\tontodict[conto]=g\n\tDebug(6,'ontologies loaded. saving to pickel %s' % outname)\n\tfl=open(outname,'wb')\n\tpickle.dump(ontodict,fl,protocol=2)\n\tDebug(6,'ontologies pickled')\n\tdb.ontodict=ontodict\n\treturn db\n\n\n\ndef loadontotrees(db,ontopickle=None):\n\t\"\"\"\n\tload the ontology dict pickle file\n\n\tinput:\n\tdb : from scdbstart()\n\tontopickle : str\n\t\tthe pickled ontology dict filename (from createontologytree()) or None for default location\n\n\toutput:\n\tdb : scdbstruct\n\t\twith the ontology dict in ontodict\n\t\"\"\"\n\tif ontopickle is None:\n\t\tontopickle=os.path.join(getheatsequerdir(),'db/ontologygraph.pickle')\n\tDebug(6,'loadding ontology trees')\n\tfl=open(ontopickle,'rb')\n\tdb.ontodict=pickle.load(fl)\n\tDebug(6,'loaded %d trees' % len(db.ontodict))\n\treturn db\n\n\ndef getontoparents(db,term):\n\t\"\"\"\n\tget all the parent terms (including original term) for a given ontology term.\n\tlook in all ontology trees in db.ontodict\n\n\tinput:\n\tdb : from scdbstart()\n\tterm : str\n\t\tthe ontology term (lower case)\n\n\toutput:\n\tterms : list of str\n\t\tall the parent terms of this item\n\t\"\"\"\n\tterms=[]\n\tfor conto in db.ontodict.values():\n\t\tparents=getnodeparents(conto,term)\n\t\tterms+=parents\n\tterms=list(set(terms))\n\treturn terms\n\n\ndef getcurationontologies(db,sequence):\n\t\"\"\"\n\tget the curation for items and all upstream (ontology-wise) items for a given sequence\n\n\tinput:\n\tdb : from scdbstart()\n\tsequence : str (ACGT)\n\n\toutput:\n\tonto : dict of key=str and value dict of key=str and value=int\n\t\ta dictionary of ['up','down','contaminant'] of dict of ontology item and number of times total we see it\n\t\"\"\"\n\tif not db.ontodict:\n\t\tloadontotrees(db)\n\tonto={}\n\tcurs=getseqcurations(db,sequence)\n\tfor ccur in curs:\n\t\tcurinfo=ccur[0]\n\t\tcurdetails=ccur[1]\n\t\tctype='other'\n\t\tlookseparate=False\n\t\tif curinfo['CurType']=='COMMON':\n\t\t\tctype='up'\n\t\telif curinfo['CurType']=='HIGHFREQ':\n\t\t\tctype='up'\n\t\telse:\n\t\t\tlookseparate=True\n\t\tfor cdet in curdetails:\n\t\t\tif lookseparate:\n\t\t\t\tif cdet[0]=='ALL':\n\t\t\t\t\tctype='up'\n\t\t\t\telif cdet[0]=='LOW':\n\t\t\t\t\tctype='down'\n\t\t\t\telif cdet[0]=='HIGH':\n\t\t\t\t\tctype='up'\n\t\t\t\telse:\n\t\t\t\t\tctype='other'\n\t\t\tif ctype not in onto:\n\t\t\t\tonto[ctype]={}\n\t\t\tontoparents=getontoparents(db,cdet[1])\n\t\t\tfor conto in ontoparents:\n\t\t\t\tif conto not in onto[ctype]:\n\t\t\t\t\tonto[ctype][conto]=1\n\t\t\t\telse:\n\t\t\t\t\tonto[ctype][conto]+=1\n\treturn onto\n\n\ndef delete_annotation(db,annotationid):\n\t'''\n\tdelete an annotation from the database.\n\n\tinput:\n\tdb :\n\tannotationid : int\n\t\tthe annotationid to delete\n\n\toutput:\n\t'''\n\tDebug(1,'delete annotation for annotatioid %d' % annotationid)\n\trdata={}\n\trdata['annotationid']=annotationid\n\tres=requests.post(db.dburl+'/annotations/delete',json=rdata)\n\tif res.status_code!=200:\n\t\tDebug(6,'error deleting annotationid %d' % annotationid)\n\t\tDebug(6,res.content)\n\t\treturn []\n\tDebug(2,'Annotation %d deleted' % annotationid)\n\n\n\n\ndef get_experiment_annotations(db,exp):\n\t'''\n\tget annotations on all sequences in the experiment\n\n\tinput:\n\tdb:\n\texp : Experiment\n\n\toutput:\n\t'''\n\tDebug(1,'get experiment sequence annotations for %d sequences' % len(exp.seqs))\n\trdata={}\n\trdata['sequences']=exp.seqs\n\tres=requests.get(db.dburl+'/sequences/get_list_annotations',json=rdata)\n\tif res.status_code!=200:\n\t\tDebug(6,'error getting list annotations')\n\t\tDebug(6,res.content)\n\t\treturn []\n\treturn res.json()['seqannotations']\n\n\ndef convert_olddb_to_server(db,olddbfilename='db/supercooldb.db'):\n\t'''\n\tload the old local sqlite3 database to the server\n\n\tinput:\n\tdb\n\tolddbfilename : str\n\t\tthe sqlite3 database filename\n\t'''\n\tcon=sqlite3.connect(olddbfilename)\n\tDebug(7,\"Connected to database\")\n\t# and the cursor\n\tcur=con.cursor()\n\n\t# add all studies\n\t# get studyids\n\tDebug(7,'getting study ids')\n\tcur.execute(\"SELECT DataID FROM Data\")\n\tallvals=cur.fetchall()\n\tDebug(7,'found %d details' % len(allvals))\n\tstudyids=set()\n\tfor cres in allvals:\n\t\tstudyids.add(cres[0])\n\tDebug(7,'found %d unique ids' % len(studyids))\n\tDebug(7,'processing per study data')\n\tstudyoldnew={}\n\tfor cid in studyids:\n\t\tcur.execute(\"SELECT Type,Value FROM Data WHERE DataID = ?\",[cid])\n\t\tallvals=cur.fetchall()\n\t\tDebug(7,'found %d details for studyid %d' % (len(allvals),cid))\n\t\tDebug(7,'adding study data')\n\t\tDebug(7,'looking for md5 in previous studies')\n\t\tfor cres in allvals:\n\t\t\tif cres[0]=='DataMD5':\n\t\t\t\tdatamd5=cres[1]\n\t\t\tif cres[0]=='MapMD5':\n\t\t\t\tmapmd5=cres[1]\n\t\tnewid=finddataid(db,datamd5=datamd5,mapmd5=mapmd5,getall=False)\n\t\tif newid is not None:\n\t\t\tDebug(7,'already exists. id=%d' % newid[0])\n\t\t# newid = addexpdata(db,list(allvals))\n\t\tnewid=0\n\t\tDebug(7,'added data new studyid %d' % newid)\n\t\tstudyoldnew[cid]=newid\n\n\t","repo_name":"amnona/heatsequer","sub_path":"heatsequer/supercooldb/scdb.py","file_name":"scdb.py","file_ext":"py","file_size_in_byte":22162,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"15"} +{"seq_id":"25425955430","text":"#!/usr/bin/env python\n\n# Headers\n__author__ = 'somsubhra'\n\n# All imports\nfrom flask import Flask, render_template, request, jsonify\nfrom clusterman import ClusterMan\n\n# All constant definitions\nHOST = \"0.0.0.0\"\nPORT = 8000\nDEBUG = False\n\n# Create an instance of the webapp\napp = Flask(__name__)\ncluster_manager = ClusterMan(nodes_file=\"default.nodes\")\n\n\n# The index page route\n@app.route('/')\ndef index_handler():\n connected_nodes = cluster_manager.nodes.to_string()\n return render_template(\"index.html\", connected_nodes=connected_nodes)\n\n\n# The API route\n@app.route('/api')\ndef api_handler():\n output = cluster_manager.execute_command(request.args.get(\"command\"))\n\n json_result = {\n \"output\": output\n }\n\n return jsonify(**json_result)\n\n# Run the app\napp.run(host=HOST, port=PORT, debug=DEBUG)\n","repo_name":"Somsubhra/clusterman","sub_path":"clusterweb.py","file_name":"clusterweb.py","file_ext":"py","file_size_in_byte":819,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"15"} +{"seq_id":"2887185175","text":"class Solution:\n def reverse(self, x: int) -> int:\n value = 0\n\n if x > 0:\n value = int(str(x)[::-1])\n else:\n value = (-1) * int(str(x*(-1))[::-1])\n\n if value not in range(-2**31, 2**31):\n value = 0\n\n return value \n\nsol = Solution()\nx = 10\nprint(sol.reverse(x))\n","repo_name":"ideyedi/algorithm","sub_path":"leet/esji/07.Reverse_Integer.py","file_name":"07.Reverse_Integer.py","file_ext":"py","file_size_in_byte":332,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"15"} +{"seq_id":"39413702476","text":"\"\"\"\n File name: train.py\n Author: Gabriel Moreira\n Date last modified: 3/28/2022\n Python Version: 3.9.10\n\"\"\"\n\nimport os\nimport torch\nimport numpy as np\nimport torch.optim as optim\nimport torch.nn as nn\nimport math\nfrom trainer import Trainer\nfrom loader import TaskLoader\nfrom rnn import EncoderLSTM, DecoderLSTM\n\nfrom utils import getNumTrainableParams\n\n\"\"\"\n FILES/PATHS\n\"\"\"\ndata_path = './data/json_feat_2.1.0'\nfeat_pt_filename = 'feat_conv.pt'\nsplits_path = './data/splits/oct21.json'\nvocab_path = \"./exp/seq2seq_im_mask/pp.vocab\"\n\n\"\"\"\n CONFIGURATION\n\"\"\"\ncfg = {'name' : 's1',\n 'seed' : 1,\n 'epochs' : 100,\n 'batch_size' : 1,\n 'lr' : 0.001,\n 'resume' : False}\n\n\nif __name__ == '__main__':\n # If experiment folder doesn't exist create it\n if not os.path.isdir(cfg['name']):\n os.makedirs(cfg['name'])\n print(\"Created experiment folder : \", cfg['name'])\n else:\n print(cfg['name'], \"folder already exists.\")\n\n device = torch.device(\"cuda\" if torch.cuda.is_available() else \"cpu\")\n\n if device == \"cuda\":\n torch.cuda.empty_cache()\n\n torch.manual_seed(cfg['seed'])\n np.random.seed(cfg['seed'])\n\n # LOAD ALFRED'S VOCABULARY\n vocab = torch.load(vocab_path)\n\n # TASK LOADERS TO BE USED DURING TRAINING\n train_loader = TaskLoader(data_path, splits_path, 'train', cfg['batch_size'], shuffle=True)\n dev_loader = TaskLoader(data_path, splits_path, 'valid_seen', cfg['batch_size'], shuffle=True)\n\n # MODEL PARAMS\n action_vocab_size = len(vocab['action_low'])\n word_vocab_size = len(vocab['word'])\n action_embedding_size = 256\n word_embedding_size = 512\n visual_embedding_size = 512 # Alfred's ResNet18 features are (T,49,512)\n hidden_size = 1024\n\n speaker_encoder = EncoderLSTM(action_vocab_size, action_embedding_size, visual_embedding_size, hidden_size, 0.1).to(device)\n speaker_decoder = DecoderLSTM(word_vocab_size, word_embedding_size, hidden_size, dropout_ratio=0.1, use_input_att_feed=True).to(device)\n\n # OPTIMIZATION\n encoder_optimizer = optim.SGD(speaker_encoder.parameters(), lr=cfg['lr'])\n decoder_optimizer = optim.SGD(speaker_decoder.parameters(), lr=cfg['lr'])\n encoder_scheduler = optim.lr_scheduler.CosineAnnealingLR(encoder_optimizer, T_max=(len(train_loader) * cfg['epochs']))\n decoder_scheduler = optim.lr_scheduler.CosineAnnealingLR(decoder_optimizer, T_max=(len(train_loader) * cfg['epochs']))\n criterion = nn.NLLLoss(ignore_index=0)\n\n trainer = Trainer(speaker_encoder,\n speaker_decoder,\n encoder_optimizer,\n decoder_optimizer,\n encoder_scheduler,\n decoder_scheduler,\n vocab,\n cfg['epochs'],\n criterion,\n train_loader, \n dev_loader,\n device,\n cfg['name'],\n cfg['resume'])\n\n # Verbose\n print('Experiment ' + cfg['name'])\n print('Running on', device)\n print('Train - {} batches of size {}'.format(math.ceil(len(train_loader)/cfg['batch_size']), cfg['batch_size']))\n print(' Val - {} batches of size {}'.format(math.ceil(len(dev_loader)/cfg['batch_size']), cfg['batch_size']))\n print('Number of trainable parameters (encoder): {}'.format(getNumTrainableParams(speaker_encoder)))\n print('Number of trainable parameters (decoder): {}'.format(getNumTrainableParams(speaker_decoder)))\n print(speaker_encoder)\n print(speaker_decoder)\n\n trainer.fit()\n\n\n\n\n \n\n\n","repo_name":"gabmoreira/speaker","sub_path":"speaker/train.py","file_name":"train.py","file_ext":"py","file_size_in_byte":3715,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"15"} +{"seq_id":"41429010306","text":"import urllib.request as rq\nfrom urllib import parse\nfrom http import cookiejar\nimport json\nimport time\nimport gzip\n\n\ndef query_privilege(cookie):\n url=\"https://api.bilibili.com/x/vip/privilege/my\"\n headers={\"Cookie\":cookie}\n req = rq.Request(url=url,headers=headers)\n req = rq.urlopen(req)\n req=req.read().decode('utf-8')\n print(req)\n\ndef auto_add_coins(cookie,csrf,avid):\n url=\"https://api.bilibili.com/x/web-interface/coin/add\"\n headers={\n \"Cookie\":cookie,\n \"content-length\": \"94\",\n \"content-type\": \"application/x-www-form-urlencoded; charset=UTF-8\",\n \"accept-language\": \"zh-CN,zh;q=0.9,en;q=0.8,en-GB;q=0.7,en-US;q=0.6\",\n \"user-agent\": \"Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/84.0.4147.89 Safari/537.36 Edg/84.0.522.39\",\n \"referer\": \"https://www.bilibili.com/video/\" #必须有\n}\n data={\"aid\":avid,\"csrf\":csrf,\"multiply\":\"1\",\"select_like\":\"1\",\"cross_domain\":\"false\"}\n data=bytes(parse.urlencode(data),encoding=\"utf8\")\n req = rq.Request(url=url,headers=headers,data=data, method='POST')\n rep = rq.urlopen(req)\n rep=rep.read().decode('utf-8')\n return rep\n\ndef get_my5B(cookie,csrf):\n url=\"https://api.bilibili.com/x/vip/privilege/receive\"\n headers={\"Cookie\":cookie}\n data={\"type\":1,\"csrf\":csrf}\n data=bytes(parse.urlencode(data),encoding=\"utf8\")\n req = rq.Request(url=url,headers=headers,data=data, method='POST')\n req = rq.urlopen(req)\n req=req.read().decode('utf-8')\n print(req)\n\ndef chrage(cookie,csrf,bpnum):\n url=\"https://api.bilibili.com/x/ugcpay/web/v2/trade/elec/pay/quick\"\n headers={\"Cookie\":cookie}\n data={\"csrf\":csrf,\"bp_num\":bpnum,\"is_bp_remains_prior\": \"true\",\"up_mid\": \"10363537\",\"otype\": \"up\",\"oid\": \"10363537\"}\n data=bytes(parse.urlencode(data),encoding=\"utf8\")\n req = rq.Request(url=url,headers=headers,data=data, method='POST')\n req = rq.urlopen(req)\n req=req.read().decode('utf-8')\n print(req)\n return req\ndef get_dynamic(cookie):\n url=\"https://api.vc.bilibili.com/dynamic_svr/v1/dynamic_svr/dynamic_new?uid=10363537&type_list=268435455&from=weball&platform=web\"\n headers={\"Cookie\":cookie}\n req = rq.Request(url=url,headers=headers)\n req = rq.urlopen(req)\n req=req.read().decode('utf-8')\n return req\n '''\n with open(\"test.json\",\"w\") as f:\n f.write(req)\n print(json.loads(req))\n '''\n\nif __name__==\"__main__\":\n import sys\n csrf,cookie=sys.argv[1].split(\" \")\n get_my5B(cookie,csrf)\n\n\n","repo_name":"ghGYR/website_checkin","sub_path":"bilibili_api.py","file_name":"bilibili_api.py","file_ext":"py","file_size_in_byte":2508,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"15"} +{"seq_id":"15932087406","text":"import sys\nfrom itertools import combinations\ninput = sys.stdin.readline\n\nn, m = map(int, input().split())\n\nchicken = [list(map(int, input().split())) for _ in range(n)]\n\n'''\nchicken[i] = i번째 사람의 치킨만족도\nchicken[i][j] = i번째 사람의 j치킨에 대한 만족도\n'''\nmax_like = 0\nfor elem in combinations(range(m), 3):\n like = 0\n for i in range(n):\n tmp = 0\n for chicken_idx in elem:\n tmp = max(tmp, chicken[i][chicken_idx])\n like += tmp\n max_like = max(max_like, like)\nprint(max_like)","repo_name":"JeongGod/Algorithm-Coding","sub_path":"Brute_Force/16439.py","file_name":"16439.py","file_ext":"py","file_size_in_byte":547,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"15"} +{"seq_id":"18009609286","text":"import sys\n\n\n# input\nt = int(sys.stdin.readline())\n# solve here\ndef solve():\n n = int(input())\n A = sorted(list(map(int,input().split())))\n i = 0\n k = n-1\n ans = []\n while i> 1->2->3->4->5->NULL\n# 2\n# OUTPUT: -\n# void\n# linked list will be:=>> 1->3->4->5->NULL\n\n# Definition for singly-linked list.\nclass ListNode:\n def __init__(self, x):\n self.val = x\n self.next = None\n\ndef delNode(node):\n\n # solution 1 using loop till node\n # Time Complexity O(n)\n while node.next:\n node.val = node.next.val\n prev = node\n node = node.next\n prev.next = None\n\n # solution 2\n # Time Complexity O(1) Space Complexity O(1)\n node.val, node.next.val = node.next.val, node.val\n node.next = node.next.next","repo_name":"drashti2210/180_Interview_Questions","sub_path":"Delete_Given_Node.py","file_name":"Delete_Given_Node.py","file_ext":"py","file_size_in_byte":690,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"15"} +{"seq_id":"26696525818","text":"import time\n\nimport em_ulator\nfrom em_ulator.models import Game\n\nclass GameRunner():\n\n def run(self):\n while True:\n games = Game.get_all()\n for game in games:\n print(f\"Tick for game {game.id}\")\n game.tick()\n\n # transition each game\n print(\"sleeping for 5\")\n time.sleep(2)\n\n\nif __name__ == '__main__':\n app = em_ulator.create_app()\n with app.app_context():\n g = GameRunner()\n g.run()\n","repo_name":"theletterd/EM-ulator","sub_path":"em_ulator/tasks/worker.py","file_name":"worker.py","file_ext":"py","file_size_in_byte":498,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"15"} +{"seq_id":"7459335134","text":"# Using xing module to analyze who wins the most games in xing\r\nimport time\r\n\r\nfrom xing import *\r\n\r\nimport interactive_histogram\r\n\r\np1_wins = 0\r\np2_wins = 0\r\ndraw = 0\r\n\r\ns = time.time()\r\nfor i in range(100000):\r\n a = xing(2)\r\n if a == 1:\r\n p1_wins += 1\r\n elif a == 2:\r\n p2_wins += 1\r\n else:\r\n draw += 1\r\nf = time.time()\r\n\r\nnew = interactive_histogram.Histogram([p1_wins, p2_wins, draw])\r\nnew.show(1000)\r\nprint(f-s)\r\n","repo_name":"kejdidomi/xing","sub_path":"analyzing_xing.py","file_name":"analyzing_xing.py","file_ext":"py","file_size_in_byte":450,"program_lang":"python","lang":"en","doc_type":"code","stars":2,"dataset":"github-code","pt":"15"} +{"seq_id":"21889896535","text":"# coding=utf-8 \r\n# @Time : 2018/8/8 22:03 \r\n# @Author : achjiang\r\n# @File : qiniu_libs.py\r\n\r\n# 导入七牛的用户及上传数据包\r\n\r\nfrom qiniu import Auth, put_data\r\n\r\naccess_key ='AnE70UQaiqokVXUT7v3BGYNAVWo5oey8UA3fEdsD'\r\nsecret_key ='BIGPCz55HcnTtq3RqDgMfeLUtvwTaBGnVKNs4gyN'\r\nbucket_name =' achjiangspace'\r\nq = Auth(access_key, secret_key)\r\n\r\ndef upload_qiniu_file_content(content):\r\n # 七牛上传文件\r\n token = q.upload_token(bucket_name)\r\n\r\n ret, info = put_data(token, None, content)\r\n return ret['key'], info\r\n\r\n\r\ndef down_qiniu_file(qiniu_url):\r\n # 七牛下载文件\r\n url = q.private_download_url(qiniu_url, expires=10)\r\n return url","repo_name":"yuyexiaohan/Tornado-OA-System","sub_path":"libs/qiniu/qiniu_libs.py","file_name":"qiniu_libs.py","file_ext":"py","file_size_in_byte":674,"program_lang":"python","lang":"en","doc_type":"code","stars":8,"dataset":"github-code","pt":"15"} +{"seq_id":"34951293938","text":"from .banking import BIC, IBAN\nfrom .bookland import ISBN, ISMN, ISSN\nfrom .euvatid import EUVATId\nfrom .finance import MIC, ISIN\nfrom .gs1 import GLN, GSIN, GTIN12, GTIN13, GTIN14, SSCC\nfrom .identifier import Identifier\nfrom .version import version as __version__\n\n\n__all__ = [\n 'Identifier',\n 'GLN',\n 'GSIN',\n 'GTIN12',\n 'GTIN13',\n 'GTIN14',\n 'SSCC',\n 'ISBN',\n 'ISMN',\n 'ISSN',\n 'BIC',\n 'IBAN',\n 'MIC',\n 'ISIN',\n 'EUVATId',\n]\n","repo_name":"mamrhein/identifiers","sub_path":"src/identifiers/__init__.py","file_name":"__init__.py","file_ext":"py","file_size_in_byte":474,"program_lang":"python","lang":"en","doc_type":"code","stars":5,"dataset":"github-code","pt":"15"} +{"seq_id":"72270144010","text":"import os\nfrom typing import List\nfrom fastapi import Depends, HTTPException, APIRouter, UploadFile, File\nfrom fastapi.responses import FileResponse\nfrom sqlalchemy.orm import Session\n\nfrom ..dependencies import get_db, get_current_user\n\nfrom .. import crud, schemas\n\nrouter = APIRouter(\n prefix=\"/api/feedback\",\n tags=[\"feedback\"]\n)\n\n@router.post(\"/{model_id}/submit-feedback\",\nresponse_model=schemas.feedback.Feedback\n)\ndef submit_feedback(\n feedback: schemas.feedback.FeedbackBase,\n model_id: int,\n db: Session = Depends(get_db),\n current_user: schemas.users.User = Depends(get_current_user)\n ):\n\n \"\"\"Takes in feedback for the given model and writes it to the database\"\"\"\n \n db_model = crud.models.get_model_by_id(db=db, id=model_id)\n if db_model is None:\n raise HTTPException(status_code=404, detail=\"Model not found\")\n\n return crud.feedback.create_feedback(\n db=db,\n feedback=feedback,\n model_id=model_id,\n user_id=current_user.id\n )\n\n@router.get(\"/{model_id}\", response_model=List[schemas.feedback.Feedback])\ndef read_model_feedback(\n model_id: int,\n skip: int = 0,\n limit: int = 100,\n db: Session = Depends(get_db),\n current_user: schemas.users.User = Depends(get_current_user)\n ):\n\n \"\"\"\n Returns all records of feedback for the corresponding model by its id.\n \"\"\"\n\n db_model = crud.models.get_model_by_id(db=db, id=model_id)\n if db_model is None:\n raise HTTPException(status_code=404, detail=\"Model not found\")\n feedback = crud.feedback.get_model_feedback(\n model_id=model_id,\n db=db,\n skip=skip,limit=limit\n )\n return feedback\n\n@router.delete(\"/delete-feedback\")\ndef delete_model(\n feedback_id: int,\n db: Session = Depends(get_db),\n current_user: schemas.users.User = Depends(get_current_user)\n ):\n\n \"\"\"\n Verifies the user requesting the delete is the one who submitted the\n feedback, if so, deletes the record of the feedback\n \"\"\"\n\n db_feedback = crud.feedback.get_feedback_by_id(db, id=feedback_id)\n if db_feedback is None:\n raise HTTPException(status_code=404, detail=\"Feedback not found\")\n if db_feedback.user_id != current_user.id:\n raise HTTPException(status_code=401, detail=\"Unauthorised\")\n crud.feedback.delete_feedback(db=db, id=feedback_id)\n return {\"ok\": True}\n","repo_name":"fnysfnys/Model-Match","sub_path":"src/api/routers/feedback.py","file_name":"feedback.py","file_ext":"py","file_size_in_byte":2387,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"15"} +{"seq_id":"20397046159","text":"from bs4 import BeautifulSoup\nimport requests\nfrom time import sleep\nimport keyboard\n\nurl = 'https://www.bfm.ru'\nno_photo_url = 'https://boom-zaim.ru/wp-content/uploads/2019/09/166_trolska-sk-1s.jpg'\n\n\ndef get_news_list():\n contents = requests.get(url).text\n soup = BeautifulSoup(contents, 'lxml')\n\n news = soup.find_all('div', {'class': 'block-news-container'})\n main_news = soup.find('div', {'class': 'main-container'}).find('a')['href']\n\n res = [url + main_news]\n\n got_news = set()\n for x in news:\n link = x.find('a')['href']\n if link not in got_news:\n got_news.add(link)\n res.append(url + link)\n\n return res\n\ndef get_post_data(url):\n contents = requests.get(url).text\n soup = BeautifulSoup(contents, 'lxml')\n\n img = soup.find('figure', {'class': 'article-figure'})\n if img == None:\n title = \"Формат новости не поддерживается\"\n text = \"Эта новость нетипичная. Пока я не умею такое парсить.\"\n return {'image_link': no_photo_url, 'title': title, 'date': \"\", 'text': text}\n else:\n img = img.find('img')['src']\n date = soup.find('span', {'class': 'date'}).find(text=True).strip()\n title = soup.find('h1', {'class': 'news-title'}).find(text=True).strip()\n short_text = soup.find('p', {'class': 'about-article'}).find(text=True).strip()\n\n return {'image_link': img, 'title': title, 'date': date, 'text': short_text}\n","repo_name":"MakArtKar/apo_school","sub_path":"lecture_12/BFM_parcer_bot/my_parser.py","file_name":"my_parser.py","file_ext":"py","file_size_in_byte":1500,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"15"} +{"seq_id":"1357290715","text":"# Массив размером 2m + 1, где m — натуральное число, заполнен случайным образом. Найдите в массиве медиану.\r\n# Медианой называется элемент ряда, делящий его на две равные части: в одной находятся элементы,\r\n# которые не меньше медианы, в другой — не больше медианы.\r\n\r\n# Примечание: задачу можно решить без сортировки исходного массива. Но если это слишком сложно, используйте\r\n# метод сортировки, который не рассматривался на уроках (сортировка слиянием также недопустима).\r\n\r\nimport random\r\nm = 10\r\narray = [random.randint(0,50) for i in range(2*m+1)]\r\nprint(f'{array} - исходная последовательность')\r\n\r\ndef median(array):\r\n el = random.choice(array)\r\n def count_arr(el):\r\n l = []\r\n r = []\r\n m = []\r\n for i in array:\r\n if i < el:\r\n l.append(i)\r\n elif i > el:\r\n r.append(i)\r\n elif i == el:\r\n m.append(i)\r\n return (l, m, r)\r\n\r\n while True:\r\n l, m, r = count_arr(el)\r\n result = m[0]\r\n if abs(len(l) - len(r)) <= len(m):\r\n break\r\n else:\r\n if len(l) < len(r):\r\n el = random.choice(r)\r\n else:\r\n el = random.choice(l)\r\n return(m[0])\r\nprint(f'Медиана = {median(array)}')\r\n\r\n# Проверим\r\nprint ('-'*30, 'Проверка', '-'*30)\r\ns_arr = sorted(array)\r\nprint(f'{s_arr} - после сортировки')\r\nprint(f'Число посредине: {s_arr[len(s_arr)//2]}')\r\n\r\n","repo_name":"karashchuk/algoritmPython_07","sub_path":"les_7_task_3.py","file_name":"les_7_task_3.py","file_ext":"py","file_size_in_byte":1898,"program_lang":"python","lang":"ru","doc_type":"code","stars":0,"dataset":"github-code","pt":"15"} +{"seq_id":"71050036810","text":"\"\"\"\nA more advanced image recognition neural net based off of the mnist dataset.\n\"\"\"\n\n# System Imports.\nfrom tensorflow.examples.tutorials.mnist import input_data\nimport tensorflow\n\n# User Class Imports.\nfrom resources import logging\n\n\n# Initiate logging.\nlogger = logging.get_logger(__name__)\n\n\nclass ConvMnist():\n def __init__(self):\n logger.info('Starting Conv MNIST Tensor Net.')\n\n self.tensor_session = None\n self.mnist_data = input_data.read_data_sets('MNIST_data', one_hot=True)\n self.input_matrix = None\n self.output_matrix = None\n self.delta_matrix = None\n self.keep_prob = tensorflow.placeholder(tensorflow.float32)\n self.cross_entropy = self.create_model()\n\n def __del__(self):\n # Close tensorflow session.\n if self.tensor_session:\n self.tensor_session.close()\n logger.info('Conv MNIST Tensor Net finished.')\n\n def create_model(self):\n \"\"\"\n Create various \"tensors\" (multi-dimensional matrixes) to manipulate data.\n A shape value of \"None\" means it can take in any arbitrary number of items in that dimension.\n 784 is the total number of pixels per input image.\n :return: Returns \"cross_entropy\" function, which is used to hold error.\n \"\"\"\n # Define input matrix setup.\n self.input_matrix = tensorflow.placeholder(tensorflow.float32, shape=[None, 784])\n\n # Reshape image by width, height, and number of color channels. Not sure what first dimension is.\n x_image = tensorflow.reshape(self.input_matrix, [-1, 28, 28, 1])\n\n # Define first convolutional layer.\n conv_layer_1 = self.create_conv_layer(x_image, 1, 32)\n\n # Define second convolutional layer.\n conv_layer_2 = self.create_conv_layer(conv_layer_1, 32, 64)\n\n # Downsample further for simplification of dense layers.\n flattening_pool = tensorflow.reshape(conv_layer_2, [-1, 7*7*64])\n\n # Define first dense layer. Also applies relu for the activation function.\n conv_output = tensorflow.nn.relu(self.create_dense_layer(flattening_pool, 7 * 7 * 64, 1024))\n\n # Define delta matrix.\n self.delta_matrix = tensorflow.placeholder(tensorflow.float32, [None, 10])\n\n # \"Dropout\" layer used during training to prevent overfitting.\n dropout_layer = tensorflow.nn.dropout(conv_output, self.keep_prob)\n\n # Create final layer/second dense layer.\n self.output_matrix = self.create_dense_layer(dropout_layer, 1024, 10)\n\n # Determine cross entropy. Used to actually train net gradient.\n cross_entropy = tensorflow.reduce_mean(\n tensorflow.nn.softmax_cross_entropy_with_logits_v2(labels=self.delta_matrix, logits=self.output_matrix)\n )\n\n # Initialize tensorflow session.\n self.tensor_session = tensorflow.InteractiveSession()\n tensorflow.global_variables_initializer().run()\n\n return cross_entropy\n\n def create_conv_layer(self, x_inputs, input_dimension, output_dimension):\n \"\"\"\n Define a given convolutional layer.\n See https://www.tensorflow.org/tutorials/layers.\n :param x_inputs: The input values for layer to manipulate.\n :param input_dimension: Input dimension of features.\n :param output_dimension: Output dimension of features.\n :return: Full convolutional layer (or at least the necessary hook into it).\n \"\"\"\n # Weights will have [output_dimension] features per 5x5 patch.\n conv_weights = self.create_conv_weights([5, 5, input_dimension, output_dimension])\n conv_biases = self.create_conv_bias([output_dimension])\n\n # Apply convolutional filters. Stride first and last value should always be 1.\n # Inner values are height and width, respectively.\n conv_filter = tensorflow.nn.relu(\n tensorflow.nn.conv2d(x_inputs, conv_weights, strides=[1, 1, 1, 1], padding='SAME') + conv_biases\n )\n\n # Pooling downsamples image data to a smaller pixel size, as filters seem to greatly expand it.\n pooling_layer = tensorflow.nn.max_pool(conv_filter, ksize=[1, 2, 2, 1], strides=[1, 2, 2, 1], padding='SAME')\n return pooling_layer\n\n def create_conv_weights(self, shape):\n \"\"\"\n Create weights of the given shape.\n :param shape: Dimensions of weights, in array format.\n :return: Weight matrix variable.\n \"\"\"\n weights = tensorflow.truncated_normal(shape, stddev=0.1)\n return tensorflow.Variable(weights)\n\n def create_conv_bias(self, shape):\n \"\"\"\n Create bias of the given shape.\n :param shape: Dimensions of bias, in array format.\n :return: Bias matrix variable.\n \"\"\"\n bias = tensorflow.constant(0.1, shape=shape)\n return tensorflow.Variable(bias)\n\n def create_dense_layer(self, x_inputs, input_dimension, output_dimension):\n \"\"\"\n Define a given dense node layer.\n :param x_inputs: The input values for layer to manipulate.\n :param input_dimension: Input dimension of features.\n :param output_dimension: Output dimension of features.\n :return: Full dense node layer (or at least the necessary hook into it).\n \"\"\"\n dense_weights = self.create_dense_weights([input_dimension, output_dimension])\n dense_biases = self.create_dense_bias([output_dimension])\n\n # Apply matrix layer logic.\n dense_layer = tensorflow.matmul(x_inputs, dense_weights) + dense_biases\n return dense_layer\n\n def create_dense_weights(self, shape):\n \"\"\"\n Create weights of the given shape.\n :param shape: Dimensions of weights, in array format.\n :return: Weight matrix variable.\n \"\"\"\n weights = tensorflow.truncated_normal(shape, mean=0.0, stddev=0.01)\n return tensorflow.Variable(weights)\n\n def create_dense_bias(self, shape):\n \"\"\"\n Create bias of the given shape.\n :param shape: Dimensions of bias, in array format.\n :return: Bias matrix variable.\n \"\"\"\n bias = tensorflow.truncated_normal(shape, mean=0.0, stddev=0.01)\n return tensorflow.Variable(bias)\n\n def train(self):\n \"\"\"\n Train tensor net.\n \"\"\"\n # Define a training step, using entropy and Gradient Descent. Learning rate of 0.5.\n train_step = tensorflow.train.GradientDescentOptimizer(0.1).minimize(self.cross_entropy)\n\n # Create structures to calculate accuracy.\n correct_prediction = tensorflow.equal(\n tensorflow.argmax(self.output_matrix, 1),\n tensorflow.argmax(self.delta_matrix, 1)\n )\n accuracy = tensorflow.reduce_mean(tensorflow.cast(correct_prediction, tensorflow.float32))\n total_accuracy = 0\n highest_accuracy = 0\n\n # Step through and train on data.\n for index in range(1000):\n features, targets = self.mnist_data.train.next_batch(50)\n\n # Only print out every 100 values. Displays step number and accuracy info.\n if index % 100 == 0:\n train_accuracy = accuracy.eval(\n feed_dict={\n self.input_matrix: features,\n self.delta_matrix: targets,\n self.keep_prob: 1.0\n }\n )\n if train_accuracy > highest_accuracy:\n highest_accuracy = train_accuracy\n # logger.info(\n # 'Step: {0} | Cur Accuracy: {1} | Best Accuracy: {2}'.format(index, train_accuracy, highest_accuracy)\n # )\n total_accuracy += train_accuracy\n\n # Run a training step.\n self.tensor_session.run(\n train_step,\n feed_dict={\n self.input_matrix: features,\n self.delta_matrix: targets,\n self.keep_prob: 0.5\n }\n )\n\n test_accuracy = accuracy.eval(\n feed_dict={\n self.input_matrix: self.mnist_data.test.images,\n self.delta_matrix: self.mnist_data.test.labels,\n self.keep_prob: 1.0,\n }\n )\n # # Evaluate results and print out.\n # logger.info('Testing Accuracy: {0} Best Training Accuracy: {1}'.format(\n # self.tensor_session.run(\n # accuracy,\n # feed_dict={\n # self.input_matrix: self.mnist_data.test.images,\n # self.delta_matrix: self.mnist_data.test.labels,\n # self.keep_prob: 1.0\n # }\n # ),\n # highest_accuracy\n # ))\n\n return [(total_accuracy / 10), test_accuracy]\n","repo_name":"brodriguez8774/cs5300_a2_NeuralNet_Tensorflow","sub_path":"conv_mnist_net.py","file_name":"conv_mnist_net.py","file_ext":"py","file_size_in_byte":8809,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"15"} +{"seq_id":"8271319611","text":"\nfrom dataclasses import dataclass\n\n@dataclass\nclass Vector(object):\n _x : int = 0\n _y : int = 0\n\n def __repr__(self) -> str:\n \"Return the Vector information\"\n return f\"Vector({self._x}, {self._y})\"\n\n def __add__(self, other):\n \"\"\"Return the vector addition of inputs\"\"\"\n return Vector(self._x + other._x, self._y + other._y)\n\n def __mul__(self, other):\n \"\"\"Return the vector multiply of inputs\"\"\"\n return Vector(self._x * other._x, self._y * other._y)\n\n def __bool__(self):\n \"\"\"Check inputs are in 2-D coordinate\"\"\"\n return bool(max(self._x, self._y))\n\n\n# Vector 인스턴스 생성\nv1 = Vector(5,7)\nv2 = Vector(23, 35)\nv3 = Vector()\n\n# 매직 메소드 출력\nprint(Vector.__add__.__doc__)\n\n\nprint(v1, v2, v3)\n\nprint(v1 + v2)\nprint(v1 * v2)\n\n\n","repo_name":"metterian/inflearn-python-tutorial","sub_path":"chapter03_02.py","file_name":"chapter03_02.py","file_ext":"py","file_size_in_byte":819,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"15"} +{"seq_id":"19011927589","text":"from django.shortcuts import render, redirect, get_object_or_404\nfrom .forms import URLShortenForm \nfrom .models import URL\n\ndef home(req):\n if req.method == 'POST':\n url = URLShortenForm(req.POST)\n if url.is_valid():\n id = url.save().id\n return redirect('show', id = id)\n else:\n form = URLShortenForm()\n data = { 'form':form }\n return render(req, 'shortenurls/home.html', data)\n\ndef show(req):\n url = get_object_or_404(URL, pk=id)\n data = {\n 'url':url\n }\n return render(req, 'shortenurls/show.html', data)\n\n","repo_name":"Graingertom/urlshortener","sub_path":"shortenurls/views.py","file_name":"views.py","file_ext":"py","file_size_in_byte":582,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"15"} +{"seq_id":"10066776347","text":"import csv, os\n\ndef import_data(filename):\n \"\"\"pass users entered file names to avoid future maintenance work of updating file names in the code\n if incorrect names are entered, allow users to re-enter or quit from the program\"\"\"\n\n # assuming data files are saved in a sub folder called 'data folder' under the same directory\n # create an indirect path to feed into file open function\n path = os.path.join('data folder', filename)\n try:\n # when filename is valid and found, read the lines from source file and write into vote.csv file\n with open('vote.csv', 'a', newline='') as csvfile:\n writer = csv.writer(csvfile, delimiter=',')\n source_data = csv.reader(open(path, 'r', newline=''))\n next(source_data,None)\n for row in source_data:\n writer.writerow(row)\n # if filename is incorrect or not found, give users options to quit or try again\n except OSError:\n response = input('File not found!. Please try again or enter \\'quit\\' to exit.')\n if response == 'quit':\n raise SystemExit\n else:\n import_data(response)\n\n# delete old vote.csv file, if any, so that it will not append new data to old data from previous executions\nif os.path.exists('vote.csv'):\n os.remove('vote.csv')\n\n# create a blank csv file with headers only\nwith open('vote.csv', 'a', newline='') as csvfile:\n writer = csv.writer(csvfile, delimiter=',')\n writer.writerow(['Voter ID', 'County', 'Candidate'])\n\n# ask users to enter the file name of election source data\nfilename = input('Please enter the file name of election data, including file extensions like csv -> ')\nimport_data(filename)\n\nAdd_more_data = True\n\n# if there are more than one source data file, allow users to append more files to create a consolidated file\nwhile Add_more_data == True:\n user_response = input('Do you have additional data to import? Y(es) or N(o) -> ')\n if user_response == 'Y':\n filename = input('Please enter the file name of election data, including file extensions like csv -> ')\n import_data(filename)\n elif user_response == 'N':\n Add_more_data = False\n else:\n print('Invalid answer. Please try again! ')\n\n# create a dictionary 'candidate_count' to count the votes by candidate\ncandidate_count = {}\n\n# count votes and identify the winner\nwith open('vote.csv', 'r', newline='') as csvfile:\n reader = csv.reader(csvfile, delimiter=',')\n # skip the header line\n next(reader, None)\n for row in reader:\n # if candidate name not in the candidate count file, add the name to the count file and add 1 to vote count\n if row[2] not in candidate_count.keys():\n candidate_count[row[2]] = 1\n # if candidate name already in the count file, add 1 to the vote count\n else:\n candidate_count[row[2]] += 1\n\n # calculate the total count in the election\n total_vote = (sum(candidate_count.values()))\n\n vote = 0\n winner = ''\n # find out which candidate has most of the votes\n for line in candidate_count.keys():\n if candidate_count[line] > vote:\n vote = candidate_count[line]\n winner = line\n\n# save vote results to txt file in the format required\nwith open('vote_results.txt','w') as txtfile:\n txtfile.writelines('Election Results\\n' + '-' * 25 + '\\n')\n txtfile.writelines(['Total Votes: ', str(total_vote)])\n txtfile.writelines('\\n' + '-' * 25 + '\\n')\n\n for line in candidate_count.keys():\n txtfile.writelines([line + ': ', str('{:.1%}'.format(candidate_count[line] / total_vote)),\n ' (' + str(candidate_count[line]) + ')' + '\\n'])\n\n txtfile.writelines('\\n' + '-' * 25 + '\\n')\n txtfile.writelines(['Winner: ',winner])\n txtfile.writelines('\\n' + '-' * 25 + '\\n')\n\n# print out vote results to screen\nwith open('vote_results.txt','r') as txtfile:\n for line in txtfile:\n print(line.rstrip())","repo_name":"nelsonxw/Python_Challenge","sub_path":"PyPoll/PyPoll.py","file_name":"PyPoll.py","file_ext":"py","file_size_in_byte":3980,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"15"} +{"seq_id":"17716143826","text":"import datetime\nimport uuid\nimport sys\nimport hep_rest_api\nfrom hep_rest_api import utils\n\nconfig = hep_rest_api.Configuration()\nconfig.host = 'xx'\n\napi_instance = hep_rest_api.RestApi(hep_rest.ApiClient(config))\napi_version = '1'\ndapp_id = 'xxx'\ndapp_key = 'xxx'\ndapp_secret = 'xx'\nprotocol = 'HEP'\nversion = '1.0'\nts = datetime.datetime.now().timestamp()\nnonce = uuid.uuid4().hex\nos = sys.platform\nlanguage = 'en'\ndapp_signature_method = 'HMAC-MD5'\ndapp_signature = ''\n\ndata = {\n 'api_version': api_version,\n 'dapp_id': dapp_id,\n 'dapp_key': dapp_key,\n 'protocol': protocol,\n 'version': version,\n 'ts': ts,\n 'nonce': nonce,\n 'os': os,\n 'language': language,\n 'dapp_signature_method': dapp_signature_method\n}\ndapp_signature = utils.sign_hmac(data, dapp_secret)\ndata['dapp_signature'] = dapp_signature\n\napi_response = api_instance.rest_dapps_read(**data)\nprint(api_response)\n","repo_name":"newtonproject/hep-sdk","sub_path":"rest/examples/python/basic_example.py","file_name":"basic_example.py","file_ext":"py","file_size_in_byte":905,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"15"} +{"seq_id":"69856579851","text":"from boto3.session import Session\n\nclass SagemakerClient:\n\n def __init__(self):\n self.client = Session(profile_name=\"default\").client(\"sagemaker\", region_name=\"us-west-2\")\n\n def submit_transform_job(self):\n\n model_name = self.client.list_models(\n NameContains=\"sample-model5\",\n SortOrder='Descending',\n SortBy='CreationTime')[\"Models\"][0][\"ModelName\"]\n\n transform_params = {\n \"TransformJobName\": \"sample-transform9\",\n \"ModelName\": model_name,\n \"MaxConcurrentTransforms\": 2,\n \"MaxPayloadInMB\": 50,\n \"BatchStrategy\": \"MultiRecord\",\n \"TransformOutput\": {\n \"S3OutputPath\": \"s3://test-ubuntu-sagemaker/output-data-prediction/\"\n },\n \"TransformInput\": {\n \"DataSource\": {\n \"S3DataSource\": {\n \"S3DataType\": \"S3Prefix\",\n \"S3Uri\": \"s3://test-ubuntu-sagemaker/input-data-prediction/\"\n }\n },\n \"ContentType\": \"text/csv\",\n \"SplitType\": \"Line\"\n },\n \"TransformResources\": {\n \"InstanceType\": \"ml.c4.xlarge\",\n \"InstanceCount\": 1\n }\n }\n\n self.client.create_transform_job(**transform_params)\n\nif __name__ == '__main__':\n SagemakerClient().submit_transform_job()\n","repo_name":"haruyasu/sagemaker-docker","sub_path":"sagemaker/submit_transform_job.py","file_name":"submit_transform_job.py","file_ext":"py","file_size_in_byte":1428,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"15"} +{"seq_id":"15305661548","text":"import unittest\nimport _6d4d\n\n\nclass WordSearch_Test(unittest.TestCase):\n def setUp(self):\n self.firstString = 'строка разбивается на набор строк через выравнивание по заданной ширине.'\n\n def test_split_string_0(self):\n self.assertEqual(_6d4d.SplitString(12, self.firstString), [\n 'строка',\n 'разбивается',\n 'на набор',\n 'строк через',\n 'выравнивание',\n 'по заданной',\n 'ширине.'\n ], f'Test for {self.firstString}')\n\n def test_split_string_1(self):\n self.assertEqual(_6d4d.SplitString(10, 'ab cd ef'), [\n 'ab cd ef'\n ])\n\n def test_split_string_2(self):\n self.assertEqual(_6d4d.SplitString(2, 'ab cd ef'), [\n 'ab',\n 'cd',\n 'ef'\n ])\n\n def test_split_string_3(self):\n self.assertEqual(_6d4d.SplitString(3, 'ab cd ef'), [\n 'ab',\n 'cd',\n 'ef'\n ])\n\n def test_split_string_4(self):\n self.assertEqual(_6d4d.SplitString(5, 'ab cd ef'), [\n 'ab cd',\n 'ef'\n ])\n\n\nif __name__ == '__main__':\n unittest.main()\n","repo_name":"michaelkutuzov/lambda_brain","sub_path":"6d4d/utest_6d4d.py","file_name":"utest_6d4d.py","file_ext":"py","file_size_in_byte":1293,"program_lang":"python","lang":"ru","doc_type":"code","stars":0,"dataset":"github-code","pt":"15"} +{"seq_id":"39974325371","text":"import json\nimport pathlib\nimport re\n\nfrom copy import deepcopy\n\n\"\"\"\nDon't remove any functions from here for posterity reasons.\n\"\"\"\n\n\ndef fix_availability(json_object, new_json_object):\n \"\"\"\n Recursively look for json objects with an availability property that's a string.\n Split that property into three new properties: availability_rating, availability_time, availability_unit\n Remove the old availabiilty property.\n\n :param json_object: The object to fix.\n :return: A fixed json.\n \"\"\"\n\n if type(json_object) is dict:\n for child_key in json_object.keys():\n try:\n child_value = json_object[child_key] # get the value from the key\n new_child_value = new_json_object[child_key]\n\n # if the key is called \"availability\" do our magic\n if child_key == \"availability\":\n split_availability(new_json_object)\n\n # recurse through if it's a _dict\n elif type(child_value) is dict:\n result = fix_availability(child_value, new_child_value)\n new_json_object[child_key] = result\n # this was used to debug a stupid error I made in the previous line where child_value was actually child_key\n except TypeError:\n # print(\"OBJECT: \" + str(json_object) + \" TYPE: \" + str(type(json_object)))\n print(\"KEY: \" + str(child_key) + \" TYPE: \" + str(type(child_key)))\n raise\n\n return new_json_object\n\n\ndef split_availability(new_json_object):\n old_availability = new_json_object[\"availability\"]\n del new_json_object[\"availability\"]\n if old_availability == \"NA\" or old_availability == \"always\":\n new_json_object[\"availability_rating\"] = 0\n new_json_object[\"availability_time\"] = 0\n new_json_object[\"availability_unit\"] = \"always\"\n else:\n split = re.split(r' |/', old_availability) # split the availabilty into three parts\n\n try:\n new_json_object[\"availability_time\"] = split[1]\n\n # set as int if we can, otherwise keep as string\n try:\n new_json_object[\"availability_rating\"] = int(split[0])\n except ValueError:\n new_json_object[\"availability_rating\"] = split[0]\n\n try:\n new_json_object[\"availability_time\"] = int(split[1])\n except ValueError:\n new_json_object[\"availability_time\"] = split[1]\n\n # availability unit is always a string\n new_json_object[\"availability_unit\"] = split[2]\n\n except IndexError:\n print(old_availability)\n raise\n\n return new_json_object\n\n\nif __name__ == \"__main__\":\n file_path = pathlib.Path.cwd().parent / \"src\" / \"Assets\" / \"SR3_Core.json\"\n new_file_path = pathlib.Path.cwd().parent / \"src\" / \"Assets\" / \"New_SR3_Core.json\"\n\n with open(file_path) as json_file:\n json_obj = json.loads(json_file.read())\n new_json_obj = deepcopy(json_obj) # make a deep copy of the json since this makes everything easier\n new_json_obj = fix_availability(json_obj, new_json_obj)\n with open(new_file_path, \"w\") as new_json_file:\n new_json_file.write(json.dumps(new_json_obj, indent=2))\n","repo_name":"apampuch/PySRCG","sub_path":"PySRCG/dev_tools/item_fixer.py","file_name":"item_fixer.py","file_ext":"py","file_size_in_byte":3297,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"15"} +{"seq_id":"10992628710","text":"#!/usr/bin/env python\n\nimport scapy.all as scapy\nimport time\nimport sys\n\n\ndef get_mac(ip):\n arp_request = scapy.ARP(pdst=ip)\n broadcast = scapy.Ether(dst=\"ff:ff:ff:ff:ff:ff\") # dst thanks to scapy.ls\n arp_request_broadcast = broadcast/arp_request\n answered_list = scapy.srp(arp_request_broadcast, timeout=1, verbose=False)[0]\n\n # return the mac address of the routor\n return answered_list[0][1].hwsrc\n\n\ndef spoof(target_ip, spoof_ip):\n target_mac = get_mac(target_ip)\n packet = scapy.ARP(op=2, pdst=target_ip, hwdst=target_mac, psrc=spoof_ip)\n # change mac address of the routor (ip 10.0.2.1 here) with the mac address of the VM kali linux\n # verbose to erase messages about packets\n scapy.send(packet, verbose=False)\n\n\ndef restore(destination_ip, source_ip):\n destination_mac = get_mac(destination_ip)\n source_mac = get_mac(source_ip)\n packet = scapy.ARP(op=2, pdst=destination_ip, hwdst=destination_mac, psrc=source_ip, hwsrc=source_mac)\n # to be sure we do it 4 times\n scapy.send(packet, count=4, verbose=False)\n\n\n# man in the middle\ntarget_ip = \"10.0.2.7\"\ngateway_ip = \"10.0.2.1\"\n# exception try except\ntry:\n # count the number of packets\n sent_packets_count = 0\n # loop to make man in the middle permanent\n while True:\n # tell the target that I'm the rooter\n spoof(\"10.0.2.7\", \"10.0.2.1\")\n # tell the rooter that I'm the target computer\n spoof(\"10.0.2.1\", \"10.0.2.7\")\n # increase the number of packets by 2\n sent_packets_count = sent_packets_count + 2\n # add , to delete \\n\n # add \\r to begin anew the line\n print(\"\\r[+] Packets sent: \" + str(sent_packets_count)),\n # don't keep on the buffer and print (not at the end of the program)\n sys.stdout.flush()\n # in python3 don't use sys and erase , after the print and od print(\"\\r.....,end=\"\")\n time.sleep(2)\nexcept KeyboardInterrupt:\n print(\"[+] Detected CTR + C ... Resetting ARP tables.... Please wait.\\n\")\n # restore the mac address of the rooter and the target\n restore(target_ip, gateway_ip)\n restore(gateway_ip, target_ip)\n","repo_name":"GuillaumeCleris/Ethical-hacking-python","sub_path":"048_057_ARP_spoofing.py","file_name":"048_057_ARP_spoofing.py","file_ext":"py","file_size_in_byte":2147,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"15"} +{"seq_id":"33440786216","text":"#!/usr/bin/env python\n# (Python 2 & python 3 compatible)\n# Get final balance of a bitcoin address from blockchain.info json\n# by circulosmeos //github.com/circulosmeos/bitcoin-in-tiny-pieces\n#\nimport sys\nimport fileinput\nimport re\nfrom time import sleep\n\ntry: # python3\n from urllib.request import urlopen\nexcept: # python2\n from urllib2 import urlopen\n\nVERBOSE = False # if True, all json is printed, and blockchain_tags are not filtered.\n\nBELL = True\nWARNING_WAITING_TIME = 0\n\nblockchain_tags = [ \n 'total_received',\n 'final_balance',\n ]\n\nSATOSHIS_PER_BITCOIN = 1e+8\n\n#\n# try to read parameters or stdin if they exist (in this order)\n#\naddress = ''\n# read parameter from cmdline\nif ( len(sys.argv) >= 2 ):\n address = sys.argv[1]\nelse:\n # tries to read stdin\n try:\n for address in fileinput.input('-'):\n break\n except:\n pass\n\n# check address (loose) correcteness\nm = re.match(r' *([a-zA-Z1-9]{1,34})', address)\nif ( m is not None ):\n address = m.group(1)\nelse:\n print( \"\\nBitcoin address invalid\\n\\n./bitcoin-get-address-balance [bitcoin address]\\n\" )\n exit(1)\n\n#\n# get address info from blockchain.info\n#\n\nreading=1\nwhile (reading):\n try:\n htmlfile = urlopen(\"https://blockchain.info/address/%s?format=json\" % address, timeout = 10)\n htmltext = htmlfile.read().decode('utf-8')\n reading = 0\n except:\n reading+=1\n print( \"... \" + str(reading) )\n sleep(60*reading)\n\nprint( \"\\naddress \\t= \" + address )\n\nif (VERBOSE):\n print (htmltext)\n exit(0)\n\nblockchain_info = []\ntag = ''\ntry:\n for tag in blockchain_tags:\n blockchain_info.append (\n float( re.search( r'%s\":(\\d+),' % tag, htmltext ).group(1) ) )\nexcept:\n print( \"Error processing tag '%s'.\" % tag );\n exit(1)\n\nfor i, coins in enumerate(blockchain_info):\n\n sys.stdout.write (\"%s \\t= \" % blockchain_tags[i])\n if coins > 0.0:\n print( \"%.8f Bitcoin\" % (coins/SATOSHIS_PER_BITCOIN) );\n else:\n print( \"0 Bitcoin\" );\n\n if (BELL and blockchain_tags[i] == 'final_balance' and coins > 0.0): \n # funny bell when something is found\n sys.stdout.write ('\\a\\a\\a\\a\\a\\a')\n sys.stdout.flush()\n if (WARNING_WAITING_TIME>0):\n sleep(WARNING_WAITING_TIME)\n else:\n exit (2)\n\nprint('')\n","repo_name":"circulosmeos/bitcoin-in-tiny-pieces","sub_path":"bitcoin-get-address-balance.py","file_name":"bitcoin-get-address-balance.py","file_ext":"py","file_size_in_byte":2343,"program_lang":"python","lang":"en","doc_type":"code","stars":34,"dataset":"github-code","pt":"15"} +{"seq_id":"13577925838","text":"'''\nThe goal of this script is to prepare data and then use it to train a NN to evaluate chess positions\nand then save it.\n\nAs training data i used a set of data that was created through one second evaluations (on one core)\nof chess board states by stockfish (version from 2015), the strongest CPU chess engine in\nthe world (currently, 2023). The dataset needed for evaluation came from the website chess.com\nand is stored in data.pgn. Here 50,000 \"events\" are listed, each corresponding to one game\nof chess which ended either in a draw, checkmate or stalemate.\nOne chess game lasts 40 moves on average (80 positions), so around 4*10^6 board states build\nour dataset.\n\nEach boardstate of every game is endcoded according to some representation.\nTherefore the position of each piece on the board together with their estimated initial values are our features.\nThe evaluation of the board state, which is in centipawns (cp), where 100 cp = 1 pawn, which is an arbritrary\nunit and is > 0 if white has the advantage and < 0 if black is winning, is our label that we have to predict.\n\n-----------------------------------------------------------------------------------------\n\nSince the portable game notation filetype (pgn) has a lot of unecessary information, at first\nI will filter it for the event (game played) and the moves.\n\nThen follows feeding each individual game into my chess engine and extracting each of the boardstates.\n\nAfter that Im merging the extracted data with the data from the corresponding evaluated positions in \nstockfish.csv, such that I have only boardstates with their corresponding evaluations in a file.\n\nSince chess uses non tabular data, I choose to work without using pandas.\n\n'''\n\nimport re\nfrom chess_module import *\nimport json\nimport random\n\ndef extract_moves(source_file, target_file):\n matches=[]\n # create a pattern for recognizing move counts, endgame results, + signs\n remove_patterns=re.compile(r\"\\d+\\.|\\d-\\d|\\d/\\d-\\d/\\d|\\+|x|#\") # pawn promotions are left in (eg. '=Q')\n with open(source_file) as source:\n for line in source:\n line=line.strip()\n if not line or line.startswith(\"[\"): # ignore empty lines and lines which start with [\n continue\n else:\n if line.startswith(\"1. \"): # detect new match\n matches.append([])\n cleaned_line=re.sub(remove_patterns, \"\", line) # removing what matches patterns\n moves_string=cleaned_line.split() # splits strings with whitespace delimiters\n matches[-1].extend(moves_string)\n \n json_data=json.dumps(matches)\n \n with open(target_file, \"w\") as target:\n target.write(json_data)\n \ndef generate_board_states_board_rep(source_file, target_dir): # uses lots of RAM\n boards=[]\n gamestate=chess_board()\n count=0\n with open(source_file, \"r\") as source:\n json_data=source.read()\n matches=json.loads(json_data)\n for match in matches:\n gamestate.reset_board()\n count+=1\n print(\"Generating board states of game number: \", count)\n for move in match:\n gamestate.make_move_UCI(move)\n gamestate.whites_turn = not gamestate.whites_turn\n rep=gamestate.convert_to_board_representation()\n boards.append(rep)\n \n # save boards into a file\n boards=np.array(boards)\n np.save(target_dir+\"boards_board_representation.npy\", boards)\n\ndef combine_evals_with_board_rep(eval_file, boards_rep_file, target_file): # USES APPROX 12GB of RAM (large dataset)\n boards=np.load(boards_rep_file)\n boards=boards.tolist()\n eval_scores=[]\n \n remove_pattern=re.compile(r\"^\\d+,\")\n \n with open(eval_file) as evals:\n for line in evals:\n if re.match(r\"^\\d\", line):\n cleaned_line=re.sub(remove_pattern, \"\", line)\n eval_scores_for_match=cleaned_line.split()\n if not eval_scores_for_match:\n eval_scores.append(\"\") # keep dimensions equal\n eval_scores.extend(eval_scores_for_match)\n else:\n continue\n \n labeled_data=[]\n \n for i in range(len(eval_scores)):\n if eval_scores[i]!='NA' and eval_scores[i]!='': # remove NA (no stockfish evaluation) and instant resigns (no moves played)\n labeled_data.append([boards[i], int(eval_scores[i])])\n else:\n print(i)\n \n random.shuffle(labeled_data)\n \n batch=labeled_data[:1000000] # first million entries\n \n with open(target_file+\"_batch.json\", 'w') as source:\n json.dump(batch, source)\n \n with open(target_file+\".json\", 'w') as source:\n json.dump(labeled_data, source)\n \n \n'''\nExtract the moves from the data and write them into a JSON file:\n'''\n\n# extract_moves(\"data/evaluated_positions/data.pgn\", \"data/evaluated_positions/extracted_moves.json\")\n\n'''\nGenerate board states from the extracted moves, and write them ordered into a numpy array:\n'''\n\n# generate_board_states_board_rep(\"data/evaluated_positions/extracted_moves.json\", \"data/evaluated_positions/\")\n\n'''\nNow get board evaluations from stockfish.csv and pair them with corresponding board states to form our base dataset for the NN:\n'''\n\n# combine_evals_with_board_rep(\"data/evaluated_positions/stockfish.csv\", \"data/evaluated_positions/boards_board_representation.npy\", \"data/evaluated_positions/labeled_data_board_rep\")\n\n#-------------------------------------------------------------------------------------------------------------\n# TRAINING OF MODEL\n\nimport tensorflow as tf\nfrom tensorflow.keras.optimizers import SGD\nfrom tensorflow.keras.models import Sequential, load_model\nfrom tensorflow.keras.layers import Dense\nfrom tensorflow.python.client import device_lib\nimport matplotlib.pyplot as plt\n\n# with open(\"data/evaluated_positions/labeled_data_board_rep.json\", 'r') as source:\n # dataset=source.read()\n # dataset=json.loads(dataset)\n # X_train=[subset[0] for subset in dataset]\n # y_train=[subset[1] for subset in dataset]\n\n# print(device_lib.list_local_devices())\n\n# X_train=tf.constant(X_train, dtype=tf.float32)\n# y_train=tf.constant(y_train, dtype=tf.float32)\n\n\n\n# max_abs=tf.reduce_max(tf.math.abs(y_train))\n\n# # # plt.hist(y_train, 20)\n# # # plt.savefig(\"data/evaluated_positions/label_distribution.png\")\n\n# y_train=y_train/max_abs # scaled to -1 1\n# # # tf.print(y_train)\n\n# # plt.hist(y_train, 20)\n# # plt.savefig(\"data/evaluated_positions/label_distribution_normalized.png\")\n\n\n\n# # Neural Network\n\n# # initialize model:\n\n# callback=tf.keras.callbacks.EarlyStopping(monitor='val_loss', patience=5, min_delta=1e-4)\n\n# model=Sequential()\n# model.add(Dense(units=64, input_shape=(64,)))\n# model.add(Dense(units=256, activation='tanh')) \n# model.add(Dense(units=256, activation='relu'))\n# model.add(Dense(units=256, activation='relu'))\n# model.add(Dense(units=1, activation='tanh'))\n\n# model.compile(loss='mae', optimizer=SGD(learning_rate=0.001) , metrics='mae')\n\n# history=model.fit(X_train, y_train, batch_size=128, steps_per_epoch=10000, epochs=1000, callbacks=[callback], validation_split=0.05)\n\n# print(len(history.history['loss']))\n\n# model.save(\"data/large_models/model_mae_3_layer_tanh_relu_wide_uniform\")\n\n\n# -------------------------\n# Testing\n\n\nchess_board_test=chess_board()\nchess_board_test.reset_board()\nx_test=chess_board_test.convert_to_board_representation().reshape(1,64)\nprint(x_test)\nprint(np.shape(x_test))\nprint(x_test.dtype)\n\n\nmodel=load_model(\"data/large_models/model_mae_3_layer_tanh_relu_wide_uniform\")\nprint(model.input[0].shape)\nprint(model.input[0].dtype)\n\n\n\ny_predict=model(x_test, training=False) # faster than predict\n\n\n\ntf.print(y_predict[0,0])","repo_name":"Marcus1506/Chess_AI","sub_path":"chess_board_eval_AI.py","file_name":"chess_board_eval_AI.py","file_ext":"py","file_size_in_byte":7778,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"15"} +{"seq_id":"8823662696","text":"# -*- coding: utf-8 -*-\r\n\"\"\"\r\nCreated on Thu Dec 30 13:12:50 2021\r\n\r\n@author: parkk\r\n\"\"\"\r\n\r\n# ■ 파이썬으로 iris 데이터의 서포트 벡터 머신 모델 생성하기\r\n\r\n# 1. 데이터 로드\r\nimport pandas as pd\r\niris = pd.read_csv(\"c:\\\\data\\\\iris2.csv\")\r\n\r\n# 2. min/max 정규화하기\r\nx = iris.iloc[ : , 0:4 ]\r\ny = iris[ 'Species' ]\r\n\r\nfrom sklearn.preprocessing import MinMaxScaler\r\n\r\nscaler = MinMaxScaler()\r\nscaler.fit(x)\r\n\r\nx_scaled = scaler.transform(x)\r\n\r\n# 3. 훈련/테스트 데이터 분리\r\nfrom sklearn.model_selection import train_test_split\r\n\r\nx_train, x_test, y_train, y_test = train_test_split( x_scaled, y, test_size = 0.2, random_state = 1 )\r\n\r\n# 4. 모델 생성하기\r\nfrom sklearn import svm\r\n\r\nsvm_model = svm.SVC( kernel = 'rbf' )\r\n# 커널의 종류 : rbf, poly, sigmoid, linear\r\n\r\n#5. 모델 훈련\r\nsvm_model.fit( x_train, y_train )\r\n\r\n# 6. 모델 예측\r\nresult = svm_model.predict(x_test)\r\n\r\n# 7. 모델 평가\r\nprint ( sum( result == y_test ) / len(y_test) ) # 0.966667\r\n\r\n# gridsearch 의 자동튜닝 기능을 이용해서 위의 아이리스 모델의 성능을 더 올리시오 !\r\n\r\n# 힌트 :\r\n\r\n# 모델 생성\r\nfrom sklearn import svm\r\nfrom sklearn.model_selection import GridSearchCV\r\n\r\nparam_grid = { 'C' : [ 0.1, 1, 10, 100, 1000 ],\r\n\t\t\t'gamma' : [ 1, 0.1, 0.01, 0.001, 0.0001 ],\r\n\t\t\t'kernel' : [ 'rbf', 'poly', 'sigmoid', 'linear' ] }\r\n\r\ngrid = GridSearchCV( svm.SVC() , param_grid, refit = True, cv = 3 , n_jobs = -1, verbose =2 )\r\n\r\n# 설명 : refit = True 는 최적의 하이퍼 파라미터를 찾은 뒤 찾아낸 최적의 하이퍼 파라미터로 재학습시킨다.\r\n\r\n# 모델 훈련\r\ngrid.fit( x_train, y_train )\r\nprint( grid.best_params_ ) # {'C': 10, 'gamma': 1, 'kernel': 'linear'}\r\n\r\n# 6. 모델 예측\r\nresult = grid.predict(x_test)\r\n\r\n# 7. 모델 평가\r\nprint ( sum( result == y_test ) / len(y_test) ) # 0.966667 / 똑같이나옴\r\n\r\n# ��래의 3개의 머신러닝 모델의 조합으로 앙상블 모델을 만들어서 아이리스 품종을 분류하는\r\n# 머신러닝 모델을 만들고 정확도를 출력하시오 !\r\n# 모델 1: 서포트 벡터 머신 / 모델 2: 나이브 베이즈 / 모델 3 : 랜덤포레스트\r\n\t\t\r\n# 1. 데이터 로드\r\nimport pandas as pd\r\niris = pd.read_csv(\"c:\\\\data\\\\iris2.csv\")\r\n\r\n# 2. min/max 정규화하기\r\nx = iris.iloc[ : , 0:4 ]\r\ny = iris[ 'Species' ]\r\n\r\nfrom sklearn.preprocessing import MinMaxScaler\r\n\r\nscaler = MinMaxScaler()\r\nscaler.fit(x)\r\n\r\nx_scaled = scaler.transform(x)\r\n\r\n# 3. 훈련/테스트 데이터 분리\r\nfrom sklearn.model_selection import train_test_split\r\n\r\nx_train, x_test, y_train, y_test = train_test_split( x_scaled, y, test_size = 0.2, random_state = 1 )\r\n\r\n\r\n#3. 앙상블 모델생성\r\nfrom sklearn.svm import SVC\r\nfrom sklearn.naive_bayes import GaussianNB\r\n# from sklearn.linear_model import LogisticRegression\r\nfrom sklearn.ensemble import RandomForestClassifier\r\nfrom sklearn.ensemble import VotingClassifier #분류\r\n\r\nr1=SVC()\r\nr2=GaussianNB()\r\nr3=RandomForestClassifier()\r\n\r\neclf1=VotingClassifier(estimators=[ ('svc', r1), ('gnb', r2), ('rf', r3) ], voting='hard')\r\n\r\n#4. 훈련데이터, 테스트데이터 예측\r\ntrain_result=eclf1.fit(x_train, y_train).predict(x_train)\r\ntest_result=eclf1.fit(x_train, y_train).predict(x_test)\r\n\r\n\r\n#5. 정확도 확인\r\nprint(sum(train_result==y_train)/len(y_train)) # 0.966667\r\nprint(sum(test_result==y_test)/len(y_test)) # 0.966667\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n","repo_name":"parkgeonwo/Python-R-machine-learning","sub_path":"SVM/SVM-iris.py","file_name":"SVM-iris.py","file_ext":"py","file_size_in_byte":3493,"program_lang":"python","lang":"ko","doc_type":"code","stars":0,"dataset":"github-code","pt":"15"} +{"seq_id":"31916667095","text":"from random import randint\r\nn = int(input())\r\nfor _ in range(n):\r\n\tl1 = []\r\n\tstart = -23452132\r\n\tend = 234341232\r\n\tsize = randint(1, 30)\r\n\tprint(size)\r\n\tfor i in range(size):\r\n\t\tl1.append(randint(start, end))\r\n\tprint(*l1)","repo_name":"ayushman-25/Codechef-Submissions","sub_path":"RANDOM.py","file_name":"RANDOM.py","file_ext":"py","file_size_in_byte":221,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"15"} +{"seq_id":"9977430651","text":"import json\nfrom django.contrib import auth\nfrom django.contrib import messages\nfrom django.contrib.auth.decorators import login_required\nfrom django.http import HttpResponse, HttpResponseRedirect\nfrom django.shortcuts import render, redirect, get_object_or_404\nfrom django.urls import reverse, reverse_lazy\nfrom django.views.generic import TemplateView\nfrom users.forms import ExperienceForm\nfrom jobapp.models import Resume\nfrom jobapp.permission import user_is_employee\nfrom users.forms import *\nfrom django.core.paginator import Paginator\nimport os\n\n\nclass ProfilePageView(TemplateView):\n template_name = \"users/profile.html\"\n\n\ndef get_success_url(request):\n \"\"\"\n Handle Success Url After LogIN\n\n \"\"\"\n if 'next' in request.GET and request.GET['next'] != '':\n return request.GET['next']\n else:\n return reverse('jobapp:home')\n\n\ndef employee_registration(request):\n \"\"\"\n Handle Employee Registration\n\n \"\"\"\n form = EmployeeRegistrationForm(request.POST or None)\n if form.is_valid():\n form = form.save()\n return redirect('users:login')\n context = {\n\n 'form': form\n }\n\n return render(request, 'users/employee-registration.html', context)\n\n\ndef employer_registration(request):\n \"\"\"\n Handle Employee Registration\n\n \"\"\"\n\n form = EmployerRegistrationForm(request.POST or None)\n if form.is_valid():\n form = form.save()\n return redirect('users:login')\n context = {\n\n 'form': form\n }\n\n return render(request, 'users/employer-registration.html', context)\n\n\n@login_required(login_url=reverse_lazy('users:login'))\n@user_is_employee\ndef employee_edit_profile(request, id=id):\n \"\"\"\n Handle Employee Profile Update Functionality\n\n \"\"\"\n\n user = get_object_or_404(User, id=id)\n form = EmployeeProfileEditForm(request.POST or None, instance=user)\n if form.is_valid():\n form = form.save()\n messages.success(request, 'Your Profile Was Successfully Updated!')\n return redirect(reverse(\"users:edit-profile\", kwargs={\n 'id': form.id\n }))\n context = {\n\n 'form': form\n }\n\n return render(request, 'users/employee-edit-profile.html', context)\n\n\ndef user_login(request):\n \"\"\"\n Provides users to logIn\n\n \"\"\"\n\n form = UserLoginForm(request.POST or None)\n\n if request.user.is_authenticated:\n return redirect('/')\n\n else:\n if request.method == 'POST':\n if form.is_valid():\n auth.login(request, form.get_user())\n return HttpResponseRedirect(get_success_url(request))\n context = {\n 'form': form,\n }\n\n return render(request, 'users/login.html', context)\n\n\ndef user_logout(request):\n \"\"\"\n Provide the ability to logout\n \"\"\"\n auth.logout(request)\n # messages.success(request, 'You are Successfully logged out')\n return redirect('users:login')\n\n\ndef resume_add(request):\n\n form = ResumeForm(request.POST, request.FILES)\n user = get_object_or_404(User, id=request.user.id)\n \n if request.method == 'POST':\n\n if form.is_valid():\n instance = form.save(commit=False)\n instance.user = user\n instance.save()\n form.save()\n return redirect(reverse('users:show-resume', kwargs={'id': user.id }))\n context = {\n 'form': form,\n\n\n }\n\n return render(request, 'users/employee-resume.html', context)\n \n\ndef show_resume(request, id):\n \"\"\"\n Смотреть детали резюме\n \"\"\"\n resumes = Resume.objects.filter(user_id=id) \n experience = Experience.objects.filter(user_id=id)\n education = Education.objects.filter(user_id=id) \n context = {'resume': resumes, 'experience': experience, 'education': education}\n return render(request, 'users/show_resumes.html', context)\n\n\ndef experience_add(request):\n form = ExperienceForm(request.POST, request.FILES)\n user = get_object_or_404(User, id=request.user.id)\n if request.method == 'POST':\n\n if form.is_valid():\n instance = form.save(commit=False)\n instance.user = user\n instance.save()\n form.save()\n return redirect(reverse('users:show-resume', kwargs={'id': user.id }))\n else:\n messages.error(request, 'Не все поля заполнены')\n\n context = {\n 'form': form,\n\n\n }\n\n return render(request, 'users/experience.html', context)\n\n\ndef education_add(request):\n form = EducationForm(request.POST, request.FILES)\n user = get_object_or_404(User, id=request.user.id)\n if request.method == 'POST': \n if form.is_valid():\n instance = form.save(commit=False)\n instance.user = user\n instance.save()\n form.save()\n return redirect(reverse('users:show-resume', kwargs={'id': user.id }))\n else:\n messages.error(request, 'Не все поля заполнены')\n\n context = {\n 'form': form,\n\n\n }\n\n return render(request, 'users/education.html', context)\n\n\ndef resume_list_view(request):\n \"\"\"\n Отобразить список вакансий\n \"\"\"\n resume_list = Resume.objects.all().order_by('-created_at')\n paginator = Paginator(resume_list, 12)\n page_number = request.GET.get('page')\n page_obj = paginator.get_page(page_number)\n\n context = {\n\n 'page_obj': page_obj,\n\n }\n return render(request, 'users/resume-list.html', context)\n\n\ndef resume_single(request, id):\n resume = Resume.objects.filter(user_id=id)\n experience = Experience.objects.filter(user_id=id)\n education = Education.objects.filter(user_id=id)\n context = {\n 'resume': resume,\n 'experience': experience,\n 'education': education,\n\n }\n\n return render(request, 'users/single-resume.html', context)\n\n\n@login_required(login_url=reverse_lazy('users:login'))\n@user_is_employee\ndef employee_edit_resume(request, id=id):\n \"\"\"\n Handle Employee Resume Update Functionality\n\n \"\"\"\n\n resume = Resume.objects.filter(user_id=id).first()\n experience = Experience.objects.filter(user_id=id).first()\n education = Education.objects.filter(user_id=id).first()\n\n if not resume:\n return redirect('users:add-resume')\n else:\n form = ResumeForm(instance=resume)\n form2 = ExperienceForm(instance=experience)\n form3 = EducationForm(instance=education)\n if request.method=='POST':\n form3 = EducationForm(request.POST,request.FILES,instance=education)\n form = ResumeForm(request.POST,request.FILES,instance=resume)\n form2 = ExperienceForm(request.POST,request.FILES,instance=experience)\n user = get_object_or_404(User, id=request.user.id)\n \n if form.is_valid():\n instance = form.save(commit=False)\n instance.user = user\n instance.save()\n form.save()\n if form2.is_valid:\n instance = form2.save(commit=False)\n instance.user = user\n instance.save()\n form2.save()\n if form2.is_valid:\n instance = form3.save(commit=False)\n instance.user = user\n instance.save()\n form3.save()\n \n messages.success(request, 'Ваше резюме успе��но обновлено!')\n return redirect(reverse(\"users:show-resume\", kwargs={'id': resume.user_id }))\n else:\n messages.error(request, {request.error})\n \n context = {\n 'resume': resume,\n 'form': form,\n 'form2': form2,\n 'form3': form3\n \n }\n\n return render(request, 'users/employee-edit-resume.html', context)\n\n \n\n","repo_name":"rexema/workfinder","sub_path":"users/views.py","file_name":"views.py","file_ext":"py","file_size_in_byte":7954,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"17"} +{"seq_id":"16599669960","text":"\"\"\"Calculates Errors in a Design\"\"\"\n\nfrom src.Oscillators import t\nfrom src.Oscillators import util\nfrom src.Oscillators import solver\n\nimport numpy as np\n\nSOLVER = solver.Solver()\nSOLVER.solve()\nMAX_FEASIBLEDEV = 1\n\n\nclass DesignError(object):\n\n def __init__(self, designer):\n self.designer = designer\n self.solver = SOLVER\n if designer.k2 is None:\n designer.find()\n # Outputs\n self.feasibledev = None\n self.alphadev = None\n self.phidev = None\n self.prediction_error = None\n\n def calculate(self):\n \"\"\"Evaluates the fit.\n \"\"\"\n # Check results of the finder\n if not self.designer.is_success:\n self.feasibledev = MAX_FEASIBLEDEV\n return\n # Completed the optimization\n oc1, oc2 = SOLVER.getOscillatorCharacteristics(dct=self.designer.params)\n if self.designer.is_x1:\n oc = oc1\n else:\n oc = oc2\n x_vec = util.getSubstitutedExpression(SOLVER.x_vec, self.designer.params) \n x1_vec, x2_vec = x_vec[0], x_vec[1]\n x1_arr = np.array([float(x1_vec.subs({t: v})) for v in self.designer.times])\n x2_arr = np.array([x2_vec.subs({t: v}) for v in self.designer.times])\n arr = np.concatenate([x1_arr, x2_arr])\n self.feasibledev = sum(arr < -1e6)/len(arr)\n self.alphadev = oc.alpha/self.designer.alpha - 1\n self.phidev = self.designer.phi - oc.phi\n sign = np.sign(self.phidev)\n adj_phidev = min(np.abs(2*np.pi - np.abs(self.phidev)), np.abs(self.phidev))\n self.phidev = sign*adj_phidev/(2*np.pi)\n self.prediction_error = self._evaluatePredictions()\n \n def _evaluatePredictions(self):\n \"\"\"\n Evaluates the predicted values of S1 and S2.\n\n Returns:\n float: fraction error\n \"\"\"\n predicted_df = self.solver.simulate(param_dct=self.designer.params, expression=self.solver.x_vec, is_plot=False)\n simulated_df = util.simulateRR(param_dct=self.designer.params, end_time=self.designer.end_time,\n num_point=self.designer.num_point, is_plot=False)\n error_ssq = np.sum(np.sum(predicted_df - simulated_df)**2)\n total_ssq = np.sum(np.sum(simulated_df)**2)\n prediction_error = error_ssq/total_ssq\n return prediction_error\n\n def __lt__(self, other):\n \"\"\"\n Checks if the design error of this object is less than another. Must have already called calculate().\n\n Args:\n other: DesignError\n Returns:\n bool\n \"\"\"\n def isLessThan(x, y):\n if x is None:\n return False\n if y is None:\n return True\n return np.abs(x) < np.abs(y)\n #\n if isLessThan(self.feasibledev, other.feasibledev):\n return True\n if isLessThan(other.feasibledev, self.feasibledev):\n return False\n if isLessThan(self.alphadev, other.alphadev):\n return True\n if isLessThan(other.alphadev, self.alphadev):\n return False\n if isLessThan(self.phidev, other.phidev):\n return True\n if isLessThan(other.phidev, self.phidev):\n return False\n return self.designer.ssq < other.designer.ssq\n \n def __repr__(self):\n return \"feasibledev=%s, alphadev=%s, phidev=%s, prediction_error=%s\" % (\n self.feasibledev, self.alphadev, self.phidev, self.prediction_error)","repo_name":"ModelEngineering/Oscillators","sub_path":"src/Oscillators/design_error.py","file_name":"design_error.py","file_ext":"py","file_size_in_byte":3521,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"17"} +{"seq_id":"16416704226","text":"# coding:utf-8\n\nimport sys\n\nimport logging\nfrom logging import handlers\n\nfrom samson.base.image import ImageItem\nfrom samson.base.log import log\n\n# 日志打印模块\nlogger = logging.getLogger('samson')\nlogger.setLevel(level=logging.INFO)\n_debug_log_format = '%(asctime)s - %(levelname)s - %(filename)s:%(funcName)s:%(lineno)d:\\n%(message)s'\n_file_handler = logging.handlers.TimedRotatingFileHandler(filename='../../app/log/samson.log', when='midnight')\n_file_handler.setFormatter(fmt=logging.Formatter(fmt=_debug_log_format))\nlogger.addHandler(hdlr=_file_handler)\n\n\nclass Samson(object):\n \"\"\"\n\n \"\"\"\n config = dict()\n\n def __init__(self):\n \"\"\"\n 初始化\n \"\"\"\n pass\n\n @log\n def apply_config(self, config):\n \"\"\"\n 生效配置文件\n :param config:\n :return:\n \"\"\"\n self.config = config.__dict__\n\n @log\n def thumbnails_for_post(self, path=None):\n \"\"\"\n 一键生成带边框和exif信息的缩略图\n :return:\n \"\"\"\n _file = sys.argv[1] if len(sys.argv) > 1 else path\n image = ImageItem(path=_file)\n # image.image.show()\n # print out\n split = _file.rfind('/')\n out = _file[:split + 1] + \"samson_\" + _file[split + 1:]\n # print out\n image.thumbnails_for_post(out=out)\n\n\n# 实例化\nsamson = Samson()\n","repo_name":"zzhoo8/samson","sub_path":"samson/__init__.py","file_name":"__init__.py","file_ext":"py","file_size_in_byte":1372,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"17"} +{"seq_id":"20975189085","text":"class Cow:\n def __init__(self, direction, x, y, cow_id):\n self.x = x\n self.y = y\n self.cow_id = cow_id\n self.direction = direction\n self.blocked_by = None # we want to know who blocked the cow (id number)\n self.blocked = 0 # number of blocked cows\n\nnum_cows = int(input())\n\nall_cows = []\nnorth_cows = []\neast_cows = []\n\n# initializing data for cows\nfor i in range(num_cows):\n cow_info = input().split()\n new_cow = Cow(cow_info[0], int(cow_info[1]), int(cow_info[2]), i)\n if new_cow.direction == 'N':\n north_cows.append(new_cow)\n else:\n east_cows.append(new_cow)\n all_cows.append(new_cow)\n\n# sort cows from closest to farthest (i used insertion sort)\nfor i in range(1, len(north_cows)):\n arr_idx = i\n while arr_idx > 0 and north_cows[arr_idx].x < north_cows[arr_idx - 1].x:\n temp = north_cows[arr_idx]\n north_cows[arr_idx] = north_cows[arr_idx - 1]\n north_cows[arr_idx - 1] = temp\n arr_idx -= 1\nfor i in range(1, len(east_cows)):\n arr_idx = i\n while arr_idx > 0 and east_cows[arr_idx].y < east_cows[arr_idx - 1].y:\n temp = east_cows[arr_idx]\n east_cows[arr_idx] = east_cows[arr_idx - 1]\n east_cows[arr_idx - 1] = temp\n arr_idx -= 1\n\nfor i in range(len(north_cows)):\n for j in range(len(east_cows)):\n if north_cows[i].y < east_cows[j].y and north_cows[i].x > east_cows[j].x and not east_cows[j].blocked_by:\n intersection = (north_cows[i].x, east_cows[j].y)\n x_distance = intersection[0] - east_cows[j].x\n y_distance = intersection[1] - north_cows[i].y\n if x_distance > y_distance: # north cow will cut off east cow\n east_cows[j].blocked_by = north_cows[i].cow_id\n north_cows[i].blocked += 1\n north_cows[i].blocked += east_cows[j].blocked\n elif y_distance > x_distance: # east cow will cut off north cow and we do not need to consider farther away cows\n east_cows[j].blocked += 1\n east_cows[j].blocked += north_cows[i].blocked\n all_cows[east_cows[j].cow_id].blocked = east_cows[j].blocked\n break\n else: # nothing happens when both cows arrive at the same cell at the same time\n pass\n all_cows[north_cows[i].cow_id].blocked = north_cows[i].blocked\n\nfor i in range(len(all_cows)):\n print(all_cows[i].blocked)\n\n","repo_name":"liunar1/USACO","sub_path":"Silver/2020/decproblem3.py","file_name":"decproblem3.py","file_ext":"py","file_size_in_byte":2449,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"17"} +{"seq_id":"28706450744","text":"import sys\nN = int(sys.stdin.readline())\narr = list(map(int, sys.stdin.readline().split()))\n\nleft, right = 0, len(arr)-1\narr.sort()\nsub = 2000000000 # 1000000000, 1000000000인 경우\nanswer = []\nwhile True:\n if left >= right:\n break\n\n S = abs(arr[left] + arr[right])\n\n if sub >= S:\n sub = S\n answer = [arr[left], arr[right]]\n\n if abs(arr[left]) >= abs(arr[right]):\n left += 1\n else:\n right -= 1\n\nprint(*answer, sep=' ')\n\n'''\ninput:\n5\n-1 -2 2 0 99\noutput:\n-2 2\n\n2\n1000000000 1000000000\n\n\n'''","repo_name":"studying-ice-bear/codingtest-study","sub_path":"김유진/단계별로 풀어보기/week11~14/TwoPointer/bj2470.py","file_name":"bj2470.py","file_ext":"py","file_size_in_byte":544,"program_lang":"python","lang":"en","doc_type":"code","stars":3,"dataset":"github-code","pt":"17"} +{"seq_id":"33363120680","text":"\"\"\"\nMain testing script\n2 plots: learnt policies, terminal reward\nStatistical arbitrage example\n\"\"\"\n# numpy\nimport numpy as np\n# plotting\nimport matplotlib.pyplot as plt\nfrom scipy.stats import gaussian_kde\n# pytorch\nimport torch as T\n# personal files\nfrom utils import directory, cmap, colors\nfrom hyperparams import init_params, print_params\nfrom models import PolicyANN, VaRANN, DiffCVaRANN\nfrom risk_measures import RiskMeasure\nfrom envs import Environment\nfrom agents import Agent\n# misc\nfrom pdb import set_trace\n\n\"\"\"\nParameters\n\"\"\"\n\nrm_labels = ['CVaR0.5', 'CVaR0.8', 'CVaR0.9'] # risk measures used\nseed = 4321 # set seed for replication purposes\nNsimulations = 30_000 # number of simulations following the optimal strategy\n\n_, envParams, algoParams = init_params()\nrepo = \"set1\" # repo name\n\n\"\"\"\nEnd of Parameters\n\"\"\"\n\n# print all parameters for reproducibility purposes\nprint('\\n*** Name of the repository: ', repo, ' ***\\n')\nprint_params(envParams, algoParams)\n\ndirectory(repo) # create the directory\n\nenv = Environment(envParams) # create the environment\n\ncosts = np.zeros((Nsimulations, envParams[\"Ndt\"], len(rm_labels))) # matrix to store all testing trajectories\n\nfor idx_method, method in enumerate(rm_labels):\n # print progress\n print('\\n*** Method = ', method, ' ***\\n')\n\n # create ANNs for policy, VaR and DiffCVaR\n policy = PolicyANN(input_size=3,\n hidden_size=algoParams[\"hidden_pi\"],\n n_layers=algoParams[\"layers_pi\"],\n env=env,\n learn_rate=algoParams[\"lr_pi\"])\n VaR_main = VaRANN(input_size=3,\n hidden_size=algoParams[\"hidden_V\"],\n n_layers=algoParams[\"layers_V\"],\n env=env,\n learn_rate=algoParams[\"lr_V\"])\n DiffCVaR_main = DiffCVaRANN(input_size=3,\n hidden_size=algoParams[\"hidden_V\"],\n n_layers=algoParams[\"layers_V\"],\n env=env,\n learn_rate=algoParams[\"lr_V\"])\n \n # initialize the actor-critic algorithm\n actor_critic = Agent(env=env,\n risk_measure=[],\n policy=policy,\n VaR_main=VaR_main,\n VaR_target=[],\n DiffCVaR_main=DiffCVaR_main,\n DiffCVaR_target=[])\n\n # load the trained model\n actor_critic.load_models(repo = repo + '/' + method)\n\n ##############################################################################\n ########################### TESTING PHASE ############################\n\n # set seed for reproducibility purposes\n T.manual_seed(seed)\n np.random.seed(seed)\n\n # initialize the starting state\n time_t, s_t, q_t = env.reset(Nsimulations)\n \n for t_idx in env.spaces[\"t_space\"]:\n # simulate transitions according to the policy\n action_t, _ = actor_critic.select_actions(time_t, s_t, q_t, 'best')\n time_t, s_t, q_t, cost_t = env.step(time_t, s_t, q_t, action_t)\n\n # store costs\n costs[:,t_idx,idx_method] = cost_t.detach().numpy()\n\n # print progress\n print('*** Testing phase completed! ***')\n\n ########################### END OF TESTING ###########################\n ##############################################################################\n\n ##############################################################################\n ##################### learnt policy at every time ####################\n \n # figure parameters\n plt.rcParams.update({'font.size': 16, 'figure.figsize': (10,7)})\n plt.rc('axes', labelsize=20)\n\n for t_idx, t_val in enumerate(env.spaces[\"t_space\"]): \n # initialize 2D histogram\n hist2dim_policy = np.zeros([len(env.spaces[\"s_space\"]), len(env.spaces[\"q_space\"])])\n\n for s_idx, s_val in enumerate(env.spaces[\"s_space\"]):\n for q_idx, q_val in enumerate(env.spaces[\"q_space\"]):\n # best action according to the policy\n hist2dim_policy[len(env.spaces[\"s_space\"])-s_idx-1, q_idx], _ = \\\n actor_critic.select_actions(t_val*T.ones(1, device=actor_critic.device),\n s_val*T.ones(1, device=actor_critic.device),\n q_val*T.ones(1, device=actor_critic.device),\n 'best')\n\n # plot the 2D histogram\n plt.imshow(hist2dim_policy,\n interpolation='none',\n cmap=cmap,\n extent=[np.min(env.spaces[\"q_space\"]),\n np.max(env.spaces[\"q_space\"]),\n np.min(env.spaces[\"s_space\"]),\n np.max(env.spaces[\"s_space\"])],\n aspect='auto',\n vmin=env.params[\"min_u\"],\n vmax=env.params[\"max_u\"])\n \n plt.title('Learned; Period:' + str(t_idx))\n plt.xlabel(\"Inventory\")\n plt.ylabel(\"Price\")\n cbar = plt.colorbar()\n cbar.set_ticks([env.params[\"min_u\"],-1,0,1,env.params[\"max_u\"]])\n cbar.set_ticklabels([env.params[\"min_u\"],-1,0,1,env.params[\"max_u\"]])\n plt.tight_layout()\n plt.savefig(repo + '/best_actions-' + method + '-period' + str(t_idx) + '.pdf', transparent=True)\n plt.clf()\n\n ##################### learnt policy at every time ####################\n ##############################################################################\n\n ##############################################################################\n ##################### learnt policy in one figure ####################\n \n # figure parameters\n plt.rcParams.update({'font.size': 16, 'figure.figsize': (10,4)})\n plt.rc('axes', labelsize=20)\n\n for t_idx, t_val in enumerate([0, int(env.spaces[\"t_space\"][-1]/2.0), env.spaces[\"t_space\"][-1]]):\n # allocate the subplot\n plt.subplot(1, 3, t_idx+1)\n \n # initialize 2D histogram\n hist2dim_policy = np.zeros([len(env.spaces[\"s_space\"]), len(env.spaces[\"q_space\"])])\n\n for s_idx, s_val in enumerate(env.spaces[\"s_space\"]):\n for q_idx, q_val in enumerate(env.spaces[\"q_space\"]):\n # best action according to the policy\n hist2dim_policy[len(env.spaces[\"s_space\"])-s_idx-1, q_idx], _ = \\\n actor_critic.select_actions(t_val*T.ones(1, device=actor_critic.device),\n s_val*T.ones(1, device=actor_critic.device),\n q_val*T.ones(1, device=actor_critic.device),\n 'best')\n\n # plot the 2D histogram\n plt.imshow(hist2dim_policy,\n interpolation='none',\n cmap=cmap,\n extent=[np.min(env.spaces[\"q_space\"]),\n np.max(env.spaces[\"q_space\"]),\n np.min(env.spaces[\"s_space\"]),\n np.max(env.spaces[\"s_space\"])],\n aspect='auto',\n vmin=env.params[\"min_u\"],\n vmax=env.params[\"max_u\"])\n \n plt.title('Learned; Time:' + str(t_val))\n plt.xlabel(\"Inventory\")\n plt.ylabel(\"Price\")\n plt.tight_layout()\n\n plt.colorbar()\n plt.tight_layout()\n plt.savefig(repo + '/best_actions-' + method + '.pdf', transparent=True)\n plt.clf()\n\n ##################### learnt policy in one figure ####################\n ##############################################################################\n\n\n##############################################################################\n################## distribution of terminal reward ###################\n\n# figure parameters\nplt.rcParams.update({'font.size': 16, 'figure.figsize': (10,7)})\nplt.rc('axes', labelsize=20)\n\n# plot rewards instead of costs\nrewards_total = -1 * np.sum(costs, axis=1)\n\n# set a grid for the histogram\ngrid = np.linspace(-0.2, 0.4, 100)\n\nfor idx_method, method in enumerate(rm_labels):\n # plot the histogram for each method\n plt.hist(x=rewards_total[:,idx_method],\n alpha=0.4,\n bins=grid,\n color=colors[idx_method],\n density=True)\n\nplt.legend(rm_labels)\nplt.xlabel(\"Terminal reward\")\nplt.ylabel(\"Density\")\nplt.title(\"Distribution of the terminal reward\")\n\nfor idx_method, method in enumerate(rm_labels):\n # plot gaussian KDEs\n kde = gaussian_kde(rewards_total[:,idx_method], bw_method='silverman')\n plt.plot(grid,\n kde(grid),\n color=colors[idx_method],\n linewidth=1.5)\n\n # plot quantiles of the distributions\n plt.axvline(x=np.quantile(rewards_total[:,idx_method],0.1),\n linestyle='dashed',\n color=colors[idx_method],\n linewidth=1.0)\n plt.axvline(x=np.quantile(rewards_total[:,idx_method],0.9),\n linestyle='dashed',\n color=colors[idx_method],\n linewidth=1.0)\n\nplt.xlim(-0.2,0.4)\nplt.tight_layout()\nplt.savefig(repo + '/comparison_terminal_cost.pdf', transparent=True)\nplt.clf()\n\n################## distribution of terminal reward ###################\n##############################################################################","repo_name":"acoache/RL-ElicitableDynamicRisk","sub_path":"StatisticalArbitrage/main_testing.py","file_name":"main_testing.py","file_ext":"py","file_size_in_byte":9477,"program_lang":"python","lang":"en","doc_type":"code","stars":3,"dataset":"github-code","pt":"17"} +{"seq_id":"71540010583","text":"import numpy as np\nfrom datetime import datetime\n\ndef output_motab(table,savedir=None, title=None):\n\t'''\n\toutput the .motab table fiel\n\t'''\n\tf=open(savedir, 'w')\n\tf.write('#1\\n')\n\n\tif table.ndim==2:\n\t\t# size of the lookup table\n\t\tm=np.shape(table)[0]-2\n\t\tn=np.shape(table)[1]-2\n\t\tf.write('double optics(%s, %s)\\n'%(m,n))\n\n\t\thour_angle=table[2, 3:]\n\t\tdeclination=table[3:,2]\n\n\t\tfor i in range(m):\n\t\t\tif i ==0:\n\t\t\t\trow_i=np.append(0, hour_angle)\n\t\t\telse:\n\t\t\t\trow_i=np.append(declination[i-1], table[2+i, 3:])\n\n\t\t\t#content=np.array2string(row_i, formatter={'float_kind':lambda x: \"%.2f\" % row_i})\n\t\t\t#content=np.array2string(row_i, precision=2, separator=' ', suppress_small=True)\n\t\t\t#f.write(content+'\\n')\n\t\t\tf.write(\" \".join(map(str, row_i)))\n\t\t\tf.write(\"\\n\")\n\n\telse:\n\t\t# 3D table, include the breakdown of the total energy\n\t\ta=len(table)\n\t\tm=np.shape(table[0])[0]-2\n\t\tn=np.shape(table[0])[1]-2\n\n\t\thour_angle=table[0][2, 3:]\n\t\tdeclination=table[0][3:,2]\n\n\t\tfor t in range(a):\n\t\t\tf.write('double %s(%s, %s)\\n'%(title[t], m,n))\n\n\t\t\tfor i in range(m):\n\t\t\t\tif i ==0:\n\t\t\t\t\trow_i=np.append(0, hour_angle)\n\t\t\t\telse:\n\t\t\t\t\trow_i=np.append(declination[i-1], table[t][2+i, 3:])\n\t\t\t\tf.write(\" \".join(map(str, row_i)))\n\t\t\t\tf.write(\"\\n\")\t\n\t\t\t\t\t\t\n\t\t\tf.write(\"\\n\")\n\t\t\tf.write(\"\\n\")\n\n\tf.close()\n\n\ndef output_matadata_motab(table, field_type, aiming, n_helios, A_helio, eff_design, d_receiver, h_receiver, H_tower, eff_rec_design,coefs_T, coefs, eff_abs, eff_emi,SM,savedir=None, details_en=None):\n\t\"\"\"Output the .motab file to work with the SolarTherm program\n\n\t``Arguments``\n\t\t* table (numpy array): the oelt that returned by design_crs.CRS.field_design_annual, listed by declination and hour angles\n\t\t* field_type (str): polar or surrounding\n\t\t* aiming (str): 'single' or 'isp' or others to specify the aiming strategy\n\t\t* n_helios (int): total number of heliostats\n\t\t* A_helio (float): area of each heliostat (m2)\n\t\t* eff_design (float): the optical efficiency at design point\n\t\t* d_receiver: receiver diameter (m)\n\t\t* h_receiver: receiver height (m)\n\t\t* H_tower (float), tower height (m)\n\t\t* eff_rec_design (float): the receiver efficiency at design point\n\t\t* savedir (str): the directory to save this .motab file\n\t\t* details_en (dict): the key of the dict is the name of the breakdown of energy (loss), the value of the dict is a numpy array that contains the value of the energy (loss) with the corresponding declination and hour angles\n\t\n\t``Return``\n\t\twrite the table(s) to the .motab file\n\t\"\"\"\n\tf=open(savedir, 'w')\n\tf.write('#1\\n')\n\tf.write('#Comments: Field type: %s, Aiming Strategy: %s, Date:%s\\n'%(field_type, aiming, datetime.now()))\n\tf.write(\"#METALABELS,n_helios,A_helio, eff_design, d_receiver, h_receiver, H_tower, eff_rec_design,CoT1,CoT2,CoT3,CoT4,CoT'1,CoT'2,CoT'3,CoT'4,Coh1,Coh2,Coh3,Coh4,Coh5,eff_abs,eff_emi,SM\\n\")\n\tf.write('##METAUNITS,integer,m2,real,m,m,m,real,real,real,real,real,real,real,real,real,real,real,real,real,real,real,real,real\\n')\n\tf.write('#METADATA,%s,%s,%s,%s,%s,%s,%s,%s,%s,%s,%s,%s,%s,%s,%s,%s,%s,%s,%s,%s,%s,%s,%s\\n'%(int(n_helios), A_helio, eff_design, d_receiver, h_receiver, H_tower, eff_rec_design,\n\t coefs_T[0],coefs_T[1][0],coefs_T[1][1],coefs_T[1][2],coefs_T[2],coefs_T[3][0],coefs_T[3][1],coefs_T[3][2],coefs[0],coefs[1],coefs[2],coefs[3],coefs[4],eff_abs,eff_emi,SM))\n\n\t# size of the lookup table \n\tm=np.shape(table)[0]\n\tn=np.shape(table)[1]\n\tf.write('double optics(%s, %s)\\n'%(m,n))\n\n\thour_angle=table[0, 1:]\n\tdeclination=table[1:,0]\n\n\tfor i in range(m):\n\t\tif i ==0:\n\t\t\trow_i=np.append(0, hour_angle)\n\t\telse:\n\t\t\trow_i=np.append(declination[i-1], table[i, 1:])\n\t\tf.write(\" \".join(map(str, row_i)))\n\t\tf.write(\"\\n\")\n\n\tif details_en!=None:\n\t\tfor key in details_en:\n\t\t\tbreakdown=key\n\t\t\ttable=details_en[key]\n\t\t\t# size of the lookup table \n\t\t\tm=np.shape(table)[0]\n\t\t\tn=np.shape(table)[1]\n\t\t\tf.write('double %s(%s, %s)\\n'%(key,m,n))\n\t\t\tfor i in range(m):\n\t\t\t\tif i ==0:\n\t\t\t\t\trow_i=np.append(0, hour_angle)\n\t\t\t\telse:\n\t\t\t\t\trow_i=np.append(declination[i-1], table[i, 1:])\n\t\t\t\tf.write(\" \".join(map(str, row_i)))\n\t\t\t\tf.write(\"\\n\")\t\t\t\n\tf.close()\n\nif __name__=='__main__':\n\tfrom sys import path\n\ttable=np.loadtxt('%s/F_optic.csv'%path[0],delimiter=',')\n\tcoefs_T=[945.7112573259491, np.array([ 0.02720568, -0.00172737, 0.07126733]), 953.7130902079241, np.array([ 0.02170311, -0.00196636, 0.08407119])]\n\tcoefs=[7.61828573e-04,-3.54208032e-02,5.93470995e-01,-9.37379885e-01,9.26793247e+00]\n\teff_abs=0.987174393114\n\teff_emi=0.940767053132\n\n\n\toutput_matadata_motab(table, field_type='surrounding', aiming='MDBA', n_helios=6766, A_helio=144.375, eff_design=0.65414, \n\t d_receiver=16., h_receiver=24., H_tower=175., eff_rec_design=0.87645, coefs_T=coefs_T, coefs=coefs, eff_abs=eff_abs, eff_emi= eff_emi,\n\t savedir='%s/example.motab'%path[0], details_en=None)\n\n\ndef read_motab(filename):\n\n\twith open(filename) as f:\n\t\tcontent=f.read().splitlines()\n\tf.close()\n\tres=content[4].split(',')\n\n\tn_helios=float(res[1])\n\tA_helio=float(res[2])\n\teff_des=float(res[3])\n\tQ_in_rcv=float(res[-2])\n\tA_land=float(res[-1])\n\n\toelt=np.array([])\n\tsolar_hour=np.array([])\n\tdeclination=np.array([])\n\tt=content[6].split(' ')\n\n\tfor v in t[1:]:\n\t\tsolar_hour=np.append(solar_hour, float(v))\n\n\tfor t in content[7:]:\n\t\tv=t.split(' ')\n\t\tdeclination=np.append(declination, float(v[0]))\n\t\toelt=np.append(oelt, np.array(v[1:],dtype=float))\n\n\toelt=oelt.reshape(len(declination), len(solar_hour))\n\n\treturn n_helios, A_helio, eff_des, Q_in_rcv, A_land, solar_hour, declination, oelt\n\t\n\n\n","repo_name":"arfontalvoANU/MDBA-Aiming-Strategy","sub_path":"mdbapy/output_motab.py","file_name":"output_motab.py","file_ext":"py","file_size_in_byte":5476,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"17"} +{"seq_id":"4831428551","text":"# -*- coding: utf-8 -*-\nimport sys\nimport os\nimport os.path\nimport uuid\nimport time\nimport random\nimport string\nimport hashlib\nimport urllib\nimport copy\nfrom functools import partial\nimport logging\nimport datetime\n\nimport tornado\nimport tornado.web\nimport tornado.escape\nimport tornado.websocket\nimport tornado.httpclient\nimport tornado.gen\nfrom tornado.escape import json_encode, json_decode\n\n# from user_agents import parse as uaparse #早年KJ用来判断设备使用\n\n# import nomagic\n# from nomagic.cache import get_user, get_users, update_user, get_doc, get_docs, update_doc, get_aim, get_aims, update_aim, get_entity, get_entities, update_entity\n# from nomagic.cache import BIG_CACHE\n# from setting import settings\n# from setting import conn\nfrom base import WebRequest\nfrom base import WebSocket\n\nimport serial #导入模块\ndef action(action,d1,d2):\n if d1<0:\n d1=d1+256\n if d2<0:\n d2=d2+256\n\n a_now = []\n if action == \"S_READY\":#车辆启动后先发这个,进入待命状态\n a_now = [0x23,0x53,0x01,0x01,0x0A]\n elif action == \"J_STOP\":#遥控停止\n a_now = [0x23,0x4A,0x00,0x00,0x0A]\n elif action == \"J_RUN\":#遥控开始\n a_now = [0x23,0x4A,0x01,0x00,0x0A]\n elif action == \"D\":\n a_now = [0x23,0x44,d1,d2,0x0A]\n elif action == \"R\":\n a_now = [0x23,0x52,d1,d2,0x0A]\n elif action == \"T\":\n a_now = [0x23,0x54,d1,d2,0x0A]\n elif action == \"W\":#消除警报\n a_now = [0x23,0x57,d1,d2,0x0A]\n elif action == \"S\":\n a_now = [0x23,0x53,0x00,0x00,0x0A]\n elif action == \"SF\":#强制停止\n a_now = [0x23,0x53,0x00,0x01,0x0A]\n return a_now\n\n\nclass UsbSendAPIHandler(tornado.web.WebRequest):\n def get(self):\n self.post()\n @tornado.gen.coroutine\n def post(self):\n value_now = self.get_argument(\"value\",None)\n action_now = self.get_argument(\"action\",None)\n if not(value_now and action_now):\n return\n value_now = int(value_now)\n a_list = []\n if action_now == \"xc_go\":\n # action(\"D\",-100,200),\n a_list =[\n action(\"D\",50,value_now)\n ]\n elif action_now == \"xc_back\":\n a_list =[\n action(\"D\",-50,value_now)\n ]\n elif action_now == \"xc_left\":\n a_list =[\n action(\"T\",-1,30)\n ]\n elif action_now == \"xc_right\":\n a_list =[\n action(\"T\",1,30)\n ]\n elif action_now == \"xc_cancel_alert_and_ready\":\n #消除警报 并车辆准备\n a_list =[\n action(\"W\",0,100),\n action(\"S_READY\",1,1),\n action(\"J_STOP\",0,0),\n ]\n self.finis({\"info\":\"ok\",\"a_list\":a_list})\n\n try:\n #端口,GNU / Linux上的/ dev / ttyUSB0 等 或 Windows上的 COM3 等\n portx_now = \"tty.wchusbserial14120\"\n portx=\"/dev/%s\" % portx_now\n #波特率,标准值之一:50,75,110,134,150,200,300,600,1200,1800,2400,4800,9600,19200,38400,57600,115200\n bps=115200\n #超时设置,None:永远等待操作,0为立即返回请求结果,其他值为等待超时时间(单位为秒)\n timex=5\n # 打开串口,并得到串口对象\n ser=serial.Serial(portx,bps,timeout=timex)\n # 写数据 最小间隔 80ms\n for a in a_list:\n # result=ser.write(\"abc\".encode(\"gbk\"))\n print(a)\n result=ser.write(a)\n print(\"写总字节数:\",result)\n time.sleep(0.1)\n # while True:\n # if ser.in_waiting:\n # stra=ser.read(ser.in_waiting)\n # if(stra==\"exit\"):#退出标志\n # break\n # else:\n # print(\"收到数据:\",stra.hex())\n # # 235701300a\n \n # # print(\"---------------\")\n ser.close()#关闭串口\n except Exception as e:\n print(\"---异常---:\",e)\n\n\n","repo_name":"hotpoor/XdHacks_201910_1920_automove","sub_path":"py3_web/controller/xc_action_now.py","file_name":"xc_action_now.py","file_ext":"py","file_size_in_byte":4140,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"17"} +{"seq_id":"39035295023","text":"import pandas as pd \nfrom sys import platform\nfrom os import system\n\n\ndef clearScreen(): \n if platform == \"linux\" or platform == \"linux2\": \n system(\"clear\")\n elif platform == \"darwin\": \n system(\"clear\")\n elif platform == \"win32\": \n system(\"cls\")\n\n\ndef calculatePercentage(total:int,current:int): \n percentage = int((current/total)*100)\n sharp = \"#\"*percentage\n dash = \"-\"*(100-percentage)\n bar = sharp+dash\n if platform == \"linux\" or platform == \"linux2\": \n system(\"clear\")\n print(bar)\n print(f\"Calculating... %{percentage}\")\n elif platform == \"darwin\": \n system(\"clear\")\n print(bar)\n print(f\"Calculating... %{percentage}\")\n elif platform == \"win32\": \n print(bar)\n system(\"cls\")\n print(f\"Calculating... %{percentage}\")\n\n\ndef get_content_convert_list(): \n try:\n fname = input(\"File name: \")\n content = \"\"\n with open(file=fname, mode=\"r\",encoding=\"utf-8\") as file: \n content = file.read()\n content = content.split(\"\\n\")\n \n return content\n except KeyboardInterrupt: \n print(\"\\n\\nForced to shut down\")\n\n\ndef create_json_convert_pandasDF(logs:list): \n try: \n logs = logs[0:5000]\n policyids, srcips, dstips, dstports = [],[],[],[]\n jsonFormat = {\n \"policyid\":policyids,\n \"srcip\":srcips,\n \"dstip\":dstips,\n \"dstport\":dstports,\n \"count\":1\n }\n for sublist in logs: \n sublist = sublist.split()\n global srcip, dstip,dstport,policyid\n policyid, srcip, dstip,dstport = \"\",\"\", \"\",\"\"\n for value in sublist: \n \n value = value.strip(\"''\")\n if \"policyid=\" in value and \"shapingpolicyid=\" not in value: \n policyid = value.split(\"=\")[1]\n elif \"srcip=\" in value: \n srcip = value.split(\"=\")[1]\n elif \"dstip=\" in value: \n dstip = value.split(\"=\")[1]\n elif \"dstport=\" in value: \n dstport = value.split(\"=\")[1]\n else: pass\n\n if policyid and srcip and dstip and dstport: \n policyids.append(policyid)\n srcips.append(srcip)\n dstips.append(dstip)\n dstports.append(dstport)\n \n df = pd.DataFrame.from_dict(jsonFormat)\n return df\n except: \n pass\n\n\ndef operation(df):\n try:\n usage = 0\n weight = float(input(\"Data was converted into Pandas DataFrame. \\nType x% weight for calculating more specific policy: \")) \n exempt = input(\"Exempt For Policies (you can leave here blank or type a list or just a policy [For Instance:1 2 3]):\").split()\n policies = df[\"policyid\"].unique()\n clearScreen()\n print(\"-\"*100 + \"\\n\" + \"Calculating... %0\") \n fullText = \"\"\n row_count = len(df.index)\n with open(file=\"result.txt\", mode='w',encoding='utf-8') as file: \n file.write('')\n\n for pol in policies:\n if pol != '0' and pol not in exempt: \n totalUsage = df[df[\"policyid\"] == pol][\"count\"].sum()\n srcipUnique = df[(df[\"policyid\"]==pol)][\"srcip\"].unique()\n dstipUnique = df[(df[\"policyid\"]==pol)][\"dstip\"].unique()\n dstportUnique = df[(df[\"policyid\"]==pol)][\"dstport\"].unique() \n usage = usage + totalUsage\n \n for src in srcipUnique: \n count = df[ (df[\"policyid\"]==pol) & (df[\"srcip\"]== src)][\"count\"].sum() \n if count/totalUsage > weight/100: \n fullText = fullText + f\"policy:{pol} srcip:{src} used {count} times proportionally: % {round((count/totalUsage)*100, 3)}\" + '\\n' \n for dst in dstipUnique: \n count = df[ (df[\"policyid\"]==pol) & (df[\"dstip\"]== dst)][\"count\"].sum() \n if count/totalUsage > weight/100: \n fullText = fullText + f\"policy:{pol} dstip:{dst} used {count} times proportionally: % {round((count/totalUsage)*100, 3)}\" +'\\n' \n for dstport in dstportUnique: \n count = df[ (df[\"policyid\"]==pol) & (df[\"dstport\"]== dstport)][\"count\"].sum() \n if count/totalUsage > weight/100: \n fullText = fullText + f\"policy:{pol} dstport:{dstport} used {count} times proportionally: % {round((count/totalUsage)*100, 3)}\" +'\\n' \n\n with open(file=\"result.txt\",mode='a',encoding='utf-8') as file: \n file.write(f\"Policy:{pol} src unique:{len(srcipUnique)} destination unique:{len(dstipUnique)} dport unique:{len(dstportUnique)}\\n\" + fullText.strip() + '\\n\\n\\n')\n fullText = ''\n calculatePercentage(row_count,usage)\n clearScreen()\n print(\"#\"*100)\n print(\"Calculating... %100\")\n \n except KeyboardInterrupt: \n print(\"\\n\\nForced to shut down\")\n\n\n\nclearScreen()\ncontent = get_content_convert_list()\ndf = create_json_convert_pandasDF(content)\noperation(df)\n","repo_name":"cauteverum/Rule-Analyzer","sub_path":"storedLogs.py","file_name":"storedLogs.py","file_ext":"py","file_size_in_byte":5237,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"17"} +{"seq_id":"72255024985","text":"#=========================================================================\n# Fletcher32UnitRTL_test\n#=========================================================================\n\nimport pytest\nimport random\nimport binascii\n\nfrom pymtl3 import *\nfrom pymtl3.stdlib.test_utils import mk_test_case_table, run_sim\nfrom pymtl3.stdlib import stream\n\nfrom project.fletcher.Fletcher32UnitRTL import Fletcher32UnitRTL\nfrom project.fletcher.Fletcher32UnitMsg import Fletcher32UnitMsgs\n\n# To ensure reproducible testing\n\nrandom.seed(0xdeadbeef)\n\n#-------------------------------------------------------------------------\n# TestHarness\n#-------------------------------------------------------------------------\n\nclass TestHarness( Component ):\n\n def construct( s, fletcher ):\n\n # Instantiate models\n\n s.src = stream.SourceRTL( Fletcher32UnitMsgs.req )\n s.sink = stream.SinkRTL( Fletcher32UnitMsgs.resp )\n s.fletcher = fletcher\n\n # Connect\n\n s.src.send //= s.fletcher.recv\n s.fletcher.send //= s.sink.recv\n\n def done( s ):\n return s.src.done() and s.sink.done()\n\n def line_trace( s ):\n return s.src.line_trace() + \" > \" + s.fletcher.line_trace() + \" > \" + s.sink.line_trace()\n\n# Function to generate Fletcher32 reference\ndef fletcher32_ref(arr):\n sum1 = 0\n sum2 = 0\n for i in range(8):\n sum1 = ( sum1 + arr[i] ) % 65536\n sum2 = ( sum1 + sum2 ) % 65536\n return ( ( sum2 << 16 ) | sum1 )\n\n\n#-------------------------------------------------------------------------\n# test_01\n#-------------------------------------------------------------------------\n# If we send in 'a' (0x61), then dut should output 3904355907\ndef test_01( cmdline_opts ):\n inputs = [0, 0, 0, 0, 0, 0, 0, 0]\n req_msgs = []\n for input in inputs:\n req_msgs.append(b16(input))\n resp_msgs = [b32(fletcher32_ref(inputs))]\n\n th = TestHarness( Fletcher32UnitRTL() )\n th.set_param( \"top.src.construct\", msgs=req_msgs )\n th.set_param( \"top.sink.construct\", msgs=resp_msgs )\n run_sim( th, cmdline_opts, duts=['fletcher'] )\n\n#-------------------------------------------------------------------------\n# test_02\n#-------------------------------------------------------------------------\n# If we send in ab, two then dut should produce three\n\ndef test_02( cmdline_opts ):\n\n inputs = [1, 1, 1, 1, 1, 1, 1, 1]\n req_msgs = []\n for input in inputs:\n req_msgs.append(b16(input))\n resp_msgs = [b32(fletcher32_ref(inputs))]\n\n th = TestHarness( Fletcher32UnitRTL() )\n th.set_param( \"top.src.construct\", msgs=req_msgs )\n th.set_param( \"top.sink.construct\", msgs=resp_msgs )\n run_sim( th, cmdline_opts, duts=['fletcher'] )\n \n#-------------------------------------------------------------------------\n# Test Case: long\n#-------------------------------------------------------------------------\ndef test_long( cmdline_opts ):\n inputs = [121, 113, 44, 14, 13, 96, 107, 89]\n req_msgs = []\n for input in inputs:\n req_msgs.append(b16(input))\n resp_msgs = [b32(fletcher32_ref(inputs))]\n\n th = TestHarness( Fletcher32UnitRTL() )\n th.set_param( \"top.src.construct\", msgs=req_msgs )\n th.set_param( \"top.sink.construct\", msgs=resp_msgs )\n run_sim( th, cmdline_opts, duts=['fletcher'] )\n\n#-------------------------------------------------------------------------\n# Test Case Table\n#-------------------------------------------------------------------------\n\nsmall_pos_req = [\n [0x0003,0x0002,0x0001,0x0000,0x0003,0x0002,0x0001,0x0000],\n [0x0000,0x0001,0x0002,0x0003,0x0000,0x0001,0x0002,0x0003],\n [0x000a,0x000b,0x000c,0x000d,0x000a,0x000b,0x000c,0x000d],\n [0x000d,0x000c,0x000b,0x000a,0x000d,0x000c,0x000b,0x000a], ]\n\nsmall_pos_resp = [\n [ b32(fletcher32_ref(small_pos_req[0])) ],\n [ b32(fletcher32_ref(small_pos_req[1])) ],\n [ b32(fletcher32_ref(small_pos_req[2])) ],\n [ b32(fletcher32_ref(small_pos_req[3])) ], ]\n \nlarge_pos_req = [\n [0x7ffc,0x7ffd,0x7ffe,0x7fff,0x7ffc,0x7ffd,0x7ffe,0x7fff],\n [0x7fff,0x7ffe,0x7ffd,0x7ffc,0x7fff,0x7ffe,0x7ffd,0x7ffc],\n [0x7ff6,0x7ff7,0x7ff8,0x7ff9,0x7ff6,0x7ff7,0x7ff8,0x7ff9],\n [0x7ff9,0x7ff8,0x7ff7,0x7ff6,0x7ff9,0x7ff8,0x7ff7,0x7ff6], ]\n\nlarge_pos_resp = [\n [ b32(fletcher32_ref(large_pos_req[0])) ],\n [ b32(fletcher32_ref(large_pos_req[1])) ],\n [ b32(fletcher32_ref(large_pos_req[2])) ],\n [ b32(fletcher32_ref(large_pos_req[3])) ], ]\ndef mk_msgs(range1, range2):\n req_msgs = []\n resp_msgs = []\n for i in range(8):\n req_msgs.append( random.randint(range1,range2) )\n resp_msgs.append( b32(fletcher32_ref(req_msgs)) )\n return req_msgs, resp_msgs\n\nreq_msgs_small, resp_msgs_small = mk_msgs(0x1, 0x8)\nreq_msgs_large, resp_msgs_large = mk_msgs(0x0f, 0x7f)\nreq_msgs_long, resp_msgs_long = mk_msgs(0x1, 0x7f)\nreq_msgs_rand, resp_msgs_rand = mk_msgs(0x1,0x7f)\n\ntest_case_table = mk_test_case_table([\n ( \"req_msgs resp_msgs src_delay sink_delay\"),\n [ \"small_pos_0\", small_pos_req[0], small_pos_resp[0], 0, 0, ], \n [ \"small_pos_1\", small_pos_req[1], small_pos_resp[1], 0, 0, ], \n [ \"small_pos_2\", small_pos_req[2], small_pos_resp[2], 0, 0, ],\n [ \"small_pos_3\", small_pos_req[3], small_pos_resp[3], 0, 0, ],\n [ \"large_pos_0\", large_pos_req[0], large_pos_resp[0], 0, 0, ], \n [ \"large_pos_0\", large_pos_req[1], large_pos_resp[1], 0, 0, ], \n [ \"large_pos_0\", large_pos_req[2], large_pos_resp[2], 0, 0, ],\n [ \"large_pos_0\", large_pos_req[3], large_pos_resp[3], 0, 0, ],\n [ \"small_0x0\", req_msgs_small, resp_msgs_small, 0, 0, ],\n [ \"small_0x5\", req_msgs_small, resp_msgs_small, 0, 5, ],\n [ \"small_5x5\", req_msgs_small, resp_msgs_small, 5, 5, ],\n [ \"large_0x0\", req_msgs_large, resp_msgs_large, 0, 0, ],\n [ \"large_0x5\", req_msgs_large, resp_msgs_large, 0, 5, ],\n [ \"large_5x5\", req_msgs_large, resp_msgs_large, 5, 5, ],\n [ \"long_0x0\", req_msgs_long, resp_msgs_long, 0, 0, ],\n [ \"long_0x5\", req_msgs_long, resp_msgs_long, 0, 5, ],\n [ \"long_5x5\", req_msgs_long, resp_msgs_long, 5, 5, ],\n [ \"rand_0x0\", req_msgs_rand, resp_msgs_rand, 0, 0, ],\n [ \"rand_0x5\", req_msgs_rand, resp_msgs_rand, 0, 5, ],\n [ \"rand_5x5\", req_msgs_rand, resp_msgs_rand, 5, 5, ],\n])\n\n#-------------------------------------------------------------------------\n# Test cases\n#-------------------------------------------------------------------------\n\n@pytest.mark.parametrize( **test_case_table )\ndef test_case( test_params, cmdline_opts ):\n\n th = TestHarness(Fletcher32UnitRTL())\n\n th.set_param( \"top.src.construct\",\n msgs=test_params.req_msgs,\n initial_delay=test_params.src_delay,\n interval_delay=test_params.src_delay )\n\n th.set_param( \"top.sink.construct\",\n msgs=test_params.resp_msgs,\n initial_delay=test_params.src_delay,\n interval_delay=test_params.src_delay )\n\n run_sim( th, cmdline_opts, duts=['fletcher'] )\n","repo_name":"cornell-ece5745/ece5745-tapeout","sub_path":"project-group15/sim/project/fletcher/block_test/Fletcher32UnitRTL_test.py","file_name":"Fletcher32UnitRTL_test.py","file_ext":"py","file_size_in_byte":7283,"program_lang":"python","lang":"en","doc_type":"code","stars":2,"dataset":"github-code","pt":"17"} +{"seq_id":"74810305303","text":"\"\"\"라이브러리 호출\"\"\"\n\nimport numpy as np\nimport pandas as pd\nimport matplotlib.pyplot as plt\nimport torch\nimport torch.nn as nn\nimport copy\nimport os\n\nfrom sklearn.preprocessing import StandardScaler\nfrom sklearn.preprocessing import MinMaxScaler\n\n\"\"\"데이터 로드\"\"\"\n\npath_data = os.getcwd()+\"/dataset_directory\"\nclimate_andong = pd.read_csv(path_data+\"/Climate_Andong.csv\")\nclimate_andong = climate_andong.iloc[:,1:]\nclimate_chuncheon = pd.read_csv(path_data+\"/Climate_Chuncheon.csv\")\nclimate_chuncheon = climate_chuncheon.iloc[:,1:]\nclimate_jeju = pd.read_csv(path_data+\"/Climate_Jeju.csv\")\nclimate_jeju = climate_jeju.iloc[:,1:]\n\n\"\"\"데이터 결측치 보간(스플라인)\"\"\"\n\nclimate_chuncheon.interpolate(method='spline', inplace=True, order=1)\nclimate_andong.interpolate(method='spline', inplace=True, order=1)\nclimate_jeju.interpolate(method='spline', inplace=True, order=1)\n\n\"\"\"넘파이 배열화 및 스케일링 (전처리)\"\"\"\n\nclimate_chuncheon_np = climate_chuncheon.to_numpy()\nclimate_andong_np = climate_andong.to_numpy()\nclimate_jeju_np = climate_jeju.to_numpy()\n\nclimate_np = np.array([climate_chuncheon_np, climate_andong_np, climate_jeju_np])\n\n\"\"\"GPU Setting\"\"\"\n\ndevice = torch.device('cuda:0' if torch.cuda.is_available() else 'cpu')\nprint(torch.cuda.is_available())\nprint(device)\n\n\"\"\"기후 데이터 넘파이 배열에 적재\"\"\"\n\nclimate = list()\nfor j in range(3) : # 0 chuncheon 1 andong 2 jeju\n s = 0\n climate_year = list()\n for i in range(10) :\n climate_year.append(climate_np[j, s:s+365, :])\n if i != 1 and 5 and 9 :\n s += 365\n else :\n s += 366\n climate_year = np.stack(climate_year, 0)\n climate.append(climate_year)\nclimate = np.stack(climate, 0)\nclimate.shape\n\n\"\"\"훈련 데이터 셋 / 테스트 데이터 셋 분류\"\"\"\n\nfrom torch.utils.data import TensorDataset\nfrom torch.utils.data import DataLoader\n\nx_ss = StandardScaler()\n\ndataset_list = []\n\nfor i in range(3) :\n cc = climate[i] # (10, 365, 14)\n dataset_list_pos = []\n for j in range(14) :\n x_cc = np.delete(cc, j, axis=2).reshape(-1, 13)\n y_cc = cc[:,:,j]\n x_scaled = x_ss.fit_transform(x_cc)\n x_scaled = x_scaled.reshape(10, 365, 13)\n x_cc_train = torch.FloatTensor(x_scaled[:9, :,:])\n x_cc_test = torch.FloatTensor(x_scaled[9, :, :])\n y_cc_train = torch.FloatTensor(y_cc[:9, :])\n y_cc_test = torch.FloatTensor(y_cc[9, :])\n train_dataset = TensorDataset(x_cc_train, y_cc_train)\n train_loader = DataLoader(train_dataset, batch_size=365, shuffle=False)\n test_dataset = TensorDataset(x_cc_test, y_cc_test)\n test_loader = DataLoader(test_dataset, batch_size=365, shuffle=False)\n dataset = (train_loader, test_loader)\n dataset_list_pos.append(dataset)\n dataset_list.append(dataset_list_pos)\n\n\"\"\"기후 데이터 예측 LSTM 모델\"\"\"\n\nclass Climate_LSTM(nn.Module):\n def __init__(self, input_dim, seq_len, n_layers, hidden_dim, output_dim, device):\n super(Climate_LSTM, self).__init__()\n self.n_layers = n_layers\n self.hidden_dim = hidden_dim\n self.device = device\n self.seq_len = seq_len\n self.output_dim = output_dim\n self.input_dim = input_dim\n \n self.lstm = nn.LSTM(self.input_dim, self.hidden_dim,\n num_layers=self.n_layers,\n batch_first=True)\n self.out = nn.Linear(self.hidden_dim, self.output_dim, bias=True)\n\n def forward(self, x): # 365*13\n h_0 = self._init_state()\n x, _ = self.lstm(x, h_0) # 365 * 100 \n h_t = x[:, -1] # 1 * 100\n logit = self.out(h_t)\n return logit\n\n def _init_state(self):\n new_cell_state = torch.zeros(self.n_layers, self.seq_len, self.hidden_dim).to(self.device)\n new_hidden_state = torch.zeros(self.n_layers, self.seq_len, self.hidden_dim).to(self.device)\n self.hidden = (new_hidden_state, new_cell_state)\n\n\"\"\"훈련 및 평가 함수\"\"\"\n\ndef train(model, criterion, optimizer, data_loader):\n model.train()\n running_loss = 0\n for i, (x, y) in enumerate(data_loader):\n x, y = x.to(device), y.to(device)\n \n optimizer.zero_grad()\n logit = model(x)\n loss = criterion(logit, y)\n loss.backward()\n optimizer.step()\n\n running_loss += loss.item() * x.size(0)\n train_loss = running_loss / len(data_loader.dataset)\n \n return train_loss\n\ndef evaluate(model, criterion, data_loader):\n model.eval()\n running_loss = 0\n \n for i, (x, y) in enumerate(data_loader):\n x, y = x.to(device), y.to(device)\n \n logit = model(torch.unsqueeze(x, 0))\n predicted = torch.flatten(logit)\n loss = criterion(logit, y)\n running_loss += loss.item() * x.size(0)\n test_loss = running_loss / len(data_loader.dataset)\n \n return test_loss, predicted\n\ndef evaluate2(model, criterion, data_loader):\n model.eval()\n running_loss = 0\n \n for i, (x, y) in enumerate(data_loader):\n x, y = x.to(device), y.to(device)\n \n logit = model(x)\n predicted = torch.flatten(logit)\n loss = criterion(logit, y)\n running_loss += loss.item() * x.size(0)\n test_loss = running_loss / len(data_loader.dataset)\n \n return test_loss, predicted\n\n\"\"\"LSTM 모델 파라미터 세팅\"\"\"\n\nn_layers = 1\nhidden_dim = 100\nseq_len = 365\ninput_dim = 13\noutput_dim = 365\nnum_epochs = 1000\nearly_stop_patience = 100\n\n\"\"\"훈련 및 평가 함수\"\"\"\n\ndef train_and_eval(model, train_loader, test_loader, epoch, criterion, optimizer, early_stop_patience) :\n train_loss_list = []\n test_loss_list = []\n best_model_wts = copy.deepcopy(model.state_dict())\n best_loss = None\n patience = 0\n\n for e in range(1, epoch+1):\n train_loss = train(model, criterion, optimizer, train_loader)\n test_loss, predicted = evaluate(model, criterion, test_loader)\n if e%10 == 0 :\n print(\"[Epoch: %d] train loss : %5.2f | test loss : %5.2f\" % (e, train_loss, test_loss))\n train_loss_list.append(train_loss)\n test_loss_list.append(test_loss)\n if e == 1:\n best_loss = test_loss\n if test_loss <= best_loss :\n best_loss = test_loss\n patience = 0\n best_model_wts = copy.deepcopy(model.state_dict())\n else :\n patience += 1\n if (patience >= early_stop_patience) : \n print('\\nEarly Stopping')\n print(f'Epoch : {e}')\n break\n\n plt.subplot(1, 2, 1)\n plt.plot(np.arange(e), train_loss_list, label='train')\n plt.plot(np.arange(e), test_loss_list, label='test')\n plt.legend()\n plt.title(\"loss\")\n\n for x, y in test_loader :\n y_test = y\n predicted = predicted.detach().cpu().numpy()\n \n predicted = predicted.reshape(-1,1)\n\n plt.subplot(1, 2, 2)\n plt.plot(np.arange(365), predicted, label = 'pred')\n plt.plot(np.arange(365), y_test, label = 'true')\n plt.legend()\n plt.title(\"predict\")\n plt.show()\n return model\n\ndef train_again(model, criterion, optimizer, data_loader):\n model.train()\n running_loss = 0\n for i, (x, y) in enumerate(data_loader):\n x, y = x.to(device), y.to(device)\n \n model._init_state()\n optimizer.zero_grad()\n logit = model(torch.unsqueeze(x, 0))\n loss = criterion(logit, torch.unsqueeze(y,0))\n loss.backward()\n optimizer.step()\n\n running_loss += loss.item() * x.size(0)\n train_loss = running_loss / len(data_loader.dataset)\n return model\n\n\"\"\"feature list\"\"\"\n\npos_list = [\"춘천\", \"안동\", \"제주\"]\nfeature_list = list(climate_andong.columns)\n\n\"\"\"모델 훈련 및 평가 진행 후 해당 모델로 기후 데이터 예측\"\"\"\n\npred_list = []\nfor i in range(3) :\n pred_list_pos = list()\n for j in range(14):\n model = Climate_LSTM(input_dim, seq_len, n_layers, hidden_dim, output_dim, device).to(device)\n criterion = nn.MSELoss().to(device)\n optimizer = torch.optim.Adam(model.parameters(), lr=0.01)\n print(f\"\\n{pos_list[i]}, {feature_list[j]}\\n\")\n trained_model = train_and_eval(model, dataset_list[i][j][0], dataset_list[i][j][1], num_epochs, criterion, optimizer, early_stop_patience)\n criterion = nn.MSELoss().to(device)\n optimizer = torch.optim.Adam(model.parameters(), lr=0.01)\n trained_model = train_again(trained_model, criterion, optimizer, dataset_list[i][j][1])\n pred_x_list = []\n for k, (x, y) in enumerate(dataset_list[i][j][1]) :\n pred_x_list.append(x)\n logit = model(torch.unsqueeze(torch.FloatTensor(x).to(device), 0)) #\n predicted = torch.flatten(logit)\n plt.plot(np.arange(predicted.shape[0]), predicted.detach().cpu().numpy())\n plt.show()\n pred_list_pos.append(predicted)\n pred_list_pos = torch.stack(pred_list_pos, 0)\n pred_list.append(pred_list_pos)\npred_list = torch.stack(pred_list, 0)\npred_list\n\n\"\"\"농작물 생산량 LSTM 모델\"\"\"\n\nclass Crop_LSTM(nn.Module):\n def __init__(self, input_dim, seq_len, n_layers, hidden_dim, output_dim, device):\n super(Crop_LSTM, self).__init__()\n self.n_layers = n_layers\n self.hidden_dim = hidden_dim\n self.device = device\n self.seq_len = seq_len\n self.output_dim = output_dim\n self.input_dim = input_dim\n \n self.lstm = nn.LSTM(self.input_dim, self.hidden_dim,\n num_layers=self.n_layers,\n batch_first=True)\n self.out = nn.Linear(self.hidden_dim, self.output_dim, bias=True)\n\n def forward(self, x): # 365*13\n h_0 = self._init_state()\n x, _ = self.lstm(x, h_0) # 365 * 100 \n h_t = x[:, -1] # 1 * 100\n logit = self.out(h_t)\n return logit\n\n def _init_state(self):\n new_cell_state = torch.zeros(self.n_layers, self.seq_len, self.hidden_dim).to(self.device)\n new_hidden_state = torch.zeros(self.n_layers, self.seq_len, self.hidden_dim).to(self.device)\n self.hidden = (new_hidden_state, new_cell_state)\n\n\"\"\"모델 하이퍼파라미터 세팅\"\"\"\n\nn_layers = 1\nhidden_dim = 7\nseq_len = 365\ninput_dim = 14\noutput_dim = 1\nnum_epochs = 1000\nearly_stop_patience = 100\n\n\"\"\"농작물 데이터 전처리\"\"\"\n\nChuncheon_Grain = pd.read_csv(path_data+\"/Chuncheon_Grain.csv\")\nChuncheon_Grain = Chuncheon_Grain.iloc[:,1:]\nChuncheon_Grain_np = Chuncheon_Grain.to_numpy()\nChuncheon_Fruit = pd.read_csv(path_data+\"/Chuncheon_Fruit.csv\")\nChuncheon_Fruit = Chuncheon_Fruit.iloc[:,1:]\nChuncheon_Fruit_np = Chuncheon_Fruit.to_numpy()\nAndong_Grain = pd.read_csv(path_data+\"/Andong_Grain.csv\")\nAndong_Grain = Andong_Grain.iloc[:,1:]\nAndong_Grain_np = Andong_Grain.to_numpy()\nAndong_Fruit = pd.read_csv(path_data+\"/Andong_Fruit.csv\")\nAndong_Fruit = Andong_Fruit.iloc[:,1:]\nAndong_Fruit_np = Andong_Fruit.to_numpy()\nJeju_Grain = pd.read_csv(path_data+\"/Jeju_Grain.csv\")\nJeju_Grain = Jeju_Grain.iloc[:,1:]\nJeju_Grain_np = Jeju_Grain.to_numpy()\nJeju_Fruit = pd.read_csv(path_data+\"/Jeju_Fruit.csv\")\nJeju_Fruit = Jeju_Fruit.iloc[:,1:]\nJeju_Fruit_np = Jeju_Fruit.to_numpy()\nGrain = [Chuncheon_Grain_np, Andong_Grain_np, Jeju_Grain_np]\nFruit = [Chuncheon_Fruit_np, Andong_Fruit_np, Jeju_Fruit_np]\n\n\"\"\"데이터 넘파이 배열로 적재\"\"\"\n\npred_list = pred_list.reshape(3, 1, 365, 14)\npred_list = pred_list.detach().cpu().numpy()\npred_list.shape\n\n\"\"\"훈련 데이터 및 테스트 데이터 셋 분류\"\"\"\n\nss = StandardScaler()\n\nclimate_new = []\ndataloader_list = []\n\nfor i in range(3) :\n climate_new_np = np.concatenate([climate[i], pred_list[i]], 0)\n x_scaled = ss.fit_transform(climate_new_np.reshape(-1, 14))\n x_scaled = x_scaled.reshape(11, 365, 14)\n climate_new.append(x_scaled)\n x_train = torch.FloatTensor(x_scaled[1:9, :, :])\n x_test = torch.FloatTensor(x_scaled[9, :, :].reshape(1,365,14))\n Grain_dataloader_list = []\n for j in range(5) : \n y_scaled = ss.fit_transform(Grain[i][:,j].reshape(-1,1))\n y_train = torch.FloatTensor(y_scaled[:8])\n y_test = torch.FloatTensor(y_scaled[8])\n train_dataset = TensorDataset(x_train, y_train)\n train_loader = DataLoader(train_dataset, batch_size=365, shuffle=False)\n test_dataset = TensorDataset(x_test, y_test)\n test_loader = DataLoader(test_dataset, batch_size=365, shuffle=False)\n Grain_dataloader_list.append((train_loader, test_loader))\n \n Fruit_dataloader_list= []\n for j in range(10) :\n y_scaled = ss.fit_transform(Fruit[i][:,j].reshape(-1,1))\n y_train = torch.FloatTensor(y_scaled[:8])\n y_test = torch.FloatTensor(y_scaled[8])\n train_dataset = TensorDataset(x_train, y_train)\n train_loader = DataLoader(train_dataset, batch_size=365, shuffle=False)\n test_dataset = TensorDataset(x_test, y_test)\n test_loader = DataLoader(test_dataset, batch_size=365, shuffle=False)\n Fruit_dataloader_list.append((train_loader, test_loader))\n\n dataloader_list.append((Grain_dataloader_list, Fruit_dataloader_list))\n\n\"\"\"훈련 및 평가 함수\"\"\"\n\ndef train_and_eval2(model, train_loader, test_loader, epoch, criterion, optimizer, early_stop_patience) :\n train_loss_list = []\n test_loss_list = []\n best_model_wts = copy.deepcopy(model.state_dict())\n best_loss = None\n patience = 0\n\n for e in range(1, epoch+1):\n train_loss = train(model, criterion, optimizer, train_loader)\n test_loss, predicted = evaluate2(model, criterion, test_loader)\n if e%10 == 0 :\n print(\"[Epoch: %d] train loss : %5.2f | test loss : %5.2f\" % (e, train_loss, test_loss))\n train_loss_list.append(train_loss)\n test_loss_list.append(test_loss)\n if e == 1:\n best_loss = test_loss\n if test_loss <= best_loss :\n best_loss = test_loss\n patience = 0\n best_model_wts = copy.deepcopy(model.state_dict())\n else :\n patience += 1\n if (patience >= early_stop_patience) : \n print('\\nEarly Stopping')\n print(f'Epoch : {e}')\n break\n\n plt.subplot(1, 2, 1)\n plt.plot(np.arange(e), train_loss_list, label='train')\n plt.plot(np.arange(e), test_loss_list, label='test')\n plt.legend()\n plt.title(\"loss\")\n plt.show()\n\n for x, y in test_loader :\n y_test = y\n predicted = predicted.detach().cpu().numpy()\n \n predicted = predicted.reshape(-1,1)\n\n print(f\"pred : {predicted.item()}, true : {y_test.item()}\")\n return model\n\ndef train_again2(model, criterion, optimizer, data_loader):\n model.train()\n running_loss = 0\n for i, (x, y) in enumerate(data_loader):\n x, y = x.to(device), y.to(device)\n \n model._init_state()\n optimizer.zero_grad()\n logit = model(x)\n loss = criterion(logit, torch.unsqueeze(y,0))\n loss.backward()\n optimizer.step()\n\n running_loss += loss.item() * x.size(0)\n train_loss = running_loss / len(data_loader.dataset)\n return model\n\n\"\"\"feature list\"\"\"\n\nfeature1 = list(Chuncheon_Grain.columns)\nfeature2 = list(Chuncheon_Fruit.columns)\n\n\"\"\"모델 훈련 및 평가 진행 후 해당 모델로 농작물 생산량 예측\"\"\"\n\npred_list = []\nfor i in range(3) :\n pred_list_Grain = []\n pred_list_Fruit = []\n for j in range(5):\n model = Crop_LSTM(input_dim, seq_len, n_layers, hidden_dim, output_dim, device).to(device)\n criterion = nn.MSELoss().to(device)\n optimizer = torch.optim.Adam(model.parameters(), lr=0.01)\n print(f\"\\n{pos_list[i]}, {feature1[j]}\\n\")\n trained_model = train_and_eval2(model, dataloader_list[i][0][j][0], dataloader_list[i][0][j][1], \n num_epochs, criterion, optimizer, early_stop_patience)\n criterion = nn.MSELoss().to(device)\n optimizer = torch.optim.Adam(model.parameters(), lr=0.01)\n trained_model = train_again2(trained_model, criterion, optimizer, dataloader_list[i][0][j][1])\n pred_x_list = []\n for k, (x, y) in enumerate(dataloader_list[i][0][j][1]) :\n pred_x_list.append(x)\n logit = trained_model(torch.FloatTensor(x).to(device)) #\n predicted = torch.flatten(logit)\n print(f\"\\npredicted : {predicted.item()}\")\n pred_list_Grain.append(predicted.item())\n for j in range(10):\n model = Crop_LSTM(input_dim, seq_len, n_layers, hidden_dim, output_dim, device).to(device)\n criterion = nn.MSELoss().to(device)\n optimizer = torch.optim.Adam(model.parameters(), lr=0.01)\n print(f\"\\n{pos_list[i]}, {feature2[j]}\\n\")\n trained_model = train_and_eval2(model, dataloader_list[i][1][j][0], dataloader_list[i][1][j][1], \n num_epochs, criterion, optimizer, early_stop_patience)\n criterion = nn.MSELoss().to(device)\n optimizer = torch.optim.Adam(model.parameters(), lr=0.01)\n trained_model = train_again2(trained_model, criterion, optimizer, dataloader_list[i][1][j][1])\n pred_x_list = []\n for k, (x, y) in enumerate(dataloader_list[i][1][j][1]) :\n pred_x_list.append(x)\n logit = trained_model(torch.FloatTensor(x).to(device)) #\n predicted = torch.flatten(logit)\n print(f\"\\npredicted : {predicted.item()}\")\n pred_list_Fruit.append(predicted.item())\n pred_list.append((pred_list_Grain, pred_list_Fruit))\n\n\"\"\"곡물 생산량 예측 표 출력\"\"\"\n\nGrain_list = []\nfor i in range(3) :\n Grain_list.append(pred_list[i][0])\nGrain_table = pd.DataFrame(np.array(Grain_list), columns=feature1, index=[\"춘천\", \"안동\", \"제주\"])\nGrain_table\n\n\"\"\"각 지역에서 가장 생산량이 많을 것으로 추정되는 작물을 추천\"\"\"\n\nGrain_table.idxmax(axis=1)\n\n\"\"\"과채류 생산량 예측 표 출력\"\"\"\n\nFruit_list = []\nfor i in range(3) :\n Fruit_list.append(pred_list[i][1])\nFruit_table = pd.DataFrame(np.array(Fruit_list), columns=feature2, index=[\"춘천\", \"안동\", \"제주\"])\nFruit_table\n\nFruit_table.idxmax(axis=1)\n","repo_name":"Castella99/Crop_Recommendation_Model_based_LSTM","sub_path":"Crop_Recommendation_Model_based_LSTM.py","file_name":"Crop_Recommendation_Model_based_LSTM.py","file_ext":"py","file_size_in_byte":17919,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"17"} +{"seq_id":"34495968443","text":"from models import get_connection\n\nclass Users:\n \"\"\"Пользователь\"\"\"\n def insert(self, user_id):\n conn = get_connection()\n c = conn.cursor()\n c.execute(\n f'INSERT INTO Users (user_id) VALUES ({user_id})')\n conn.commit()\n\n def select_all(self):\n conn = get_connection()\n c = conn.cursor()\n c.execute('SELECT * FROM Users')\n users = c.fetchall()\n return users\n\n def select_one(self, user_id):\n conn = get_connection()\n c = conn.cursor()\n c.execute('SELECT * FROM Users WHERE user_id = ?', ([user_id]))\n user = c.fetchone()\n if not user:\n return False\n return {\"id\": user[0], \"user_id\": user[1], \"his_meeting\": user[2]}\n\n def update_his_meeting(self, user_id, id_metting):\n print(user_id)\n conn = get_connection()\n c = conn.cursor()\n c.execute(f'UPDATE users SET his_meeting = \"{id_metting}\" WHERE user_id = {user_id}')\n conn.commit()\n\nclass Meetings:\n \"\"\"Встреча\"\"\"\n def insert(self, id_meeting, first_member):\n conn = get_connection()\n c = conn.cursor()\n c.execute(\n f'INSERT INTO Meetings (id_meeting, first_member, need_garant) VALUES (\"{id_meeting}\", {first_member}, 0)')\n conn.commit()\n\n def select_all(self):\n conn = get_connection()\n c = conn.cursor()\n c.execute('SELECT * FROM Meetings')\n return c.fetchall()\n\n def select_one(self, id_meeting):\n conn = get_connection()\n c = conn.cursor()\n c.execute('SELECT * FROM Meetings WHERE id_meeting = ?', ([id_meeting]))\n meeting = c.fetchone()\n if not meeting:\n return False\n return {\"id\": meeting[0], \"id_meeting\": meeting[1], \"first_member\": meeting[2], \"second_member\": meeting[3], \"url_meeting\": meeting[4], \"admin\": meeting[5], \"need_garant\": meeting[6]}\n\n def select_WHERE_need_garant(self, need_garant):\n \"\"\" Достает и отправляет список сделок, которые вызвали ГАРАНТА \"\"\"\n conn = get_connection()\n c = conn.cursor()\n c.execute(f'SELECT * FROM Meetings WHERE need_garant = {need_garant}')\n meetings = c.fetchall()\n return meetings\n\n def update_admin_member(self, id_meeting, admin_id):\n conn = get_connection()\n c = conn.cursor()\n c.execute('UPDATE Meetings SET admin_member = ? WHERE id_meeting = ?', (admin_id, id_meeting))\n conn.commit()\n\n def update_second_member(self, id_meeting, second_member):\n conn = get_connection()\n c = conn.cursor()\n c.execute('UPDATE Meetings SET second_member = ? WHERE id_meeting = ?', (second_member, id_meeting))\n conn.commit()\n\n def update_need_garant(self, id_meeting, need_garant):\n conn = get_connection()\n c = conn.cursor()\n c.execute(f'UPDATE Meetings SET need_garant = {need_garant} WHERE id_meeting = \"{id_meeting}\"')\n conn.commit()\n\n def delete(self, id_meeting):\n conn = get_connection()\n c = conn.cursor()\n c.execute('DELETE FROM Meetings WHERE id_meeting=?', (id_meeting,))\n conn.commit()\n\nclass Messages:\n \"\"\"Сообщения\"\"\"\n def insert(self, id_meeting, message, first_member=False, second_member=False, admin=False):\n conn = get_connection()\n c = conn.cursor()\n\n if first_member:\n c.execute(\n f'INSERT INTO Messages (id_meeting, message, of_second_member) VALUES (\"{id_meeting}\", \"{message}\", \"False\")')\n elif second_member:\n c.execute(\n f'INSERT INTO Messages (id_meeting, message, of_second_member) VALUES (\"{id_meeting}\", \"{message}\", \"True\")')\n elif admin:\n c.execute(\n f'INSERT INTO Messages (id_meeting, message, of_second_member) VALUES (\"{id_meeting}\", \"{message}\", \"False\")')\n\n conn.commit()\n\n def select_all_msg_of_meeting(self, id_meeting):\n \"\"\"Достать все смс определенной Сделки\"\"\"\n conn = get_connection()\n c = conn.cursor()\n c.execute(f'SELECT * FROM Messages WHERE id_meeting=\"{id_meeting}\"')\n return c.fetchall()\n\n def select_all(self):\n conn = get_connection()\n c = conn.cursor()\n c.execute('SELECT * FROM Messages')\n return c.fetchall()\n\n def delete_all(self, id_meeting):\n conn = get_connection()\n c = conn.cursor()\n c.execute('DELETE FROM Messages WHERE id_meeting=?', (id_meeting,))\n conn.commit()\n","repo_name":"MishaKarliychuk/GARANT_bot","sub_path":"functions_db.py","file_name":"functions_db.py","file_ext":"py","file_size_in_byte":4642,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"17"} +{"seq_id":"6139750319","text":"import numpy as np\nfrom scipy import ndimage\n\ndef main(grid, ndim=3):\n kern = np.ones([3]*ndim,dtype=np.uint8)\n kern[(1,)*ndim] = 0\n\n for i in range(6):\n grid = np.pad(grid, 1)\n counts = ndimage.convolve(grid, kern, mode='constant', cval=0)\n for ind, v in np.ndenumerate(grid):\n n = counts[ind]\n if v == 1 and n not in [2,3]:\n grid[ind] = 0\n elif v == 0 and n == 3:\n grid[ind] = 1\n print(np.sum(grid))\n \nif __name__ == '__main__':\n #fn = 'test.txt'\n fn = 'input.txt'\n with open(fn, 'r') as f:\n lines = [[c=='#' for c in li.strip()] for li in f.readlines()]\n grid = np.array(lines, dtype=np.uint8)[:,:,np.newaxis]\n main(grid)\n\n grid = grid[:,:,:,np.newaxis]\n main(grid, ndim=4)\n","repo_name":"stevenpclark/aoc2020","sub_path":"17/17.py","file_name":"17.py","file_ext":"py","file_size_in_byte":804,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"17"} +{"seq_id":"32078040344","text":"from ..layer import Layer\n\nclass Crop(Layer):\n '''This layer crops the image.'''\n\n def __init__(self, output_dim=(250, 70), name='Crop'):\n \"\"\"\n Arguments:\n output_dim: A tuple of 2-integers, (width, height),\n the output dimensions of the image after crop.\n\n name: A string,\n the name of the layer\n \"\"\"\n\n if name is None:\n raise ValueError('name must be different from None')\n\n super(Crop, self).__init__()\n\n self.new_width = output_dim[0]\n self.new_height = output_dim[1]\n self.name = name\n\n def call(self, img):\n \"\"\"Transforms the image\"\"\"\n if img is None: raise ValueError('img is None')\n\n width = img.width\n\n x_shift = self.new_width\n\n img = img.crop((x_shift-1, 0, width-x_shift-1, self.new_height))\n\n return img\n","repo_name":"ConsciousML/Autonomous-RC-Car","sub_path":"smartcar/simulator/layers/utils/crop.py","file_name":"crop.py","file_ext":"py","file_size_in_byte":887,"program_lang":"python","lang":"en","doc_type":"code","stars":6,"dataset":"github-code","pt":"17"} +{"seq_id":"32203160399","text":"import torch\nimport gym\nimport sawyer_gripper_env # noqa: F401\n\n\nclass GraspingPolicy(torch.nn.Module):\n def __init__(self, env):\n super().__init__()\n self.env = env\n self.t = 0\n\n def forward(self, states=None):\n action = self.env.action_space.new()\n if not states:\n return action\n\n z_low, z_high = 0.05, 0.4\n dz = 0.02\n w_open, w_close = 0.11, 0.05\n gripper_force = 20\n\n if self.t < 50:\n action.end_effector.position = states.object.position + [0, 0, z_high]\n action.end_effector.orientation = [0.0, 1, 0.0, 0.0]\n action.gripper_width = w_open\n elif self.t < 100:\n s = (self.t - 50) / 50\n z = z_high - s * (z_high - z_low)\n action.end_effector.position = states.object.position + [0, 0, z]\n elif self.t < 150:\n action.gripper_width = w_close\n action.gripper_force = gripper_force\n elif self.t < 220:\n delta = [0, 0, dz]\n action.end_effector.position = states.robot.end_effector.position + delta\n action.gripper_width = w_close\n action.gripper_force = gripper_force\n else:\n action.gripper_width = w_close\n\n self.t += 1\n\n return action\n\n\ndef main():\n env = gym.make(\"sawyer-gripper-v0\")\n print (f\"Env observation space: {env.observation_space}\")\n env.reset()\n\n # Create a hard-coded grasping policy\n policy = GraspingPolicy(env)\n\n # Set the initial state (obs) to None, done to False\n obs, done = None, False\n\n while not done:\n env.render()\n action = policy(obs)\n obs, reward, done, info = env.step(action)\n\n env.close()\n\n\nif __name__ == \"__main__\":\n main()\n","repo_name":"facebookresearch/tacto","sub_path":"examples/demo_sawyer_gripper_env.py","file_name":"demo_sawyer_gripper_env.py","file_ext":"py","file_size_in_byte":1781,"program_lang":"python","lang":"en","doc_type":"code","stars":290,"dataset":"github-code","pt":"17"} +{"seq_id":"41277019896","text":"class Solution:\n def longestCommonPrefix(self, strs: List[str]) -> str:\n first, last = min(strs), max(strs)\n prefix = ''\n for ind in range(min(len(first), len(last))):\n if first[ind] != last[ind]:\n break\n prefix += first[ind]\n\n return prefix\n","repo_name":"Shruti2301/LeetCode-Practice","sub_path":"Longest Common Prefix.py","file_name":"Longest Common Prefix.py","file_ext":"py","file_size_in_byte":310,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"17"} +{"seq_id":"26431084744","text":"import json\n\n\nclass Account:\n def __init__(self, name, account_number, money, history):\n self.name = name\n self.account_number = account_number\n self.money = money\n self.history = history\n\n def show_data(self):\n print(f'Name : {self.name}')\n print(f'Account number : {self.account_number}')\n print(f'Money : {self.money}')\n print(f'History : {self.history}')\n\n def deposit(self):\n amount = int(input('Amount : '))\n self.money += amount\n if self.history == '':\n self.history = f'Deposit : {amount}'\n else:\n self.history += f'\\nDeposit : {amount}'\n print(f'Current money : {self.money}')\n\n def withdraw(self):\n amount = int(input('amount : '))\n self.money -= amount\n if self.history == '':\n self.history = f'Withdraw : {amount}'\n else:\n self.history += f'\\nWithdraw : {amount}'\n print(f'Current money : {self.money}')\n\n def show_history(self):\n print(self.history)\n\nfilename = input('Filename : ')\nwith open(filename) as f:\n data = json.load(f)\n\nclasses = []\nfor account in data:\n classes.append(Account(\n account['name'], account['account number'], account['money'], account['history']))\n\nwhile True:\n acc_num = input('Account number : ')\n for account in classes:\n if account.account_number == acc_num:\n while True:\n menu = input('Menu : ')\n if menu == '0':\n break\n elif menu == '1':\n account.show_data()\n elif menu == '2':\n account.deposit()\n elif menu == '3':\n account.withdraw()\n elif menu == '4':\n account.show_history()\n elif menu == '5':\n continue\n break\n\ncheck = input()\nif check == '01':\n classes[0].show_data()\nelif check =='02' :\n classes[0].deposit()\nelif check =='03' :\n classes[0].withdraw()\nelif check =='04' :\n classes[0].show_history()\n","repo_name":"Paradorn-248/TA-compro","sub_path":"L10/t.py","file_name":"t.py","file_ext":"py","file_size_in_byte":2114,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"17"} +{"seq_id":"33008161640","text":"import json\nimport datetime\nfrom kafka import KafkaProducer\n\nproducer = KafkaProducer(bootstrap_servers=['194.61.2.84:32769'], api_version=(0,10,1)) \n\nwhile 1:\n\tsend_json = None\n\ttry:\n\t\tsend_type_message = int(input(\"\\nВведите 1, если хотите отправить сообщен��е или введите 2, если хотите отправить сообщение об ошибке\\n\")) \n\texcept ValueError:\n\t\tcontinue\n\n\tif send_type_message == 1: \n\t\tprint(datetime.datetime.utcnow().strftime(\"%Y.%m.%d %H:%M:%S\"),\"\\tСообщение типа *message*\")\n\t\tsend_json = (json.dumps({\"type\": \"message\"})).encode('utf-8')\n\n\telif send_type_message == 2: \n\t\t\tprint(datetime.datetime.utcnow().strftime(\"%Y.%m.%d %H:%M:%S\"),\"\\tСообщение типа *error*\")\n\t\t\tsend_json = (json.dumps({\"type\": \"error\"})).encode('utf-8')\n\n\tproducer.send('main_topic', send_json)\n\n","repo_name":"comfaer/DZ7","sub_path":"DZ7/app1.py","file_name":"app1.py","file_ext":"py","file_size_in_byte":888,"program_lang":"python","lang":"ru","doc_type":"code","stars":0,"dataset":"github-code","pt":"17"} +{"seq_id":"25402210936","text":"from machine import Pin,PWM\nimport threading,time\nfrom Blinker.Blinker import Blinker, BlinkerButton, BlinkerNumber,BlinkerSlider\nfrom Blinker.BlinkerDebug import *\nfrom dianji import Run\nfrom hongwaix import get_value\nfrom Temp_Hum import get_temp_hum\nimport ntptime\nntptime.host='s1a.time.edu.cn' #北京邮电大学ntp服务器\n\n\nauth = '7f185ddddb90'\nssid = '62-5-202'\npswd = 'anys888888'\np2 = Pin(2, Pin.OUT)\np5 = Pin(5,Pin.OUT) #继电器\npwm=PWM(Pin(4,Pin.OUT))#led正极接3.3,负极接4号脚\npwm2=PWM(Pin(15,Pin.OUT))\nclass LED():\n\n def __init__(self):\n self.auth = auth\n self.ssid = ssid\n self.pswd = pswd\n\n BLINKER_DEBUG.debugAll()\n\n Blinker.mode('BLINKER_WIFI')\n Blinker.begin(auth, ssid, pswd)\n\n self.button1 = BlinkerButton('btn-of9')\n self.button2 = BlinkerButton('btn-a1x')#开窗帘\n self.button3 = BlinkerButton('btn-qni')#关窗帘\n self.button4 = BlinkerButton('btn-5gx')#1号继电器\n self.number1 = BlinkerNumber('num-abc')\n self.number2 = BlinkerNumber('num-kf5')#发送温度\n self.number3 = BlinkerNumber('num-50b')#发送湿度\n self.slider1 = BlinkerSlider(\"ran-jhb\")\n self.slider2 = BlinkerSlider(\"ran-bqm\")\n\n self.counter = 0\n self.pinValue = 0\n \n\n self.p2 = p2\n self.p5 = p5\n self.value5 = 0\n self.pwm = pwm\n self.pwm.freq(38000)\n self.pwm.duty(1)\n self.pwm2 = pwm2\n self.pwm2.freq(38000)\n self.pwm2.duty(1)\n self.p2.value(self.pinValue)\n \n \n \n def slider1_callback(self,value):\n \n value=1024-value\n self.pwm.duty(value)\n BLINKER_LOG('Slider read: ',value)\n \n def slider2_callback(self,value):\n \n self.pwm2.duty(value)\n BLINKER_LOG('Slider read: ',value)\n def button1_callback(self,state):\n\n\t\t BLINKER_LOG('get button state: ', state)\n \n\t\t self.pinValue=1-self.pinValue\n\t\t if self.pinValue==1:\n\t\t \tself.button1.text('开')\n\t\t else:\n\t\t \tself.button1.text('关')\n\t\t self.p2.value(self.pinValue)\n\t\t print(self.pinValue)\n def button2_callback(self,state):\n t=threading.Thread(target=Run,args=(720,))\n t.start()\n def button3_callback(self,state):\n t=threading.Thread(target=Run,args=(-720,))\n t.start()\n\t\t\n\t\t\n\t\t#继电器\n def button4_callback(self,state):\n self.value5 = 1-self.value5\n self.p5.value(self.value5)\n print(self.value5)\n def data_callback(self,data):\n\n\t\t BLINKER_LOG('Blinker readString: ', data)\n\t\t self.counter += 1\n\t\t self.number1.print(self.counter)\n\n \n def heartbeat_callback(self):\n t,h = get_temp_hum()\n self.number2.print(t)\n self.number3.print(h)\n\t\t\n\t\t\n\n def run(self):\n \t self.button1.attach(self.button1_callback)\n \t Blinker.attachData(self.data_callback)\n \t Blinker.attachHeartbeat(self.heartbeat_callback)\n \t self.button2.attach(self.button2_callback)\n \t self.button3.attach(self.button3_callback)\n \t self.button4.attach(self.button4_callback)\n \t self.slider1.attach(self.slider1_callback)\n \t self.slider2.attach(self.slider2_callback)\n\n \t while True:\n value=get_value()\n try:\n Blinker.run()\n except OSError:\n pass\n\n","repo_name":"leadkj/esp32","sub_path":"blinker_test.py","file_name":"blinker_test.py","file_ext":"py","file_size_in_byte":3348,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"17"} +{"seq_id":"71775570264","text":"import unittest\nimport os\nimport requests_mock\nimport csv\nfrom parsons.scytl import Scytl, scytl\n\nTEST_STATE = \"GA\"\nTEST_ELECTION_ID = \"114729\"\nTEST_VERSION_NUM = \"296262\"\n\n_DIR = os.path.dirname(__file__)\n\n\nclass TestScytl(unittest.TestCase):\n def setUp(self):\n self.scy = Scytl(TEST_STATE, TEST_ELECTION_ID)\n\n self.requests_mock = requests_mock.Mocker()\n\n self._mock_responses(self.requests_mock)\n\n def tearDown(self) -> None:\n self.requests_mock.stop()\n\n def test_get_summary_results_succeeds(self):\n result = self.scy.get_summary_results()\n\n with open(f\"{_DIR}/114729_summary_expected.csv\", \"r\") as expected:\n expectedResult = list(csv.DictReader(expected, delimiter=\",\"))\n\n for i, row in enumerate(result):\n expectedResultRow = expectedResult[i]\n\n expectedResultRow[\"counties_reporting\"] = (\n expectedResultRow[\"counties_reporting\"] or None\n )\n expectedResultRow[\"total_counties\"] = (\n expectedResultRow[\"total_counties\"] or None\n )\n\n self.assertDictEqual(row, expectedResultRow)\n\n def test_get_summary_results_skips_if_no_version_update(self):\n result = self.scy.get_summary_results()\n\n self.assertIsNotNone(result)\n\n result = self.scy.get_summary_results()\n\n self.assertIsNone(result)\n\n result = self.scy.get_summary_results(True)\n\n self.assertIsNotNone(result)\n\n def test_get_detailed_results_succeeds(self):\n result = self.scy.get_detailed_results()\n\n with open(f\"{_DIR}/114729_county_expected.csv\", \"r\") as expected:\n expectedResult = list(csv.DictReader(expected, delimiter=\",\"))\n\n for i in range(len(result)):\n expectedResultRow = expectedResult[i]\n\n expectedResultRow[\"recorded_votes\"] = int(\n expectedResultRow[\"recorded_votes\"]\n )\n expectedResultRow[\n \"timestamp_last_updated\"\n ] = self.scy._parse_date_to_utc(\n expectedResultRow[\"timestamp_last_updated\"]\n )\n\n self.assertDictEqual(result[i], expectedResultRow)\n\n def test_get_detailed_results_skips_if_no_version_update(self):\n result = self.scy.get_detailed_results()\n\n self.assertIsNotNone(result)\n\n result = self.scy.get_detailed_results()\n\n self.assertIsNone(result)\n\n result = self.scy.get_detailed_results(True)\n\n self.assertIsNotNone(result)\n\n def test_get_detailed_results_for_participating_counties_succeeds(self):\n _, result = self.scy.get_detailed_results_for_participating_counties()\n\n with open(f\"{_DIR}/114729_precinct_expected.csv\", \"r\") as expected:\n expectedResult = list(csv.DictReader(expected, delimiter=\",\"))\n\n for i in range(len(result)):\n expectedResultRow = expectedResult[i]\n\n expectedResultRow[\"recorded_votes\"] = int(\n expectedResultRow[\"recorded_votes\"]\n )\n expectedResultRow[\n \"timestamp_last_updated\"\n ] = self.scy._parse_date_to_utc(\n expectedResultRow[\"timestamp_last_updated\"]\n )\n\n self.assertDictEqual(result[i], expectedResultRow)\n\n def test_get_detailed_results_for_participating_counties_succeeds_for_two_counties(\n self,\n ):\n counties = [\"Barrow\", \"Clarke\"]\n\n _, result = self.scy.get_detailed_results_for_participating_counties(\n county_names=counties\n )\n\n with open(f\"{_DIR}/114729_precinct_expected.csv\", \"r\") as expected:\n expectedResult = csv.DictReader(expected, delimiter=\",\")\n\n filteredExpectedResults = list(\n filter(lambda x: x[\"county_name\"] in counties, expectedResult)\n )\n\n for i, row in enumerate(result):\n expectedResultRow = filteredExpectedResults[i]\n\n expectedResultRow[\"recorded_votes\"] = int(\n expectedResultRow[\"recorded_votes\"]\n )\n expectedResultRow[\n \"timestamp_last_updated\"\n ] = self.scy._parse_date_to_utc(\n expectedResultRow[\"timestamp_last_updated\"]\n )\n\n self.assertDictEqual(row, expectedResultRow)\n\n def test_get_detailed_results_for_participating_counties_missing_counties_update(\n self,\n ):\n counties = [\"Barrow\"]\n\n _, result = self.scy.get_detailed_results_for_participating_counties(\n county_names=counties\n )\n\n self.assertNotEqual(result, [])\n\n self.scy.previous_county_details_version_num = None\n\n _, result = self.scy.get_detailed_results_for_participating_counties()\n\n self.assertNotEqual(result, [])\n\n self.assertTrue(all(x[\"county_name\"] not in counties for x in result))\n\n def test_get_detailed_results_for_participating_counties_skips_if_no_version_update(\n self,\n ):\n _, result = self.scy.get_detailed_results_for_participating_counties()\n\n self.assertNotEqual(result, [])\n\n _, result = self.scy.get_detailed_results_for_participating_counties()\n\n self.assertEqual(result, [])\n\n _, result = self.scy.get_detailed_results_for_participating_counties(\n force_update=True\n )\n\n self.assertNotEqual(result, [])\n\n def test_get_detailed_results_for_participating_counties_skips_if_no_county_version_update(\n self,\n ):\n _, result = self.scy.get_detailed_results_for_participating_counties()\n\n self.assertNotEqual(result, [])\n\n self.scy.previous_county_details_version_num = None\n\n _, result = self.scy.get_detailed_results_for_participating_counties()\n\n self.assertEqual(result, [])\n\n def test_get_detailed_results_for_participating_counties_repeats_failed_counties(\n self,\n ):\n _, result = self.scy.get_detailed_results_for_participating_counties()\n\n self.assertNotEqual(result, [])\n\n self.scy.previous_county_details_version_num = None\n self.scy.previously_fetched_counties.remove(\"Barrow\")\n\n _, result = self.scy.get_detailed_results_for_participating_counties()\n\n self.assertNotEqual(result, [])\n\n def _mock_responses(self, m: requests_mock.Mocker):\n mock_current_version_url = scytl.CURRENT_VERSION_URL_TEMPLATE.format(\n administrator=TEST_STATE, election_id=TEST_ELECTION_ID\n )\n\n m.get(mock_current_version_url, text=TEST_VERSION_NUM)\n\n mock_election_settings_url = scytl.ELECTION_SETTINGS_JSON_URL_TEMPLATE.format(\n state=TEST_STATE, election_id=TEST_ELECTION_ID, version_num=TEST_VERSION_NUM\n )\n\n with open(\n f\"{_DIR}/GA_114729_296262_county_election_settings.json\", \"r\"\n ) as details_file:\n m.get(mock_election_settings_url, text=details_file.read())\n\n for file in os.listdir(f\"{_DIR}/mock_responses\"):\n with open(f\"{_DIR}/mock_responses/{file}\", \"rb\") as details_file:\n file_url = f\"https://results.enr.clarityelections.com/{file}\".replace(\n \"_\", \"/\"\n )\n m.get(file_url, content=details_file.read())\n\n mock_summary_csv_url = scytl.SUMMARY_CSV_ZIP_URL_TEMPLATE.format(\n administrator=TEST_STATE,\n election_id=TEST_ELECTION_ID,\n version_num=TEST_VERSION_NUM,\n )\n\n with open(f\"{_DIR}/114729_summary.zip\", \"rb\") as summary:\n m.get(mock_summary_csv_url, content=summary.read())\n\n mock_detail_xml_url = scytl.DETAIL_XML_ZIP_URL_TEMPLATE.format(\n administrator=TEST_STATE,\n election_id=TEST_ELECTION_ID,\n version_num=TEST_VERSION_NUM,\n )\n\n with open(f\"{_DIR}/114729_detailxml.zip\", \"rb\") as detailxml:\n m.get(mock_detail_xml_url, content=detailxml.read())\n\n m.start()\n","repo_name":"move-coop/parsons","sub_path":"test/test_scytl/test_scytl.py","file_name":"test_scytl.py","file_ext":"py","file_size_in_byte":8146,"program_lang":"python","lang":"en","doc_type":"code","stars":237,"dataset":"github-code","pt":"17"} +{"seq_id":"6145706056","text":"import os\nimport textwrap\nfrom tkinter import *\nfrom PIL import Image, ImageTk, ImageDraw, ImageFont\nimport time\n\nimport sex\nfrom errors import photo_not_selected\n\n\ndef show_card(card_numb, name, surname, birth, birth_place, add, DL, DE, ID_photo, path, is_save=False):\n front_template = Image.open(\"../Templates/template_front.jpg\")\n HEIGHT = 638\n WIDTH = 1039\n\n front_template = front_template.resize((550, 300), Image.ANTIALIAS)\n fr_font = ImageFont.truetype(\"../Fonts/times-new-roman.ttf\", size=20, layout_engine=ImageFont.LAYOUT_RAQM)\n fr_font_input = ImageFont.truetype(\"../Fonts/times-new-roman.ttf\", size=18, layout_engine=ImageFont.LAYOUT_RAQM)\n fr_font_input_bold = ImageFont.truetype(\"../Fonts/times new roman bold.ttf\", size=18,\n layout_engine=ImageFont.LAYOUT_RAQM)\n zh_font = ImageFont.truetype(\"../Fonts/NotoSansSC-Medium.otf\", size=14, layout_engine=ImageFont.LAYOUT_RAQM)\n title_font_fr = ImageFont.truetype(\"../Fonts/BERNHC.TTF\", size=25, layout_engine=ImageFont.LAYOUT_RAQM)\n title_font_zh = ImageFont.truetype(\"../Fonts/NotoSansSC-Medium.otf\", size=21, layout_engine=ImageFont.LAYOUT_RAQM)\n if not photo_not_selected(ID_photo):\n front_template.paste(im=ID_photo, box=(31, 83, 166, 253))\n draw = ImageDraw.Draw(front_template)\n\n draw.text((44, 15), f\"CARTE D'IDENTITÉ CONSULAIRE/\", fill='green', font=title_font_fr, language='fr')\n draw.text((337, 14), \"布基纳法索领事卡\", fill='green', font=title_font_zh, language='zh-Hans')\n draw.text((240, 50), f\"N°ABFPK/{card_numb}\", fill='black', font=fr_font_input_bold, language='fr')\n\n draw.text((180, 78), \"Nom\", fill='black', font=fr_font, language='fr')\n draw.text((222, 78), \"/性:\", fill='black', font=zh_font, language='zh-Hans')\n draw.text((250, 80), str(name), fill='black', font=fr_font_input_bold, language='fr')\n\n draw.text((180, 110), \"Prénoms\", fill='black', font=fr_font, language='fr')\n draw.text((252, 109), \"/名:\", fill='black', font=zh_font, language='zh-Hans')\n draw.text((285, 111), str(surname), fill='black', font=fr_font_input_bold, language='fr')\n if sex.gender == 'Femme':\n draw.text((180, 142), \"Née le\", fill='black', font=fr_font, language='fr')\n draw.text((233, 142), \"/出日:\", fill='black', font=zh_font, language='zh-Hans')\n draw.text((275, 143), str(birth), fill='black', font=fr_font_input_bold, language='fr')\n draw.text((360, 143), ' A ' + str(birth_place), fill='black',\n font=fr_font_input, language='fr')\n else:\n draw.text((180, 142), \"Né le\", fill='black', font=fr_font, language='fr')\n draw.text((225, 142), \"/出日:\", fill='black', font=zh_font, language='zh-Hans')\n draw.text((270, 143), str(birth), fill='black', font=fr_font_input_bold, language='fr')\n draw.text((355, 143), ' A ' + str(birth_place), fill='black',\n font=fr_font_input, language='fr')\n\n draw.text((180, 174), \"Délivré le\", fill='black', font=fr_font, language='fr')\n draw.text((262, 174), \"/颁发时间:\", fill='black', font=zh_font, language='zh-Hans')\n draw.text((335, 176), str(DL), fill='black', font=fr_font_input, language='fr')\n\n draw.text((180, 206), \"Expire le\", fill='black', font=fr_font, language='fr')\n draw.text((253, 207), \"/到期时间:\", fill='black', font=zh_font, language='zh-Hans')\n draw.text((325, 209), str(DE), fill='black', font=fr_font_input, language='fr')\n\n back_template = Image.open(\"../Templates/template_back.jpg\")\n back_template = back_template.resize((550, 300), Image.ANTIALIAS)\n draw = ImageDraw.Draw(back_template)\n draw.text((125, 25), \"AMBASSADE DU BURKINA FASO À BEIJING\", fill='green', font=title_font_fr, language='fr')\n draw.text((230, 60), \"布基纳法索驻大使馆\", fill='green', font=title_font_zh, language='zh-Hans')\n draw.text((310, 200), \"/地址:\", fill='black', font=zh_font, language='zh-Hans')\n add = \"Addresse de l'intéressé \" + add\n lines = textwrap.wrap(str(add), width=50)\n y_text = 200\n for line in lines:\n width, height = fr_font.getsize(line)\n draw.text((125, y_text), line, font=fr_font, fill='black', language='fr')\n y_text += height\n\n if is_save:\n time.sleep(0.5)\n front_template = front_template.resize((WIDTH, HEIGHT), Image.ANTIALIAS)\n back_template = back_template.resize((WIDTH, HEIGHT), Image.ANTIALIAS)\n qr_code_image = Image.open(str(os.path.join(path, 'QrCode.jpeg')))\n qr_code_image = qr_code_image.resize((170, 170), Image.ANTIALIAS)\n back_template.paste(im=qr_code_image, box=(55, 425, 225, 595))\n front_template.save(f\"{path}page_devant.png\")\n back_template.save(f\"{path}page_arriere.png\")\n\n else:\n card = Toplevel(borderwidth=1, relief=RIDGE, pady=20, padx=20)\n card.title(\"Carte consulaire\")\n\n # Main pages\n FrontPage = Frame(card, borderwidth=1, relief=RIDGE, border=5, padx=10, pady=10)\n FrontPage.pack()\n\n front_template_show = ImageTk.PhotoImage(front_template)\n photo = Label(FrontPage, image=front_template_show, relief=RIDGE, borderwidth=5)\n photo.image = front_template_show\n photo.pack()\n\n back_template_show = ImageTk.PhotoImage(back_template)\n photo1 = Label(FrontPage, image=back_template_show, relief=RIDGE, borderwidth=5)\n photo1.image = back_template_show\n photo1.pack()\n","repo_name":"elsanal/ID-card-generator_with-Python-Tkinter","sub_path":"Codes/validation.py","file_name":"validation.py","file_ext":"py","file_size_in_byte":5762,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"17"} +{"seq_id":"3626779214","text":"#!/usr/bin/python3\n# coding: UTF-8\nimport flask\nfrom flask import request, Response\nimport json\nimport requests\nimport codecs\nimport time\nimport sys\nimport os\nimport datetime\nfrom selenium import webdriver\nfrom selenium.webdriver.common.keys import Keys\nfrom selenium.webdriver.chrome.options import Options\nimport traceback\nimport urllib\n# import unicode\n# import mysql.connector as MySQLdb\n\n\nWEB_HOOK_URL = \"URL\"\nWEB_HOOK_URL += \"KEY\"\n\n# f = sys.argv[1].encode('utf-8')\n# get = urllib.parse.quote(f)\n\nget = sys.argv[1]\nchrome_options = Options()\nchrome_options.add_argument('--headless')\nchrome_options.add_argument('--no-sandbox')\nchrome_options.add_argument('--disable-dev-shm-usage')\ndriver = webdriver.Chrome(\"chromedriver\", chrome_options=chrome_options)\n\ntry:\n\n # これを用いれば、複数の単語を検索可能に\n # google = \"https://www.google.co.jp\"\n # driver.get(google)\n # search_bar = driver.find_element_by_name(\"q\")\n # search_bar.send_keys(get)\n # search_bar.submit()\n # themes = driver.find_elements_by_xpath(\"//div[@class=\\'r\\']/a/h3\")\n # urls = driver.find_elements_by_xpath(\"//div[@class=\\'r\\']/a\")\n\n google = \"https://www.google.com/search?q={}&safe=off\".format(get)\n driver.get(google)\n themes = driver.find_elements_by_xpath(\"//div[@class=\\'r\\']/a/h3\")\n urls = driver.find_elements_by_xpath(\"//div[@class=\\'r\\']/a\")\n\n # listを制作するため\n li = []\n\n #5件のみ取得\n num = 0\n\n for theme, url in zip(themes, urls):\n if num > 4:\n break\n th = theme.text\n ur = url.get_attribute('href')\n li.append([th, ur])\n num += 1\n word = '以下が参考資料です!\\n'\n for response in li:\n word += response[0] + '\\n' + response[1] + '\\n'\n requests.post(WEB_HOOK_URL, data=json.dumps({\n \"text\" : \"<@\" + get + \">\\n\" + word\n }))\n driver.quit()\nexcept:\n requests.post(WEB_HOOK_URL, data=json.dumps({\n \"text\" : \"エラーしました\"\n }))\ntraceback.print_exc()","repo_name":"tech-is/maine-coon","sub_path":"slackBot/slackBot2.py","file_name":"slackBot2.py","file_ext":"py","file_size_in_byte":2039,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"17"} +{"seq_id":"18455006098","text":"#!/usr/bin/env python3\n# -*- coding: utf-8 -*-\n\"\"\"\nCreated on Thu Nov 14 20:05:27 2019\n\n@author: miriam\n\"\"\"\n\nimport numpy as np\nimport matplotlib.pyplot as plt\n\nimport tools\n\n#################\n### CONSTANTS ###\n#################\n\nk = 1.380649e-23 #J/K\nk = 1.4e-23\nhbar = 1.054571817e-34 #Js\nhbar = 1.05e-34 #Js\nc = 3e8 #m/s\ngrav = 9.8 #m/s^2\n\n###########################################################################\n##################\n### PARAMETERS ###\n##################\n\n\nomega = np.arange(0, 400, 1e-2)*1e3*2*np.pi # freq for spectrum\n\nT = 300 #temperatur [K]\nNPERIOD=160000 #NPERIOD=NOT RELEVANT TO ANALYTICAL CODE: ignore\nNTOT=8 #NTOT=number of equations so 8=>1 optical mode +3D\nR0=100e-9 #sphere radius\nRHO=2198 #sphere density\nEPSR=2.1\nEpsi0=8.854e-12\n# rho=2198.d0,EPSR=1.45d0**2,Epsi0=8.854d-12, &\nWK=5.9e6 #=2*pi/lambda=k\nwaist=41.1e-6 #waist radius\nWX=0.67e-6\nWY=0.77e-6\nXL=1.07e-2 #cavity length \nFinesse=15e4\nPress=1e-5 #air pressure in millibars\nPin1=0.17e0 #input power in Watts tweezer beam\ndetuning=-300e3 #detuning in KHz trap beam\nDelFSR=14e9 #1 FSR= 14 GHz\ntheta0=0.2 #angle between tweezer polarization and cavity axis. Given as as FRACTION of pi so pi/4 is theta0=0.25\n\n# Equilibrium positions \n# X0=0.125*lambda ,Y0=waist/sqrt(2)\nY0=0.0e-6\nX0=0.125*1.064e-6\nZ0=0e-6\n\n\n\n###############################################################\n\n\n\n#################\n### FUNCTIONS ###\n#################\n\n\n\ndef print_parameter(param):\n print()\n print('Parameter:')\n print('mechanical frequencies/2pi: ', param[0]/2/np.pi)\n print('detuning/2pi: ', param[1]/2/np.pi)\n print('Gamma/2pi: ', param[3]/2/np.pi)\n print('kappa/2pi: ', param[4]/2/np.pi)\n print('couplings:')\n print('g_x, g_y, g_z: ', param[2]/2/np.pi, '*2pi')\n \n \n \n############################\n### PREPARE CALCULATIONS ###\n############################ \n \n# zero eq. initial values\nXM=RHO*4.*np.pi/3.*R0**3\nprint('Mass of bead= (Kg)', XM)\n\nPolaris=4.*np.pi*Epsi0*(EPSR-1)/(EPSR+2)*R0**3\nprint('Polarisability of bead=', Polaris)\n\nOMOPT=c*WK\n# note waist is waist radius\nW2=waist**2\n\n# add a factor of 4 here. Not in GALAX1-5 routines!!!\nVOL=XL*np.pi*W2/4\n\n# &&&&&&&&&&&&&\n# Depth of cavity field. Weak and unimportant for CS case\nA=OMOPT*Polaris/2./VOL/Epsi0\nprint('Cavity trap A/(2pi)= (Hz); zero-th shift', A/np.pi/2, A*np.cos(WK*X0)**2)\n#&&&&&&&&&&&&&&&&&&\nKAPPin=np.pi*c/Finesse/XL\nprint('kappaIn= (Hz)', KAPPin/2/np.pi)\n\nepsTW=4*Pin1/(WX*WY*np.pi*c*Epsi0)\nepsTW = np.sqrt(epsTW)\nepsCAV=hbar*OMOPT/(2.*VOL*Epsi0)\nepsCAV = np.sqrt(epsCAV)\nprint('epsTW,epsCAV', epsTW,epsCAV)\n\ncoeff=WK*Polaris/Epsi0/OMOPT**2/np.pi\nkappnano=4*coeff**2*DelFSR*np.cos(WK*X0)*np.cos(WK*X0)\nprint('kappnano',kappnano)\nkappa=kappnano+KAPPin\n#&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&\nZR=WX*WY*WK/2\nprint('ZR=',ZR)\n \n# Pressure 1.d-4 mBar => ~ 0.125Hz in old expt\n# now take usual expression eg Levitated review by Li Geraci etc\n# 1 bar= 10^ 5 pascal; Press is in mbar = 10^ 2 pascal\n#gamma=16 * P/(np.pi*v*RHO*R)\n# v=speed of air=500 /s\nGAMMAM=1600*Press/np.pi\nGAMMAM=GAMMAM/500/RHO/R0\n#Fix of Feb.2016 our GAMMAM => GAMMAM/2!!\n# gamma/2=8 P/(pi*v*rho*R)\nGamma=GAMMAM/2\nprint('mechanical damping* 2pi', Gamma)\n\nprint('theta [pi]', theta0)\n#*************************************************************************\n#*************************************************************************\n# subroutine below obtains the optomechanical parameters\n# SUBROUTINE EQUIL_PAR(thet,Wkx0,Polaris,epsTW,epsCAV,XM,ZR,kappnano,kappin,GammaM,OMX,OMY,OMZ,GMAT,PHON)\n \n#************************************************************************\n#************************************************************************\niwrite=6\nDet2pi=detuning*2*np.pi\n\nkappa=kappnano+KAPPin\nkapp2=0.5*kappa\nKAPP2 = kapp2\nprint('kappa/2/pi (kHz)=',kappa/2/np.pi)\n# note that detunings include zeroth order correction for linearised versions\n# as a first pass work out frequencies with Wk0=0\nWkx0=WK*X0 #was commented out\nOmX=Polaris*epsTW**2/XM/WX**2\nOmY=Polaris*epsTW**2/XM/WY**2\nOmZ=0.5*Polaris*epsTW**2/XM/ZR**2\n\nprint('Wkxeq',Wkx0)\n# OPtomechanical drive frequency\nprint('epsTW,epsCAV', epsTW,epsCAV)\n\n# theta vs thet\nthet = theta0 * np.pi\n\n# Sept 5 we will use negative Edip\nEdip=-0.5*Polaris*epsTW*epsCAV*np.sin(thet)\nEdiph=Edip/hbar\nprint('Edip/2/pi/hbar=', Ediph/2/np.pi)\n# photon number in cavity\n# real part of photon field\nALPRe=Det2pi*Ediph*np.cos(Wkx0)/(kapp2**2+Det2pi**2)\nALPim=-kapp2*Ediph*np.cos(Wkx0)/(kapp2**2+Det2pi**2)\nNphoton=Ediph*Ediph*np.cos(Wkx0)*np.cos(Wkx0)\nNphoton=Nphoton/(kapp2**2+Det2pi**2)\nprint('delta,kappa/2,number of photons in cavity', Det2pi/2/np.pi,kapp2/2/np.pi,Nphoton)\n\n### ADD CAVITY CORRECTION to frequency squared ###\nC1=-Edip/XM*2.*ALPRe*WK**2*np.cos(Wkx0)\nOmX=OmX+C1*np.sin(thet)*np.sin(thet)\nOmY=OmY+C1*np.cos(thet)*np.cos(thet)\nOmZ=OmZ-2.*Edip/XM*ALPRe*(WK-1/ZR)**2*np.cos(Wkx0)\n\nomega_j = np.array([np.sqrt(OmX), np.sqrt(OmY), np.sqrt(OmZ)])\nprint('mech freq Omx/2pi=',omega_j[0]/2/np.pi)\nprint('mech freq Omy/2pi=',omega_j[1]/2/np.pi)\nprint('mech freq Omz/2pi=',omega_j[2]/2/np.pi)\n\n#&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&\n \n### resulting variables ###\nn_opt = 0\nn_mech = k*T/(hbar * omega_j)\n \nNPTS = 2000/2\nomega = np.linspace(0, 2*omega_j[0]+1, NPTS)\n \n \n \ndef calculate_couplings():\n# Optomechanical couplings\n XZPF = np.sqrt(hbar/(2*XM*omega_j[0]))\n YZPF = np.sqrt(hbar/(2*XM*omega_j[1]))\n ZZPF = np.sqrt(hbar/(2*XM*omega_j[2]))\n\n GX = Ediph*WK*XZPF*np.sin(thet)*np.sin(Wkx0)\n GY = Ediph*WK*YZPF*np.cos(thet)*np.sin(Wkx0)\n GZ = -Ediph*(WK-1/ZR)*ZZPF*np.cos(Wkx0)\n # write(iwrite,*)'GX , GY, GZ in Hz',GX/2/pi,GY/2/pi,Gz/2/pi\n# corrected sign on 29/8/2019\n GXY = Ediph*WK*XZPF*WK*YZPF*ALPRe*np.sin(2*thet)*np.cos(Wkx0)\n GZX = 2*Ediph*(WK-1/ZR)*ZZPF*WK*XZPF*ALPim*np.sin(Wkx0)*np.sin(thet)\n GYZ = 2*Ediph*(WK-1/ZR)*ZZPF*WK*YZPF*ALPim*np.sin(Wkx0)*np.cos(thet)\n #write(iwrite,*)'GXY , GYZ, GZX in Hz',GXY/2/pi,GYZ/2/pi,GZX/2/pi\n \n print('couplings')\n print('GX, GY, GZ', GX/2/np.pi, GY/2/np.pi, GZ/2/np.pi)\n print('GXY, GYZ, GZX', GXY/2/np.pi, GYZ/2/np.pi, GZX/2/np.pi)\n return [GX, GY, GZ, GXY, GYZ, GZX]\n\n########################################################################\n \n############ \n### MAIN ###\n############\n\n#################\n### FUNCTIONS ###\n#################\n \ng = np.array(calculate_couplings()[0:3] )\nGamm2 = Gamma/2\n\n#print(g)\n\n#################\n### FUNCTIONS ###\n#################\n\ndef opt_damp_rate(_kappa, _detuning, _g, _omega_j):\n det2 = _detuning * 2*np.pi\n Gamma_opt = -_g**2 * _kappa * (1/(_kappa**2/4 + (det2+_omega_j)**2) - 1/(_kappa**2/4 + (det2-_omega_j)**2) ) \n\n print()\n print('optical damping rates')\n print('$\\Gamma_{opt, x}$:', round(Gamma_opt[0]/1e5, 5), '1e5')\n print('$\\Gamma_{opt, y}$:', round(Gamma_opt[1]/1e5, 5), '1e5')\n print('$\\Gamma_{opt, z}$:', round(Gamma_opt[2]/1e5, 5), '1e5')\n \n# print('mechanical damping')\n# print('X', Gamma[0])\n \n return Gamma_opt\n\n\ndef photon_number(_n_j, _Gamma_opt, _Gamma_j):\n N = 2*_n_j * _Gamma_j / (abs(_Gamma_opt) + 2*_Gamma_j)\n \n print()\n print('theoretical photon numbers at equiv')\n print('n_x theo: ', round(N[0], 3))\n print('n_y theo: ', round(N[1], 3))\n print('n_z theo: ', round(N[2], 3))\n \n print('theoretical photon numbers at room temperature')\n print('n_x theo: ', round(n_mech[0]/1e8, 5), '1e8')\n print('n_y theo: ', round(n_mech[1]/1e8, 5), '1e8')\n print('n_z theo: ', round(n_mech[2]/1e8, 5), '1e8')\n \n return N\n\nCHIR1 = 0\nCHISTMOM1 = 0\nCHIMX = 0\nCHIMMOMX = 0\nCHIMY = 0\nCHIMMOMY = 0\nCHIMZ = 0\nCHIMMOMZ = 0\n\n#********************************************************************\n# Generic routine for noise spectra of trap and probe beams\n#********************************************************************\n#def Suscept(OMEGA,DET1x,Kapp2,gamm,OMX,OMY,OMZ,CHIR1,CHISTMOM1,CHIMX,CHIMMOMX,CHIMY,CHIMMOMY,CHIMZ,CHIMMOMZ):\n #Suscept(OMEGA,DET,Kapp2,GAMMAM,OMX,OMY,OMZ,CHIR1,CHISTMOM1,CHIMX,CHIMMOMX,CHIMY,CHIMMOMY,CHIMZ,CHIMMOMZ)\n \n #detuning = det\n\n#def Avect(GMAT,Gamm,kapp2,CHIR1,CHISTMOM1,CHIMX,CHIMMOMX,CHIMY,CHIMMOMY,CHIMZ,CHIMMOMZ,A1,A1dagg,BAX,BAY,BAZ):\n# Avect(GMAT,GAMMAM,Kapp2,CHIR1,CHISTMOM1,CHIMX,CHIMMOMX,CHIMY,CHIMMOMY,CHIMZ,CHIMMOMZ,A1,A1dagg,BAX,BAY,BAZ)\n \n\n\n\n#def Homodyne(NTOT,AVNX,AVNY,AVNZ,AVPHOT,THETA,A1,A1dagg,SHOM1):\n# Homodyne(NT,AVNX,AVNY,AVNZ,AVPHOT,THETA,A1,A1dagg,SHOM1)\n \nXXF = 0\n \ndef ANALYT(GMAT,AVNX,AVNY,AVNZ,AVPHOT,THETA,DET,Kapp2,GAMMAM,OMX,OMY,OMZ,omega,XXF,YYF,ZZF,SHOM1):\n detuning = DET\n\n#************************************************************************\n#************************************************************************\n# First do susceptibilities\n##### ROUTINE SUCEPT #########\n Gamm2 = GAMMAM\n ANORM = KAPP2**2+ (omega+detuning)**2\n t1=KAPP2/ANORM\n t2= (omega+detuning)/ANORM\n CHIR1 = t1 + t2*1j\n \n #print(CHIR1)\n# chi_r^*(-omega)\n ANORM = KAPP2**2+ (-omega+detuning)**2\n t1=KAPP2/ANORM\n t2= (-omega+detuning)/ANORM\n CHISTMOM1=t1-t2*1j\n #******************************************\n# X MECHANICAL susceptibilities\n# chi_M X\n BNORM=(Gamm2)**2 + (omega-OMX)**2\n t1= (Gamm2)/BNORM\n t2=(omega-OMX)/BNORM\n CHIMX=t1+t2*1j\n#CHI_M*(-om) X\n T1=(Gamm2)**2 + (-omega-OMX)**2\n CHIMMOMX= Gamm2/T1 + 1j*(omega+OMX)/T1\n \n \n# Y MECHANICAL susceptibilities\n# chi_M Y\n BNORM=(Gamm2)**2 + (omega-OMY)**2\n t1= (Gamm2)/BNORM\n t2=(omega-OMY)/BNORM\n CHIMY=t1 + 1j*t2\n # CHI_M*(-om) Y\n T1=(Gamm2)**2 + (-omega-OMY)**2\n CHIMMOMY=Gamm2/T1 + 1j* (omega+OMY)/T1\n #****************************************************\n #******************************************\n # Z MECHANICAL susceptibilities\n # chi_M Z\n BNORM=(Gamm2)**2 + (omega-OMZ)**2\n t1= (Gamm2)/BNORM\n t2=(omega-OMZ)/BNORM\n CHIMZ=t1 + 1j*t2\n # CHI_M*(-om) Z\n T1=(Gamm2)**2 + (-omega-OMZ)**2\n CHIMMOMZ=Gamm2/T1 + 1j* (omega+OMZ)/T1\n #****************************************************\n########################################\n\n\n#########################################\n### ROUTINE AVECT ####\n Gamm = GAMMAM\n GX=GMAT[0]\n GY=GMAT[1]\n GZ=GMAT[2]\n GXY=0\n GYZ=0\n GZX=0\n#&&&&&&&&& 2D &&&&&&&&&&&&&&&&&&\n# as we only want x spectrum, switch off other couplings\n GY=0\n GZ=0\n GXY=0\n GYZ=0\n GZX=0\n\n#&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&& \n# actually Gamm is gamma/2\n Gamm2=Gamm\n# zero arrays\n BAX=np.array([0+0j,0,0,0,0,0,0,0])\n BAY=np.array([0+0j,0,0,0,0,0,0,0])\n BAZ=np.array([0+0j,0,0,0,0,0,0,0])\n\n NTOT = 8\n N0X=np.array([0+1j,0,0,0,0,0,0,0])\n N0Y=np.array([0+1j,0,0,0,0,0,0,0])\n N0Z=np.array([0+1j,0,0,0,0,0,0,0])\n #A1=0\n #A1dagg=0\n# i\n XI=1j\n ONE=1\n\n# SUSCEPTIBILITIES\n eta0c=CHIR1-CHISTMOM1\n etaMpi2c=XI*(CHIR1+CHISTMOM1)\n etaPpi2c=-XI*(CHIR1+CHISTMOM1)\n etax=CHIMX-CHIMMOMX\n etay=CHIMY-CHIMMOMY\n etaz=CHIMZ-CHIMMOMZ\n\n# coeff of X-Y coupling- Combines direct and indirect paths\n GcoefXY=(GXY+1j*eta0c*GX*GY)\n GcoefYX=(GXY+1j*eta0c*GX*GY)\n GcoefXZ=(GZX+1j*etaMpi2c*GZ*GX)\n GcoefZX=(GZX+1j*etaPpi2c*GZ*GX)\n GcoefYZ=(GYZ+1j*etaMpi2c*GY*GZ)\n GcoefZY=(GYZ+1j*etaPpi2c*GY*GZ)\n#!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!\n# GcoefXY=CMPLX(0.d0,0.d0)\n # GcoefZX=CMPLX(0.d0,0.d0)\n # GcoefYZ=CMPLX(0.d0,0.d0)\n# NORMALIZATIONS\n CMX=1+GX**2*etax*eta0c\n CMY=1+GY**2*etay*eta0c\n CMZ=1+GZ**2*etaz*eta0c\n \n\n Sqrtkapp=np.sqrt(2*KAPP2)\n Sqrtgamm=np.sqrt(2*Gamm2)\n BETX=1j*Sqrtkapp*etax*GX\n BETY=1j*Sqrtkapp*etay*GY\n BETZ=1j*Sqrtkapp*etaz*GZ\n#&&&&&&&&&&&&&&&&&&&&&&&&\n# zero-th order X noise vector; weights of a1,a1*,bx,bx*,by,by*,bz,bz*\n # print(CHIR1.size)\n N0X[0]=BETX*CHIR1/CMX\n N0X[1]=BETX*CHISTMOM1/CMX\n N0X[2]=Sqrtgamm*CHIMX/CMX\n N0X[3]=Sqrtgamm*CHIMMOMX/CMX\n\n# Zero-th order Y noise vector;weights of a1,a1*,bx,bx*,by,by*,bz,bz*\n N0Y[0]=BETY*CHIR1/CMY\n N0Y[1]=BETY*CHISTMOM1/CMY\n N0Y[4]=Sqrtgamm*CHIMY/CMY\n N0Y[5]=Sqrtgamm*CHIMMOMY/CMY\n# Zero-th Z noise vector;weights of a1,a1*,bx,bx*,by,by*,bz,bz*\n N0Z[0]=-1j*BETZ*CHIR1/CMZ\n N0Z[1]=1j*BETZ*CHISTMOM1/CMZ\n N0Z[6]=Sqrtgamm*CHIMZ/CMZ\n N0Z[7]=Sqrtgamm*CHIMMOMZ/CMZ\n\n \n# for i in range(NTOT):\n# BAX[i]=N0X[i]\n# BAY[i]=N0Y[i]\n# BAZ[i]=N0Z[i]\n \n#&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&\n# Higher order\n RXY=1j*etax*GcoefXY/CMX\n RYX=1j*etay*GcoefYX/CMY\n RXZ=1j*etax*GcoefXZ/CMX\n RZX=1j*etaz*GcoefZX/CMZ\n RYZ=1j*etay*GcoefYZ/CMY\n RZY=1j*etaz*GcoefZY/CMZ\n\n #print(RXY, RYX, RXZ, RZX, RYZ, RZY)\n# RXY=CMPLX(0.d0,0.d0)\n # RYX=CMPLX(0.d0,0.d0)\n# RXZ=CMPLX(0.d0,0.d0)\n# RZX=CMPLX(0.d0,0.d0)\n# RYZ=CMPLX(0.d0,0.d0)\n# RZY=CMPLX(0.d0,0.d0)\n\n CNORM=1-RZX*RXZ-RZY*RYZ-RYX*RXY-RZX*RXY*RYZ-RYX*RXZ*RZY\n \n# ADD 3D BACK-ACTION TERMS\n for i in range(NTOT):\n CSUM=(1-RZY*RYZ)*N0X[i]+(RXY+RXZ*RZY)*N0Y[i]+(RXZ+RXY*RYZ)*N0Z[i]\n BAX[i]=BAX[i]+CSUM/CNORM\n CSUM=(1-RZX*RXZ)*N0Y[i]+(RYX+RYZ*RZX)*N0X[i]+(RYZ+RYX*RXZ)*N0Z[i]\n BAY[i]=BAY[i]+CSUM/CNORM\n CSUM=(1-RYX*RXY)*N0Z[i]+(RZX+RZY*RYX)*N0X[i]+(RZY+RZX*RXY)*N0Y[i]\n BAZ[i]=BAZ[i]+CSUM/CNORM\n \n #print(omega, BAX[0])\n \n# now work out the optical trap field =a1\n CA1=XI*CHIR1\n# now work out the photon field a1dagger\n CA1dagg=-XI*CHISTMOM1\n \n A1 = np.array([0+1j,0,0,0,0,0,0,0])\n A1dagg = np.array([0+1j,0,0,0,0,0,0,0])\n#\n for i in range(NTOT):\n A1[i]=CA1*(GX*BAX[i]+GY*BAY[i]+GZ*BAZ[i])\n A1dagg[i]=CA1dagg*(GX*BAX[i]+GY*BAY[i]+GZ*BAZ[i])\n \n# add shot or incoming noise\n# trap beam: add cavity-filtered contribution\n A1[1]=A1[1]+Sqrtkapp*CHIR1\n A1dagg[2]=A1dagg[2]+Sqrtkapp*CHISTMOM1\n\n# cavity output : add incoming imprecision\n# work out a_out=a_in-Sqrtkapp(a)\n for i in range(NTOT):\n A1[i]=-A1[i]*Sqrtkapp\n A1dagg[i]=-A1dagg[i]*Sqrtkapp\n \n A1[1]=ONE+A1[1]\n A1dagg[2]=ONE+A1dagg[2]\n#####################################################################\n \n#####################################################################\n ### ROUTINE HOMODYNE ###\n NTOT = 8\n \n theta = 0\n XAM1 = np.array([0+1j,0,0,0,0,0,0,0])\n XPM1 = np.array([0+1j,0,0,0,0,0,0,0])\n XTHET1 = np.array([0+1j,0,0,0,0,0,0,0]) \n for i in range(8):\n XAM1[i]=A1[i]+A1dagg[i]\n XPM1[i]=1j*(A1[i]-A1dagg[i])\n \n XTHET1[i]=XPM1[i]*np.sin(theta)+XAM1[i]*np.cos(theta)\n \n SHOM1=0\n \n SHOM1=SHOM1+abs(XTHET1[0])**2*AVPHOT+abs(XTHET1[1])**2*(AVPHOT+1)\n SHOM1=SHOM1+abs(XTHET1[2])**2*AVNX+abs(XTHET1[3])**2*(AVNX+1)\n SHOM1=SHOM1+abs(XTHET1[4])**2*AVNY+abs(XTHET1[5])**2*(AVNY+1)\n SHOM1=SHOM1+abs(XTHET1[6])**2*AVNZ+abs(XTHET1[7])**2*(AVNZ+1)\n #SHOM1 = tools.spectrum(XTHET1, n_opt, n_mech)\n\n########################################################################### \n # G2NORM=G2*G2*(ABS(CHIR2-cos(2*theta)*CHISTMOM2))**2\n \n # work out noise vector for x, a1 and a2\n #Avect(GMAT,GAMMAM,Kapp2,CHIR1,CHISTMOM1,CHIMX,CHIMMOMX,CHIMY,CHIMMOMY,CHIMZ,CHIMMOMZ,A1,A1dagg,BAX,BAY,BAZ)\n # work out homodyne spectra\n \n XXF=(abs(BAX[0]))**2\n XXF=XXF+ (AVNX+1)*(abs(BAX[2]))**2+AVNX*(abs(BAX[3]))**2+(AVNY+1)*abs(BAX[4])**2+AVNY*abs(BAX[5])**2\n XXF=XXF+ (AVNZ+1)*(abs(BAX[6]))**2+AVNZ*(abs(BAX[7]))**2\n\n YYF=(abs(BAY[0]))**2\n YYF=YYF+ (AVNX+1)*(abs(BAY[2]))**2+AVNX*(abs(BAY[3]))**2+(AVNY+1)*abs(BAY[4])**2+AVNY*abs(BAY[5])**2\n YYF=YYF+ (AVNZ+1)*(abs(BAY[6]))**2+AVNZ*(abs(BAY[7]))**2\n\n ZZF=(abs(BAZ[0]))**2\n ZZF=ZZF+ (AVNX+1)*(abs(BAZ[2]))**2+AVNX*(abs(BAZ[3]))**2+(AVNY+1)*abs(BAZ[4])**2+AVNY*abs(BAZ[5])**2\n ZZF=ZZF+ (AVNZ+1)*(abs(BAZ[6]))**2+AVNZ*(abs(BAZ[7]))**2\n\n\n #XXF = tools.spectrum(BAX, n_opt, n_mech)\n #XXF = tools.spectrum(BAX, n_opt, n_mech)\n #XXF = tools.spectrum(BAX, n_opt, n_mech)\n return XXF, YYF, ZZF\n \n\n'''\n# SUSCEPTIBILITIES\n eta0c=CHIR1-CHISTMOM1\n etaMpi2c=1j*(CHIR1+CHISTMOM1)\n etaPpi2c=-1j*(CHIR1+CHISTMOM1)\n etaX=CHIMX-CHIMMOMX\n #etaY=CHIMY-CHIMMOMY\n #etaZ=CHIMZ-CHIMMOMZ\n\n# NORMALIZATIONS\n CMX=1+g[0]**2*etaX*eta0c\n \n\n Sqrtkapp=np.sqrt(2*KAPP2)\n Sqrtgamm=np.sqrt(2*Gamm2)\n BETX=1j*Sqrtkapp*etaX*g[0]\n \n#&&&&&&&&&&&&&&&&&&&&&&&&\n# zero-th order X noise vector; weights of a1,a1*,bx,bx*,by,by*,bz,bz*\n N0X1=BETX*CHIR1/CMX\n N0X2=BETX*CHISTMOM1/CMX\n N0X3=Sqrtgamm*CHIMX/CMX\n N0X4=Sqrtgamm*CHIMMOMX/CMX\n\n\n XPM1=0\n XAM1=0\n\n XTHET1=0\n\n \n#XX= sqrt(0.5) (b+b^dagg) so halve XX,\n XXF=np.abs(N0X1)**2\n XXF=XXF+ (n_mech[0]+1)*np.abs(N0X3)**2+n_mech[0]*np.abs(N0X4)**2\n return XXF\n'''\n\n\ndef area(S, omega): \n\n# integrate the position spectrum of bead\n# quick hack - use trapezoidal rule- improve later\n summe=0\n Delta=np.abs(omega[1]-omega[0])\n for i in range(len(S)-1):\n Tem = 0.5*(S[i]+S[i+1])\n summe = summe + Tem\n return summe*Delta / (2*np.pi)\n \n\n\n\n#***************************************************************\n#&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&\n# open loop over frequency for noise spectra eg S_xx(\\omega)=FT(autocorrelation )\n\n\n# optical damping rates\nGamma_opt = opt_damp_rate(kappa, detuning, g, omega_j)\n\n# photon numbers at equiv\nN = photon_number(n_mech, Gamma_opt, Gamma)\n\nAVNX = n_mech[0]\nAVNY = n_mech[1]\nAVNZ = n_mech[2]\nAVPHOT = 0\nTHETAHOM = 0\nDET2pi = detuning*2*np.pi\nKapp2 = kappa/2\nGAMMAM = Gamma\nOMX = omega_j[0]\nOMY = omega_j[1]\nOMZ = omega_j[2]\nXXQM = 0\nYYQM = 0 \nZZQM = 0\nSHOM1 = 0\nGMAT = g\n\nSXX_plus = np.zeros(len(omega))\nSXX_minus = np.zeros(len(omega))\nfor i in range(len(omega)):\n OMsweep = omega[i]\n XXF, YYF, ZFF = ANALYT(GMAT,AVNX,AVNY,AVNZ,AVPHOT,THETAHOM,DET2pi,Kapp2,GAMMAM,OMX,OMY,OMZ,-OMsweep,XXQM,YYQM,ZZQM,SHOM1)\n SXX_minus[i] = XXF \n XXF, YYF, ZZF = ANALYT(GMAT,AVNX,AVNY,AVNZ,AVPHOT,THETAHOM,DET2pi,Kapp2,GAMMAM,OMX,OMY,OMZ,OMsweep,XXQM,YYQM,ZZQM,SHOM1)\n SXX_plus[i] = XXF\n\nplt.plot(omega/2/np.pi*1e-3, SXX_plus)\nplt.plot(omega/2/np.pi*1e-3, SXX_minus)\nplt.show()\n\n#delta_omega = omega[1]-omega[0]\n\n# calculate photon numbers from area\nN_X_plus = area(SXX_plus, omega)\nN_X_minus = area(SXX_minus, omega)\nN_X = (N_X_plus + N_X_minus -1)/2\n\nprint()\nprint('photon number from area, difference')\nprint('X +:', round(N_X_plus, 4), '(', round((N_X_plus-N[0])/(N[0]+1)*100, 2), '% )')\nprint('X -:', round(N_X_minus, 4), '(', round((N_X_minus-N[0])/(N[0])*100, 2), '% )')\nprint('X summed:', round(N_X, 4), '(', round((N_X-N[0])/(N[0])*100, 2), '% )')\n#print('area -', area(SXX_minus, omega))\n\n\n#for i in range(len(omega)):\n# print(omega[i]/2/np.pi*1e-6, SXX_plus[i])","repo_name":"Miriam-Gerharz/UCL-project","sub_path":"1D_system_right_quant.py","file_name":"1D_system_right_quant.py","file_ext":"py","file_size_in_byte":18768,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"17"} +{"seq_id":"72119314904","text":"\nimport pandas as pd\nimport numpy as np\nfrom io import StringIO\nfrom itertools import product, count\nfrom functools import partial, reduce\nfrom operator import add\n\nf = open(\"day22.txt\", \"r\")\ntext = f.read().replace(\"on \", \"1,\").replace(\"off \", \"0,\").replace(\"x=\", \"\").replace(\"y=\", \"\").replace(\"z=\", \"\").replace(\"..\", \",\")\nsteps = pd.read_csv(StringIO(text), names=[\"state\", \"x0\", \"x1\", \"y0\", \"y1\", \"z0\", \"z1\"]).astype(int).astype({\"state\": bool})\n\nm = np.zeros((101, 101, 101), dtype=bool)\nfor state, x0, x1, y0, y1, z0, z1 in steps.itertuples(index=False):\n m[\n (50 + min(51, max(-50, x0))):(50 + min(51, max(-50, x1 + 1))),\n (50 + min(51, max(-50, y0))):(50 + min(51, max(-50, y1 + 1))),\n (50 + min(51, max(-50, z0))):(50 + min(51, max(-50, z1 + 1))),\n ] = state \nprint(\"Number of cubes on:\", m.sum())\n\nxs = sorted(list(set(steps[\"x0\"].tolist() + (steps[\"x1\"] + 1).tolist())))\nys = sorted(list(set(steps[\"y0\"].tolist() + (steps[\"y1\"] + 1).tolist())))\nzs = sorted(list(set(steps[\"z0\"].tolist() + (steps[\"z1\"] + 1).tolist())))\nn_x = len(xs)\nn_y = len(ys)\nn_z = len(zs)\nprint(\"# x endoints:\", n_x, \"# y endoints:\", n_y, \"# z endoints:\", n_z)\n\ndx = np.array(xs[1:], dtype=int) - np.array(xs[:-1], dtype=int)\ndy = np.array(ys[1:], dtype=int) - np.array(ys[:-1], dtype=int)\ndz = np.array(zs[1:], dtype=int) - np.array(zs[:-1], dtype=int)\nmm = (\n np.tile(dx.reshape((-1, 1, 1)), (1, n_y - 1, n_z - 1)) *\n np.tile(dy.reshape((1, -1, 1)), (n_x - 1, 1, n_z - 1)) *\n np.tile(dz.reshape((1, 1, -1)), (n_x - 1, n_y - 1, 1))\n)\nmmm = np.zeros((n_x - 1, n_y - 1, n_z - 1), dtype=bool)\nfor state, x0, x1, y0, y1, z0, z1 in steps.itertuples(index=False):\n ix0 = xs.index(x0)\n ix1 = xs.index(x1 + 1)\n iy0 = ys.index(y0)\n iy1 = ys.index(y1 + 1)\n iz0 = zs.index(z0)\n iz1 = zs.index(z1 + 1)\n mmm[ix0:ix1, iy0:iy1, iz0:iz1] = state\nprint(\"Number of cubes on:\", (mm * mmm).sum())\n","repo_name":"joaopmatias/adventofcode","sub_path":"2021/day22.py","file_name":"day22.py","file_ext":"py","file_size_in_byte":1917,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"17"} +{"seq_id":"74506220183","text":"import asyncio\nimport re\nfrom datetime import datetime, timedelta, timezone\nfrom json import dumps, loads\nfrom typing import Dict, List, Optional\nfrom uuid import uuid4\n\nfrom aiohttp import ClientSession\nfrom slack import WebClient\nfrom slack.errors import SlackApiError\nfrom slack.web.base_client import SlackResponse\n\nfrom ..config import ConfigSchema\nfrom ..models import Request, RequestMessage, ScheduleEvent, SlackAction\nfrom ..models.blockkit import (\n actions,\n button,\n checkbox,\n checkboxes,\n confirm,\n context,\n find_block,\n group_info,\n inputbox,\n inputsection,\n md,\n remove_actions,\n remove_blocks,\n section,\n text,\n timestamp,\n)\nfrom .ggroups import GoogleGroupsController\nfrom .ldap import LDAPController\nfrom .request import RequestController\nfrom .schedule import ScheduleController\n\nPAGE_SIZE = 30\n\nREQUEST_SENT = 1\nMEMBERS_ADDED = 2\nREASON_REQUESTED = 4\n\n\nclass SlackActionController(object):\n def __init__(\n self,\n client: WebClient,\n ldap: LDAPController,\n ggroups: GoogleGroupsController,\n schedule: ScheduleController,\n request: RequestController,\n config: ConfigSchema,\n ) -> None:\n # Variables starting with _ are protected. This means that they cannot be read\n # from outside this class\n self._client: WebClient = client\n self._ldap: LDAPController = ldap\n self._ggroups: GoogleGroupsController = ggroups\n self._schedule: ScheduleController = schedule\n self._request: RequestController = request\n self._approvals_channel: str = config.slack.approvals_channel\n self._domain: str = config.domain\n\n self._approval_timeout = timedelta(minutes=config.approval_timeout)\n self._regex_email = re.compile(\n r\"^(?:)?$\".format(\n domain=config.domain.replace(\".\", r\"\\.\")\n ),\n re.IGNORECASE,\n )\n self._action_map = {\n \"ggroups_show_members\": self.send_members_page,\n \"ggroups_next\": self.send_members_page,\n \"ggroups_previous\": self.send_members_page,\n \"ggroups_user_join\": self.send_join_request,\n \"ggroups_user_become_owner\": self.send_owner_request,\n \"ggroups_user_leave\": self.leave_group,\n \"ggroups_join_approve\": self.approve_join_group,\n \"ggroups_join_deny\": self.deny_request,\n \"ggroups_become_owner_approve\": self.approve_become_owner,\n \"ggroups_become_owner_deny\": self.deny_request,\n \"ggroups_create_approve\": self.approve_create_group,\n \"ggroups_create_deny\": self.deny_request,\n \"ggroups_start_create_group\": self.send_create_group_options,\n \"ggroups_manage_group\": self.send_manage_group_options,\n \"ggroups_manage_add_members\": self.send_add_members_options,\n \"ggroups_manage_remove_members\": self.send_remove_members_options,\n }\n\n # Short term hold for requests waiting for reason messages\n # Key is request_id\n self.held_actions: Dict[str, SlackAction] = {}\n\n # Register callbacks with the schedule controller\n self._schedule.register_callback(\"ggroups_approval_timeout\", self.timeout_join_request)\n\n @staticmethod\n async def _respond(url: str, **kwargs: Dict[str, any]) -> None:\n async with ClientSession() as session:\n async with session.post(url, json=kwargs) as response:\n if response.status > 299:\n print(\"Error sending action response:\", await response.text())\n\n async def _update(self, msg: RequestMessage, **kwargs: Dict[str, any]) -> None:\n await self._client.chat_update(channel=msg.channel, ts=msg.ts, **kwargs)\n\n async def _inform_targets(\n self, action: SlackAction, request: Request, requester_id: str\n ) -> None:\n skipped = {\n requester_id,\n action.user_id,\n }\n targets = action.value.get(\"targets\", [])\n if action.action_id == \"ggroups_create_approve\":\n targets = action.value.get(\"members\", []) + action.value.get(\"owners\", [])\n await asyncio.gather(\n *[\n self._client.chat_postMessage(\n channel=target,\n text=(f\"You have been {request.heads_up_text}\" f\" by <@{requester_id}>\"),\n )\n for target in targets\n if target not in skipped\n ]\n )\n\n async def _respond_to_approval(self, action: SlackAction, approved: bool) -> None:\n blocks = remove_blocks(\n blocks=action.message[\"blocks\"], block_ids=[\"ggroups_approvals_choice\"]\n )\n result = \"approved\" if approved else \"denied\"\n result_md = \":check: approved\" if approved else \":denied-animated: denied\"\n\n approver = self._ldap.get_user_from_slack(action.user_id)\n request: Request = await self._request.record_request_result(\n request_id=action.request_id, approver_email=approver.email, approved=approved,\n )\n blocks.append(\n context(\n md(\n f\"<@{action.user_id}> has {result_md} this request \"\n f\"{timestamp(request.approval_timestamp)}\"\n )\n )\n )\n\n # Update all owners and admins that got the request\n await asyncio.gather(\n *[\n self._update(\n msg, blocks=blocks, text=f\"Request {result}\", as_user=True, parse=\"full\"\n )\n for msg in request.messages\n ]\n )\n\n # Update the approver on the result\n await self._respond(\n action.response_url, blocks=blocks, text=f\"Request {result}\", replace_original=True\n )\n\n # Update the requester too\n requester = self._ldap.get_user_from_aliases(\n self._ggroups.get_user_emails(request.requester_email)\n )\n await self._client.chat_postMessage(\n channel=requester.aliases[\"slack\"],\n text=f\"Request {result}\",\n blocks=[\n section(\n md(\n f\"Your request to {request.recall_text} \"\n f\"has been {result_md} by <@{action.user_id}>\"\n )\n )\n ],\n as_user=True,\n )\n\n if approved:\n await self._inform_targets(action, request, requester.aliases[\"slack\"])\n\n async def _respond_already_approved(self, action: SlackAction, request: Request) -> None:\n result = \"approved\" if request.approved else \"denied\"\n approver = self._ldap.get_user_from_aliases(\n self._ggroups.get_user_emails(request.approver_email)\n )\n\n blocks = remove_blocks(\n blocks=action.message[\"blocks\"], block_ids=[\"ggroups_approvals_choice\"]\n )\n blocks.append(\n section(md(f\"<@{approver.aliases['slack']}> has already {result} this request\"))\n )\n await self._respond(\n action.response_url,\n blocks=blocks,\n text=f\"Request already {result}\",\n replace_original=True,\n )\n\n async def _respond_unauthorised(self, action: SlackAction) -> None:\n blocks = [section(text(\"Sorry, you are not authorised to do that\"))]\n return await self._client.chat_postEphemeral(\n channel=action.channel_id,\n user=action.user_id,\n text=\"You are not authorised to do that\",\n blocks=blocks,\n as_user=True,\n )\n\n async def _add_eyes(self, action: SlackAction) -> None:\n try:\n await self._client.reactions_add(\n name=\"eyes\", channel=action.channel_id, timestamp=action.message[\"ts\"]\n )\n except SlackApiError:\n # Ignore errors\n pass\n\n async def _remove_eyes(self, action: SlackAction) -> None:\n try:\n await self._client.reactions_remove(\n name=\"eyes\", channel=action.channel_id, timestamp=action.message[\"ts\"]\n )\n except SlackApiError:\n # Ignore errors\n pass\n\n def get_modal_value(self, action: SlackAction, key: str) -> any:\n for k, v in action.value.items():\n t = v[\"type\"]\n # Checkboxes are heavily nested\n # Return true if the checkbox with the desired key is checked\n if t == \"checkboxes\":\n for cbox in v.get(\"selected_options\", []):\n if cbox[\"value\"] == key:\n return True\n\n elif k == key:\n if t == \"multi_users_select\":\n return v.get(\"selected_users\", [])\n if t == \"plain_text_input\":\n # Slack used to return no value field,\n # Then they updated it and it returns null instead\n return v.get(\"value\", \"\") or \"\"\n\n async def _try_load_data(self, action: SlackAction) -> None:\n if \"requester\" in action.value:\n action.user = self._ldap.get_user_from_slack(action.value[\"requester\"])\n if \"group_id\" in action.value:\n action.group = await self._ggroups.get_from_id(action.value[\"group_id\"])\n\n async def route_action(self, action: SlackAction) -> None:\n await self._try_load_data(action)\n # Find the handler for this action, or fall back to self.unhandled_event\n handler = self._action_map.get(action.action_id, self.unhandled_event)\n await handler(action=action)\n\n async def unhandled_event(self, action: SlackAction) -> None:\n print(\"Unhandled action\", action.action_id)\n\n async def send_members_page(self, action: SlackAction) -> None:\n # This function is idempotent. Remove the message blocks that aren't needed\n # But preserve the original message\n blocks = remove_blocks(blocks=action.message[\"blocks\"], block_ids=[\"ggroups_members\"])\n actions = find_block(blocks=blocks, block_id=\"ggroups_actions\")\n actions[\"elements\"] = remove_actions(\n actions[\"elements\"], [\"ggroups_show_members\", \"ggroups_previous\", \"ggroups_next\"]\n )\n\n # Just send back no members\n if not len(action.group.members):\n msg = \"No members in this group\"\n blocks.append(section(md(msg)))\n await self._respond(action.response_url, blocks=blocks, text=msg, replace_original=True)\n return\n\n # The buttons need to have the whole value so that user and group can be resolved\n index = action.value.get(\"index\", 0)\n next_index = index + PAGE_SIZE\n previous_index = max(index - PAGE_SIZE, 0)\n if index != previous_index:\n action.value[\"index\"] = previous_index\n actions[\"elements\"].append(\n button(\"ggroups_previous\", \"\", text(\"Previous\"), dict(action.value))\n )\n\n if next_index < len(action.group.members):\n action.value[\"index\"] = next_index\n actions[\"elements\"].append(button(\"ggroups_next\", \"\", text(\"Next\"), dict(action.value)))\n\n group_members = sorted(action.group.members, key=lambda m: m.email)[\n index : index + PAGE_SIZE\n ]\n\n blocks.append(\n section(\n md(\"```\\n\" + \"\\n\".join(member.email for member in group_members) + \"```\"),\n block_id=\"ggroups_members\",\n )\n )\n\n await self._respond(\n action.response_url, blocks=blocks, text=\"Group members\", replace_original=True\n )\n\n async def _send_join_request(\n self, action: SlackAction, channel: str, targets: List[str], event_id: int = 0,\n ) -> SlackResponse:\n \"\"\"\n Sends the Slack approval requests to someone or somewhere\n \"\"\"\n user, group = action.user, action.group\n button_data = {\n \"request_id\": action.request_id,\n \"requester\": user.aliases[\"slack\"],\n \"targets\": targets,\n \"group_id\": group.group_id,\n }\n if event_id:\n button_data[\"event_id\"] = event_id\n\n # Summary changes based on targets and user\n targets_tags = [f\"<@{t}>\" for t in targets]\n summary = f\"{user.name} (<@{user.aliases['slack']}>) \"\n if len(targets) > 1 or targets[0] != user.aliases[\"slack\"]:\n summary += f\"has requested to add {', '.join(targets_tags)} to {group.email}\"\n else:\n summary += f\"has requested to join {group.email}.\"\n\n if \"reason\" in action.value:\n summary += f\"\\nReason: `{action.value['reason'] or 'Not specified'}`\"\n\n def confirm_message(action: str) -> str:\n return f\"{', '.join(targets_tags)} will be *{action}* to {group.email}\"\n\n blocks = [\n section(md(summary)),\n group_info(group),\n actions(\n \"ggroups_approvals_choice\",\n button(\n \"ggroups_join_approve\",\n \"primary\",\n text(\"Approve\"),\n button_data,\n confirm(confirm_message(\"added\")),\n ),\n button(\n \"ggroups_join_deny\",\n \"danger\",\n text(\"Deny\"),\n button_data,\n confirm(confirm_message(\"denied\")),\n ),\n ),\n ]\n\n return await self._client.chat_postMessage(\n channel=channel,\n text=\"Please review this Google Group join request\",\n blocks=blocks,\n as_user=True,\n )\n\n async def _send_join_requests(self, action: SlackAction) -> int:\n slack_targets = action.value[\"targets\"]\n\n # Ensure the payload contains the request id\n action.value[\"request_id\"] = action.request_id\n\n # Load the target emails\n targets = [self._ldap.get_user_from_slack(slack_id).email for slack_id in slack_targets]\n\n # Check if the group is protected or user is an owner\n # Also check if someone other than the requester is being added\n member = self._ggroups.find_member(action.group, action.user.email)\n if (\n (not action.group.protected and slack_targets == [action.user_id])\n or (member and member.is_owner)\n or action.user.is_admin\n ):\n error = await self._ggroups.add_members(action.group, targets)\n if error:\n raise RuntimeError(error)\n\n await self._request.add_join_request(\n request_id=action.request_id,\n targets=targets,\n requester_email=action.user.email,\n group_email=action.group.email,\n messages=[],\n )\n request = await self._request.record_request_result(\n request_id=action.request_id, approver_email=action.user.email, approved=True\n )\n\n requester_id = self._ldap.get_user_from_email(request.requester_email).aliases[\"slack\"]\n await self._inform_targets(action, request, requester_id)\n\n return MEMBERS_ADDED\n\n # Prompt a user to provide a reason for the request if they haven't already done so\n if \"reason\" not in action.value:\n await self.send_request_reason_prompt(action)\n return REASON_REQUESTED\n\n # If there are owners, create a timeout event to send the request to the\n # group create page\n owners = action.group.owners\n responses: List[SlackResponse] = []\n if owners:\n # Scheduled fail over to approvals channel if owners are there\n event: ScheduleEvent = await self._schedule.add_event(\n \"ggroups_approval_timeout\",\n (datetime.now(tz=timezone.utc) + self._approval_timeout).timestamp(),\n vars(action),\n )\n\n # Send to owners (top 3)\n for owner in owners[:3]:\n # It's hard to derive group owner slack IDs, since GoogleGroupMember\n # and LDAPUser are separate objects\n owner_ldap = self._ldap.get_user_from_aliases(\n self._ggroups.get_user_emails(owner.email)\n )\n if not owner_ldap:\n print(\n \"Failed to send Slack join request: Could not find LDAP user for owner\",\n owner.email,\n )\n continue\n responses.append(\n await self._send_join_request(\n action, owner_ldap.aliases[\"slack\"], slack_targets, event.event_id\n )\n )\n\n # No owners? Send to approvals channel\n else:\n responses.append(\n await self._send_join_request(action, self._approvals_channel, slack_targets)\n )\n\n await self._request.add_join_request(\n request_id=action.request_id,\n targets=targets,\n requester_email=action.user.email,\n group_email=action.group.email,\n messages=[RequestMessage.from_slack(slack_res) for slack_res in responses],\n reason=action.value[\"reason\"],\n )\n\n return REQUEST_SENT\n\n async def _send_become_owner_request(\n self, action: SlackAction, channel: str, event_id: int = 0\n ) -> SlackResponse:\n user, group = action.user, action.group\n button_data = {\n \"request_id\": action.request_id,\n \"requester\": user.aliases[\"slack\"],\n \"group_id\": group.group_id,\n }\n if event_id:\n button_data[\"event_id\"] = event_id\n summary = (\n f\"{user.name} (<@{user.aliases['slack']}>) has requested to \"\n f\"become an owner of {group.email}.\"\n )\n confirm_message = (\n lambda action: f\"{user.name} (<@{user.aliases['slack']}>) \"\n f\"will be *{action}* as an owner of {group.email}\"\n )\n\n blocks = [\n section(md(summary)),\n group_info(group),\n actions(\n \"ggroups_approvals_choice\",\n button(\n \"ggroups_become_owner_approve\",\n \"primary\",\n text(\"Approve\"),\n button_data,\n confirm(confirm_message(\"added\")),\n ),\n button(\n \"ggroups_become_owner_deny\",\n \"danger\",\n text(\"Deny\"),\n button_data,\n confirm(confirm_message(\"denied\")),\n ),\n ),\n ]\n\n return await self._client.chat_postMessage(\n channel=channel,\n text=\"Please review this Google Group become owner request\",\n blocks=blocks,\n as_user=True,\n )\n\n def get_held_action(self, request_id: str) -> Optional[SlackAction]:\n if request_id in self.held_actions:\n action = self.held_actions[request_id]\n del self.held_actions[request_id]\n return action\n\n async def send_request_reason_prompt(self, action: SlackAction) -> None:\n self.held_actions[action.request_id] = action\n\n blocks = [\n section(\n text(\n \"Please provide a reason for your request, to help our admins action it sooner.\"\n )\n ),\n inputsection(\n text(\"Reason\"),\n inputbox(\"ggroups_request_reason\", \"plain_text_input\", text(\"I like doggos\")),\n ),\n ]\n\n return await self._client.views_open(\n trigger_id=action.trigger_id,\n view={\n \"type\": \"modal\",\n \"callback_id\": \"ggroups_request_reason\",\n \"title\": text(\"Request Reason\"),\n \"submit\": text(\"Submit\"),\n \"close\": text(\"Cancel\"),\n \"blocks\": blocks,\n \"private_metadata\": action.request_id,\n },\n )\n\n async def send_join_request(self, action: SlackAction) -> None:\n blocks = remove_blocks(\n blocks=action.message[\"blocks\"], block_ids=[\"ggroups_members\", \"ggroups_actions\"]\n )\n\n try:\n result = await self._send_join_requests(action)\n except RuntimeError as error:\n print(\"Error adding user(s) to\", action.group.email, \":\", error)\n blocks.append(section(md(f\"Error joining group: {error}\")))\n await self._respond(action.response_url, blocks=blocks, text=\"Error joining group\")\n return\n\n msg = \"\"\n targets = action.value[\"targets\"]\n if result == REQUEST_SENT:\n msg = f\":email: Request sent to join {action.group.name} ({action.group.email})!\"\n elif result == MEMBERS_ADDED:\n if targets[0] == action.user_id and len(targets) == 1:\n msg = (\n \":heavy_check_mark: You have joined \"\n f\"{action.group.name} ({action.group.email})!\"\n )\n else:\n users = \", \".join(f\"<@{t}>\" for t in targets[: min(len(targets), 3)])\n remainder = len(targets) - 3\n msg = (\n f\":heavy_check_mark: You have added {users} \"\n f\"{f'and {remainder} others ' if remainder > 0 else ''}\"\n f\"to {action.group.name} ({action.group.email})!\"\n )\n\n if msg:\n blocks.append(section(md(msg)))\n await self._respond(action.response_url, blocks=blocks, text=msg)\n\n async def timeout_join_request(self, event: ScheduleEvent) -> None:\n action: SlackAction = SlackAction.from_dict(event.payload)\n if \"targets\" not in action.value:\n group = action.group.email if action.group else \"UNKNOWN GROUP\"\n user = action.user.name if action.user else \"UNKNOWN USER\"\n print(f\"Request to add NO ONE to {group} by {user} is being dropped\")\n return\n targets_pretty: str = \", \".join(action.value[\"targets\"])\n print(\n f\"Request to owners to add {targets_pretty} to {action.group.email} timed out. \"\n \"Sending to channel\"\n )\n message = await self._send_join_request(\n action, self._approvals_channel, action.value[\"targets\"]\n )\n await self._request.add_messages(\n RequestMessage.from_slack(message), request_id=action.request_id\n )\n\n async def send_owner_request(self, action: SlackAction) -> None:\n # Ensure the payload contains the request id\n action.value[\"request_id\"] = action.request_id\n\n blocks = [\n section(\n md(\n \":heavy_check_mark: Sending request. You will receive a confirmation\"\n \" when it is sent and when it has been approved or denied.\"\n )\n )\n ]\n\n # If user closes the view fast this will fail\n try:\n await self._client.views_update(\n trigger_id=action.trigger_id,\n view_id=action.channel_id,\n view={\n \"type\": \"modal\",\n \"callback_id\": \"ggroups_close_modal\",\n \"title\": text(\"Become owner of group\"),\n \"close\": text(\"Back\"),\n \"submit\": text(\"Done\"),\n \"blocks\": blocks,\n },\n )\n except SlackApiError:\n pass\n\n # If there are owners, create a timeout event to send the request to the\n # group create page\n owners = action.group.owners\n responses: List[SlackResponse] = []\n if owners:\n # Scheduled fail over to approvals channel if owners are there\n event: ScheduleEvent = await self._schedule.add_event(\n \"ggroups_approval_timeout\",\n (datetime.now(tz=timezone.utc) + self._approval_timeout).timestamp(),\n vars(action),\n )\n\n # Send to owners\n owner_slacks: List[str] = []\n for owner in owners:\n # It's hard to derive group owner slack IDs, since GoogleGroupMember\n # and LDAPUser are separate objects\n owner_ldap = self._ldap.get_user_from_aliases(\n self._ggroups.get_user_emails(owner.email)\n )\n if not owner_ldap:\n print(\n \"Failed to send become owner request: \"\n \"Could not find LDAP user for existing owner\",\n owner.email,\n )\n else:\n owner_slacks.append(owner_ldap.aliases[\"slack\"])\n\n responses.extend(\n await asyncio.gather(\n *[\n self._send_become_owner_request(action, slack_id, event.event_id)\n for slack_id in owner_slacks\n ]\n )\n )\n\n # No owners? Send to approvals channel\n else:\n responses.append(await self._send_become_owner_request(action, self._approvals_channel))\n\n await self._request.add_become_owner_request(\n request_id=action.request_id,\n requester_email=action.user.email,\n group_email=action.group.email,\n messages=[RequestMessage.from_slack(slack_res) for slack_res in responses],\n )\n\n await self._client.chat_postMessage(\n channel=action.user.aliases[\"slack\"],\n text=\"Request sent!\",\n blocks=[\n section(md(f\":email: Request sent to become an owner of {action.group.email}!\"))\n ],\n as_user=True,\n )\n\n async def leave_group(self, action: SlackAction) -> None:\n member = self._ggroups.find_member(action.group, action.user.email)\n\n await self._client.views_push(\n trigger_id=action.trigger_id,\n view={\n \"type\": \"modal\",\n \"callback_id\": \"ggroups_close_modal\",\n \"title\": text(\"Leaving group\"),\n \"close\": text(\"Back\"),\n \"submit\": text(\"Done\"),\n \"blocks\": [\n section(\n md(\n \"Removing you from the group. This takes a second, \"\n \"you will receive a message when it is complete.\"\n )\n )\n ],\n },\n )\n\n msg = f\"You have left { action.group.name }\"\n try:\n await self._ggroups.remove_member(action.group, member)\n await self._request.add_leave_request(\n request_id=action.request_id,\n requester_email=member.email,\n group_email=action.group.email,\n )\n\n except ValueError as error:\n print(\"Error removing user\", member.email, \"from\", action.group.email, \":\", error)\n msg = f\"Error removing user from group: {error}\"\n\n await self._client.chat_postMessage(\n channel=action.user.aliases[\"slack\"], text=msg,\n )\n\n async def approve_join_group(self, action: SlackAction) -> None:\n # Check user permissions\n approver = self._ldap.get_user_from_slack(action.user_id)\n if (\n not action.group or approver.email not in action.group.owners\n ) and not approver.is_admin:\n await self._respond_unauthorised(action)\n return\n\n # Check existing approval\n request = await self._request.get_request(action.request_id)\n if request.approved is not None:\n await self._respond_already_approved(action, request)\n return\n\n # Add eyes as a reaction so people know it's being run\n await self._add_eyes(action)\n\n # Load the target users\n targets = [self._ldap.get_user_from_slack(slack_id) for slack_id in action.value[\"targets\"]]\n\n error = await self._ggroups.add_members(action.group, [t.email for t in targets])\n\n if error:\n print(\"Error adding user(s) to\", action.group.email, \":\", error)\n msg = f\"Error adding user(s) to group: {error}\"\n await self._respond(action.response_url, text=msg)\n\n else:\n await self._respond_to_approval(action, True)\n if \"event_id\" in action.value:\n await self._schedule.cancel_event(action.value[\"event_id\"])\n\n await self._remove_eyes(action)\n\n async def deny_request(self, action: SlackAction) -> None:\n # Check user permissions\n requester = self._ldap.get_user_from_slack(action.user_id)\n if (action.group and requester.email not in action.group.owners) and not requester.is_admin:\n await self._respond_unauthorised(action)\n return\n\n # Check existing approval\n request = await self._request.get_request(action.request_id)\n if request.approved is not None:\n await self._respond_already_approved(action, request)\n return\n\n if \"event_id\" in action.value:\n await self._schedule.cancel_event(action.value[\"event_id\"])\n\n await self._respond_to_approval(action, False)\n\n async def approve_become_owner(self, action: SlackAction) -> None:\n # Check user permissions\n approver = self._ldap.get_user_from_slack(action.user_id)\n if not approver.is_admin:\n await self._respond_unauthorised(action)\n return\n\n # Check existing approval\n request = await self._request.get_request(action.request_id)\n if request.approved is not None:\n await self._respond_already_approved(action, request)\n return\n\n # Add eyes as a reaction so people know it's being run\n await self._add_eyes(action)\n\n member = self._ggroups.find_member(action.group, action.user.email)\n\n if member in action.group.owners:\n print(\n \"Attempted double-approval of become owner \",\n action.user.email,\n \"to\",\n action.group.email,\n )\n msg = f\"This request has already been approved\"\n await self._respond(action.response_url, text=msg)\n\n error = await self._ggroups.change_role(action.group, member, \"OWNER\")\n\n if error:\n print(\"Error adding owner\", action.user.email, \"to\", action.group.email, \":\", error)\n msg = f\"Error adding owner to group: {error}\"\n await self._respond(action.response_url, text=msg)\n\n else:\n await self._respond_to_approval(action, True)\n if \"event_id\" in action.value:\n await self._schedule.cancel_event(action.value[\"event_id\"])\n\n await self._remove_eyes(action)\n\n async def approve_create_group(self, action: SlackAction) -> None:\n # Check user permissions\n approver = self._ldap.get_user_from_slack(action.user_id)\n if not approver.is_admin:\n await self._respond_unauthorised(action)\n return\n\n # Check existing approval\n request = await self._request.get_request(action.request_id)\n if request.approved is not None:\n await self._respond_already_approved(action, request)\n return\n\n # Add eyes as a reaction so people know it's being run\n await self._add_eyes(action)\n\n name = action.value[\"name\"]\n email = action.value[\"email\"]\n description = action.value[\"description\"]\n protect = action.value[\"protect\"]\n\n # Check if the group already exists. If the request crashed we don't want to duplicate it\n group = await self._ggroups.get_from_email(email)\n if not group:\n group = await self._ggroups.create(\n email=email, name=name, description=description, protect=protect\n )\n\n owners = [self._ldap.get_user_from_slack(user_id) for user_id in action.value[\"owners\"]]\n error = await self._ggroups.add_members(\n group=group, emails=[u.email for u in owners], role=\"OWNER\"\n )\n if error:\n msg = f\"Failed to add some owners to the new group {group.name}: \" + error\n print(msg)\n await self._client.chat_postMessage(channel=self._approvals_channel, text=msg)\n\n members = [self._ldap.get_user_from_slack(user_id) for user_id in action.value[\"members\"]]\n error = await self._ggroups.add_members(group=group, emails=[u.email for u in members])\n if error:\n msg = f\"Failed to add some members to the new group {group.name}: \" + error\n print(msg)\n await self._client.chat_postMessage(channel=self._approvals_channel, text=msg)\n\n await self._respond_to_approval(action, True)\n await self._remove_eyes(action)\n\n async def send_create_group_options(self, action: SlackAction) -> None:\n protected_checkbox = checkbox(\n \"ggroups_group_protect\", text(\"Protect this group (new members must request to join)\"),\n )\n\n blocks = [\n inputsection(\n text(\"Email Address\"),\n inputbox(\n \"ggroups_group_email\",\n \"plain_text_input\",\n text(f\"emea-daily-doggos@{self._domain}\"),\n ),\n hint=text(f\"What email address should it have? (Make sure it is @{self._domain})\"),\n ),\n section(text(\"Please note this will submit an approval request to admins.\")),\n inputsection(\n text(\"Name\"),\n inputbox(\"ggroups_group_name\", \"plain_text_input\", text(\"EMEA Daily Doggos\")),\n hint=text(\n \"What do you want to call this group? (It should be close to the email address)\"\n ),\n ),\n inputsection(\n text(\"Description\"),\n inputbox(\n \"ggroups_group_description\",\n \"plain_text_input\",\n text(f\"Good boys, daily (EMEA region)\"),\n ),\n hint=text(f\"What email address should it have? (Make sure it is @{self._domain})\"),\n ),\n inputsection(\n text(\"Options\"),\n checkboxes(\"ggroups_group_checkboxes\", [protected_checkbox]),\n optional=True,\n ),\n inputsection(\n text(\"Owners\"),\n inputbox(\n \"ggroups_group_owners\",\n \"multi_users_select\",\n text(\"@jdoe\"),\n initial_users=[action.user_id],\n max_selected_items=10,\n ),\n hint=text(\"Who can approve new members in this group?\"),\n ),\n inputsection(\n text(\"Members\"),\n inputbox(\n \"ggroups_group_members\",\n \"multi_users_select\",\n text(\"@jdoe\"),\n # I did some napkin math to work out how many slackIDs we could fit in\n # the 2000 characters for action data\n max_selected_items=100,\n ),\n hint=text(\n \"Who will initially be in this group?\"\n \"(You can add more later. Don't include owners)\"\n ),\n optional=True,\n ),\n ]\n\n return await self._client.views_open(\n trigger_id=action.trigger_id,\n view={\n \"type\": \"modal\",\n \"callback_id\": \"ggroups_create_group\",\n \"title\": text(\"Create a Group\"),\n \"submit\": text(\"Submit\"),\n \"close\": text(\"Cancel\"),\n \"blocks\": blocks,\n },\n )\n\n async def validate_create_group_request(self, action: SlackAction) -> Dict[str, str]:\n email = self.get_modal_value(action, \"ggroups_group_email\")\n members = self.get_modal_value(action, \"ggroups_group_members\")\n owners = self.get_modal_value(action, \"ggroups_group_owners\")\n\n # Valdiate the request. Only some things need to be checked, as Slack will make sure:\n # - Owners must be > 1, < 10\n # - Members must be < 100\n # - Name and email can't be empty\n # - All owners and members are valid slackIDs\n\n # Append domain if user didn't put it in\n if f\"@{self._domain}\" not in email:\n email += f\"@{self._domain}\"\n\n errors = {}\n if \"+\" in email:\n errors[\n action.value[\"ggroups_group_email\"][\"parent\"]\n ] = \"The email address cannot contain an alias part (+blah)\"\n return errors\n\n if self._domain != email.split(\"@\")[1]:\n errors[\n action.value[\"ggroups_group_email\"][\"parent\"]\n ] = f\"The email address must be @{self._domain}\"\n return errors\n\n match = self._regex_email.match(email)\n if not match:\n errors[\n action.value[\"ggroups_group_email\"][\"parent\"]\n ] = \"This email address is not valid\"\n return errors\n email = match.group(1)\n\n # Check if group name is taken\n if await self._ggroups.get_from_email(email):\n errors[\n action.value[\"ggroups_group_email\"][\"parent\"]\n ] = \"This email address is already taken\"\n\n for member in members:\n if member in owners:\n errors[\n action.value[\"ggroups_group_members\"][\"parent\"]\n ] = f\"Users cannot be an owner and a regular member\"\n\n for users, field in [(members, \"ggroups_group_members\"), (owners, \"ggroups_group_owners\")]:\n for user in users:\n if not self._ldap.get_user_from_slack(user):\n errors[action.value[field][\"parent\"]] = (\n f\"Cannot find user with Slack ID {user}.\"\n \" Please check the list, then contact an admin.\"\n )\n\n return errors\n\n async def send_create_group_request(self, action: SlackAction) -> None:\n name = self.get_modal_value(action, \"ggroups_group_name\")\n email = self.get_modal_value(action, \"ggroups_group_email\")\n description = self.get_modal_value(action, \"ggroups_group_description\")\n members = self.get_modal_value(action, \"ggroups_group_members\")\n owners = self.get_modal_value(action, \"ggroups_group_owners\")\n protect = self.get_modal_value(action, \"ggroups_group_protect\")\n request_id = uuid4().hex\n\n # Append domain if user didn't put it in\n if f\"@{self._domain}\" not in email:\n email += f\"@{self._domain}\"\n\n button_data = {\n \"request_id\": request_id,\n \"name\": name,\n \"email\": email,\n \"description\": description,\n \"members\": members,\n \"owners\": owners,\n \"protect\": protect,\n }\n\n group_owners = \"• \" + (\"\\n• \".join(f\"<@{owner}>\" for owner in owners) or \"None\")\n confirm_message = (\n lambda action: f\"Request to create group '{name}' ({email}) will be *{action}*\"\n )\n\n info = section(\n fields=[\n md(f\"*Name:*\\n{name}\"),\n md(f\"*Email:*\\n{email}\"),\n md(f\"*Members:*\\n{len(members + owners)}\"),\n md(f\"*Description:*\\n{description or 'None'}\"),\n md(f\"*Owners:*\\n{group_owners}\"),\n md(f\"*Protected:*\\n{protect}\"),\n ]\n )\n\n blocks = [\n section(md(f\"<@{action.user_id}> has requested to create a new group '{name}'.\")),\n info,\n actions(\n \"ggroups_approvals_choice\",\n button(\n \"ggroups_create_approve\",\n \"primary\",\n text(\"Approve\"),\n button_data,\n confirm(confirm_message(\"approved\")),\n ),\n button(\n \"ggroups_create_deny\",\n \"danger\",\n text(\"Deny\"),\n button_data,\n confirm(confirm_message(\"denied\")),\n ),\n ),\n ]\n\n blocks_result = [\n section(md(f\":email: Request sent! Here's the details:\")),\n info,\n ]\n\n slack_res: SlackResponse = await self._client.chat_postMessage(\n channel=self._approvals_channel,\n text=\"Please review this Google Group creation request\",\n blocks=blocks,\n as_user=True,\n )\n\n message = RequestMessage.from_slack(slack_res)\n creator = self._ldap.get_user_from_slack(action.user_id)\n\n await self._request.add_create_request(\n request_id=request_id,\n requester_email=creator.email,\n group_email=email,\n messages=[message],\n )\n\n await self._client.chat_postMessage(\n channel=action.user_id, text=\"Request sent!\", blocks=blocks_result, as_user=True,\n )\n\n async def send_manage_group_options(self, action: SlackAction) -> None:\n button_data = {\n \"requester\": action.user.aliases[\"slack\"],\n \"group_id\": action.group.group_id,\n }\n confirm_msg = \"and will have to request access to rejoin\" if action.group.protected else \"\"\n member = self._ggroups.find_member(action.group, action.user.email)\n is_owner = member and member.is_owner\n is_admin = action.user.is_admin\n\n blocks = [\n section(text(f\"Managing {action.group.name}\")),\n ]\n\n if member:\n blocks.append(\n section(\n md(\":wave: *Leave Group*\\nStop receiving mail from this group.\"),\n accessory=button(\n \"ggroups_user_leave\",\n \"danger\",\n text(\"Leave\"),\n button_data,\n confirm(f\"You will be removed from {action.group.name} {confirm_msg}\"),\n ),\n )\n )\n if member and not is_owner:\n blocks.append(\n section(\n md(\n \":briefcase: *Become an Owner*\\nAdd and remove members yourself,\"\n \" and manage requests to join this group.\"\n ),\n accessory=button(\n \"ggroups_user_become_owner\",\n \"primary\",\n text(\"Become an Owner\"),\n button_data,\n confirm(\n f\"This will request that you become an owner of {action.group.name}\"\n ),\n ),\n )\n )\n if is_owner or is_admin or not action.group.protected:\n blocks.append(\n section(\n md(\":incoming_envelope: *Add Members*\\nAdd people to this group.\"),\n accessory=button(\n \"ggroups_manage_add_members\", \"primary\", text(\"Add Members\"), button_data,\n ),\n )\n )\n if is_owner or is_admin:\n blocks.append(\n section(\n md(\":x: *Remove Members*\\nRemove people from this group.\"),\n accessory=button(\n \"ggroups_manage_remove_members\",\n \"danger\",\n text(\"Remove Members\"),\n button_data,\n ),\n )\n )\n\n return await self._client.views_open(\n trigger_id=action.trigger_id,\n view={\n \"type\": \"modal\",\n \"callback_id\": \"ggroups_manage_group\",\n \"title\": text(\"Manage group\"),\n \"close\": text(\"Close\"),\n \"blocks\": blocks,\n },\n )\n\n async def send_add_members_options(self, action: SlackAction) -> None:\n blocks = [\n section(\n text(\n \"Please note that the available users includes\"\n \" members and non members of the group.\"\n )\n ),\n inputsection(\n text(\"New Members\"),\n inputbox(\n \"ggroups_group_members\",\n \"multi_users_select\",\n text(\"@jdoe\"),\n # I did some napkin math to work out how many slackIDs we could fit in\n # the 2000 characters for action data\n max_selected_items=100,\n initial_users=action.value.get(\"targets\", []),\n ),\n hint=text(f\"List members you would like to add to this group\"),\n block_id=\"ggroups_members_input\",\n ),\n ]\n\n member = self._ggroups.find_member(action.group, action.user.email)\n if not action.user.is_admin and not (member and member.is_owner):\n blocks.append(\n inputsection(\n text(\"Reason\"),\n inputbox(\n \"ggroups_request_reason\", \"plain_text_input\", text(\"These people are cool\"),\n ),\n hint=text(\n \"Please provide a reason for your request,\"\n \" to help our admins action it sooner.\"\n ),\n )\n )\n\n view = {\n \"type\": \"modal\",\n \"callback_id\": \"ggroups_add_members\",\n \"title\": text(f\"Manage members\"),\n \"submit\": text(\"Submit\"),\n \"close\": text(\"Cancel\"),\n \"blocks\": blocks,\n \"private_metadata\": dumps(action.value),\n }\n\n if action.value.get(\"new_request\", False):\n return await self._client.views_open(trigger_id=action.trigger_id, view=view,)\n return await self._client.views_push(trigger_id=action.trigger_id, view=view,)\n\n async def send_remove_members_options(self, action: SlackAction) -> None:\n blocks = [\n section(\n text(\n \"Please note that the available users includes\"\n \" members and non members of the group.\"\n )\n ),\n inputsection(\n text(\"Members\"),\n inputbox(\n \"ggroups_group_members\",\n \"multi_users_select\",\n text(\"@jdoe\"),\n # I did some napkin math to work out how many slackIDs we could fit in\n # the 2000 characters for action data\n max_selected_items=100,\n ),\n hint=text(f\"List members you would like to remove from this group\"),\n block_id=\"ggroups_members_input\",\n ),\n ]\n\n return await self._client.views_push(\n trigger_id=action.trigger_id,\n view={\n \"type\": \"modal\",\n \"callback_id\": \"ggroups_remove_members\",\n \"title\": text(f\"Manage members\"),\n \"submit\": text(\"Submit\"),\n \"close\": text(\"Cancel\"),\n \"blocks\": blocks,\n \"private_metadata\": dumps(action.value),\n },\n )\n\n def validate_modal_members(self, action: SlackAction) -> Dict[str, str]:\n errors = {}\n targets = self.get_modal_value(action, \"ggroups_group_members\")\n\n # Valdiate the request. Only some things need to be checked, as Slack will make sure:\n # - Targets must be < 100\n # - Name and email can't be empty\n # - All owners and targets are valid slackIDs\n for target in targets:\n if not self._ldap.get_user_from_slack(target):\n errors[\"ggroups_members_input\"] = f\"Cannot find user with Slack ID {target}.\"\n\n return errors\n\n async def send_add_members_request(self, action: SlackAction) -> None:\n reason = self.get_modal_value(action, \"ggroups_request_reason\")\n slack_targets = self.get_modal_value(action, \"ggroups_group_members\")\n\n # Hax, because usually the value contains this info\n action.value = loads(action.private_metadata)\n action.value[\"targets\"] = slack_targets\n action.value[\"reason\"] = reason\n await self._try_load_data(action)\n\n try:\n result = await self._send_join_requests(action)\n except RuntimeError as error:\n print(\"Error adding user(s) to\", action.group.email, \":\", error)\n msg = f\"Error adding user(s) to group: {error}\"\n await self._client.chat_postMessage(\n channel=action.user_id, text=msg, as_user=True,\n )\n return\n\n msg = \":email: Request sent to add \"\n if result == MEMBERS_ADDED:\n msg = \":heavy_check_mark: You have added \"\n\n users = \", \".join(f\"<@{t}>\" for t in slack_targets[: min(len(slack_targets), 3)])\n remainder = len(slack_targets) - 3\n msg += (\n f\"{users} {f'and {remainder} others ' if remainder > 0 else ''}\"\n f\"to {action.group.name} ({action.group.email})!\"\n )\n\n await self._client.chat_postMessage(\n channel=action.user_id, text=msg, blocks=[section(md(msg))], as_user=True,\n )\n\n async def kick_members(self, action: SlackAction) -> None:\n slack_targets = self.get_modal_value(action, \"ggroups_group_members\")\n action.value = loads(action.private_metadata)\n await self._try_load_data(action)\n\n # Load the target emails\n targets = [self._ldap.get_user_from_slack(slack_id).email for slack_id in slack_targets]\n\n # Load the target members\n members = [self._ggroups.find_member(action.group, email) for email in targets]\n\n # Add the request now, incase any one of the remove requests fails fatally\n # We don't want to lose the trail on partial deletes\n request = await self._request.add_leave_request(\n request_id=action.request_id,\n requester_email=action.user.email,\n group_email=action.group.email,\n targets=targets,\n )\n\n users = \", \".join(f\"<@{t}>\" for t in slack_targets[: min(len(slack_targets), 3)])\n remainder = len(slack_targets) - 3\n msg = (\n f\"Removed {users} {f'and {remainder} others ' if remainder > 0 else ''}\"\n f\"from {action.group.name} ({action.group.email})!\"\n )\n\n for member in members:\n if member is None:\n continue\n\n try:\n await self._ggroups.remove_member(action.group, member)\n except Exception as error:\n msg = f\"Error removing member {member.email} from {action.group.email}: {error}\"\n print(msg)\n break\n\n await self._client.chat_postMessage(\n channel=action.user_id, text=msg, as_user=True,\n )\n\n requester_id = action.user.aliases[\"slack\"]\n await self._inform_targets(action, request, requester_id)\n","repo_name":"HubSpot/python-app-google-groups","sub_path":"app_google_groups/controllers/slackaction.py","file_name":"slackaction.py","file_ext":"py","file_size_in_byte":51954,"program_lang":"python","lang":"en","doc_type":"code","stars":4,"dataset":"github-code","pt":"17"} +{"seq_id":"35246378831","text":"import time\nfrom collections import deque\n\nclass Maze():\n \"\"\"A pathfinding problem.\"\"\"\n\n def __init__(self, grid, location, path=None):\n \"\"\"Instances differ by their current agent locations.\"\"\"\n self.grid = grid\n self.location = location\n self.path = path or []\n\n def display(self):\n \"\"\"Print the maze, marking the current agent location.\"\"\"\n for r in range(len(self.grid)):\n for c in range(len(self.grid[r])):\n if (r, c) == self.location:\n print('\\033[96m*\\x1b[0m', end=' ') # print a blue *\n else:\n print(self.grid[r][c], end=' ') # prints a space or wall\n print()\n print()\n\n def moves(self):\n \"\"\"Return a list of possible moves given the current agent location.\"\"\"\n # YOU FILL THIS IN\n possibleMoves = []\n position = self.location\n posx = self.location[0]\n posy = self.location[1]\n\n # Check North (x-1, y)\n if self.grid[posx - 1][posy] == \" \":\n possibleMoves += ['N']\n\n # Check South (x+1, y)\n if self.grid[posx + 1][posy] == \" \":\n possibleMoves += ['S']\n\n # Check East (x, y+1)\n if self.grid[posx][posy+1] == \" \":\n possibleMoves += ['E']\n\n # Check West (x, y-1)\n if self.grid[posx][posy-1] == \" \":\n possibleMoves += ['W']\n\n return possibleMoves\n\n\n def neighbor(self, move):\n \"\"\"Return another Maze instance with a move made.\"\"\"\n # YOU FILL THIS IN\n position = self.location\n posx = self.location[0]\n posy = self.location[1]\n if (move == 'N'):\n return Maze(self.grid, (posx - 1, posy), self.path + [move])\n elif (move == 'S'):\n return Maze(self.grid, (posx + 1, posy), self.path + [move])\n elif (move == 'E'):\n return Maze(self.grid, (posx, posy+1), self.path + [move])\n elif (move == 'W'):\n return Maze(self.grid, (posx, posy-1), self.path + [move])\n\nclass Agent():\n \"\"\"Knows how to find the exit to a maze with BFS.\"\"\"\n\n def bfs(self, maze, goal):\n \"\"\"Return an ordered list of moves to get the maze to match the goal.\"\"\"\n # YOU FILL THIS IN\n print(\"start\")\n q = deque()\n closedList = []\n q.append(maze)\n\n\n\n while q: # Will be False if q is empty\n #pop next state\n state = q.popleft()\n\n #check if goal\n if state.location == goal.location:\n # return path to goal\n return state.path\n\n #else generate list of moves and add child states to queue\n else:\n closedList += [state.location]\n moves = state.moves()\n for move in moves:\n temp = state.neighbor(move)\n if temp.location not in closedList:\n q.append(temp)\n\n\n\n\ndef main():\n \"\"\"Create a maze, solve it with BFS, and console-animate.\"\"\"\n\n grid = [\"XXXXXXXXXXXXXXXXXXXX\",\n \"X X X X\",\n \"X XXXXX XXXX XXX XXX\",\n \"X X X X X\",\n \"X X XXX XXXXXX X X X\",\n \"X X X X X X\",\n \"X XXX XXXXXX XXXXX X\",\n \"X XXX X X X X\",\n \"X XXX XXXXX\",\n \"XXXXX XXXXXX X\",\n \"X XXX X X X X X\",\n \"XXX XXX X X XXXX X X\",\n \"X X X XX X X X\",\n \"XXXXX XXXX X XXX\",\n \"X X XXX X X\",\n \"X XXXXX X XXXX XXX X\",\n \"X X X X X X\",\n \"X X XXXXXX X XXXXX X\",\n \"X X X\",\n \"XXXXXXXXXXXXXXXXXX X\"]\n\n maze = Maze(grid, (1, 1))\n maze.display()\n\n agent = Agent()\n goal = Maze(grid, (19, 18))\n path = agent.bfs(maze, goal)\n\n while path:\n move = path.pop(0)\n maze = maze.neighbor(move)\n time.sleep(0.50)\n maze.display()\n\n\nif __name__ == '__main__':\n main()","repo_name":"AMSearer/bfs-maze-search","sub_path":"bfs_maze.py","file_name":"bfs_maze.py","file_ext":"py","file_size_in_byte":4090,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"17"} +{"seq_id":"21274061536","text":"import sqlite3\r\nimport datetime\r\nimport re\r\n\r\nfrom datetime import datetime\r\nfrom sqlite3 import Error\r\nfrom config.globals import DBPATH\r\n\r\nclass IMC:\r\n\r\n def calcularIMC(self, usuario):\r\n regex = '[^0-9]|[-]' \r\n self.usuario_id = usuario.usuario_id\r\n altura = input(\"Ingresar peso: \")\r\n peso = input(\"Ingresar altura: \")\r\n if (re.search(regex, altura) or re.search(regex, peso)):\r\n return False\r\n \r\n self.peso = float(peso)\r\n self.altura = float(altura)\r\n self.imc = self.peso / (self.altura * self.altura)\r\n self.estado = self.mostrarEstadoNutricional(self, usuario.genero)\r\n self.fecha = datetime.today().strftime('%Y-%m-%d')\r\n con = sqlite3.connect(DBPATH)\r\n flag = True\r\n try:\r\n cursorObj = con.cursor()\r\n entities = (self.usuario_id,\r\n self.peso,\r\n self.altura,\r\n self.imc,\r\n self.estado,\r\n self.fecha)\r\n cursorObj.execute(\"\"\"INSERT INTO imc(\r\n usuario_id,\r\n peso,\r\n altura,\r\n imc,\r\n estado,\r\n fecha)\r\n VALUES(?, ?, ?, ?, ?, ?)\"\"\", entities)\r\n con.commit()\r\n \r\n except Error:\r\n flag = False\r\n print(Error)\r\n finally:\r\n con.close()\r\n return flag\r\n \r\n def mostrarEstadoNutricional(self, genero):\r\n if genero == 1:\r\n self.estado = tabla_masculino(self.imc)\r\n elif genero == 2:\r\n self.estado = tabla_femenino(self.imc)\r\n else:\r\n self.estado = \"N/A\"\r\n print(\"Estado nutricional: \" + self.estado)\r\n print(\" \")\r\n return self.estado\r\n\r\n def mostrarListadoDeRegistros(self, usuario):\r\n con = sqlite3.connect(DBPATH)\r\n try:\r\n cursorObj = con.cursor()\r\n query_select = \"SELECT * FROM imc WHERE usuario_id = \" + str(usuario.usuario_id)\r\n cursorObj.execute(query_select)\r\n rows = cursorObj.fetchall()\r\n if (len(rows) > 0):\r\n print(\"Registros de salud: \")\r\n for row in rows:\r\n print(\"Fecha: \" + row[6])\r\n print(\"Peso: \" + str(row[2]))\r\n print(\"Altura: \" + str(row[3]))\r\n print( \"Estado: \" + row[5]) \r\n print(\"IMC: \" + str(row[4])) \r\n print(\"-------\") \r\n except Error:\r\n print(Error)\r\n finally:\r\n con.close()\r\n return usuario\r\n\r\ndef tabla_masculino(imc_valor):\r\n if imc_valor < 20:\r\n return bcolors.Yellow + \"BAJO PESO\" + bcolors.ENDC\r\n elif imc_valor >= 20 and imc_valor < 24.9:\r\n return bcolors.Green + \"NORMAL\" + bcolors.ENDC\r\n elif imc_valor >= 25 and imc_valor < 29.9:\r\n return bcolors.Orange + \"OBESIDAD LEVE\" + bcolors.ENDC\r\n elif imc_valor >= 30 and imc_valor < 40:\r\n return bcolors.Red + \"OBESIDAD SEVERA\" + bcolors.ENDC\r\n elif imc_valor >= 40:\r\n return bcolors.Red + \"OBESIDAD MUY SEVERA\" + bcolors.ENDC\r\n\r\ndef tabla_femenino(imc_valor):\r\n if imc_valor < 20:\r\n return bcolors.Yellow + \"BAJO PESO\" + bcolors.ENDC\r\n elif imc_valor >= 20 and imc_valor < 23.9:\r\n return bcolors.Green + \"NORMAL\" + bcolors.ENDC\r\n elif imc_valor >= 24 and imc_valor < 28.9:\r\n return bcolors.Orange + \"OBESIDAD LEVE\" + bcolors.ENDC\r\n elif imc_valor >= 29 and imc_valor < 37:\r\n return bcolors.Red + \"OBESIDAD SEVERA\" + bcolors.ENDC\r\n elif imc_valor >= 37:\r\n return bcolors.Red + \"OBESIDAD MUY SEVERA\" + bcolors.ENDC\r\n\r\nclass bcolors:\r\n Red = '\\033[91m'\r\n Green = '\\033[92m'\r\n Yellow = '\\033[93m'\r\n Orange = '\\033[33m'\r\n ENDC = '\\033[0m'","repo_name":"atariki-haoa/testing_taller_1","sub_path":"model/imc.py","file_name":"imc.py","file_ext":"py","file_size_in_byte":4144,"program_lang":"python","lang":"es","doc_type":"code","stars":0,"dataset":"github-code","pt":"17"} +{"seq_id":"24060979541","text":"def topKFrequent(): # leetcode 347\n mem = {}\n for i in nums:\n # dictionary set if does not exist\n mem[i] = 1 + mem.setdefault(i, 0)\n #returning all list inside mem \n return [sorted(mem.items(), key = lambda x:-x[1])[i][0] for i in range(0, k)]\n\nnums = [2,3,4,1,4,0,4,-1,-2,-1]\nk = 2\np = topKFrequent(nums, k)\nprint('dictionary')\n\ndef ifelse():\n # 1 line if else\n age_group = \"Minor\" if age < 18 else \"Adult\"\n # regular \n age = 20 \n if age < 18:\n age_group = \"Minor\"\n else:\n age_group = \"Adult\"","repo_name":"locbgiang/leetcodeproblems","sub_path":"methods.py","file_name":"methods.py","file_ext":"py","file_size_in_byte":555,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"17"} +{"seq_id":"8123805548","text":"from django.contrib.auth.models import User\r\nfrom django import forms\r\nfrom dirsysapp.models import *\r\nfrom django.contrib.auth.forms import UserCreationForm\r\n\r\nclass RegisterForm(forms.Form):\r\n PROGRAM_TYPE_CHOICES = [\r\n ('Program',\r\n (\r\n ('BSN', 'Nursing Program'),\r\n ('BSHM', 'Hospitality Management Program'),\r\n ('BSTM', 'Tourism Management Program'),\r\n ('BSA', 'Accountancy Program'),\r\n ('AB', 'Liberal Arts Program'),\r\n ('BS CRIM.', 'Criminology Program'),\r\n ('BSBA', 'Business Administration Program'),\r\n ('BSCE', 'Civil Engineering Program'),\r\n ('BEED', 'Elementary Education Program'),\r\n ('BSED', 'Secondary Education Program'),\r\n ('BSCS', 'Computer Science Program'),\r\n ('J.D.', 'Juris Doctor Program'),\r\n )\r\n ),\r\n ]\r\n USER_TYPE_CHOICES= [\r\n ('User Type', \r\n (\r\n ('Admin', 'Admin'),\r\n ('Faculty', 'Faculty'),\r\n ('Student', 'Student'),\r\n )\r\n ),\r\n ]\r\n YEAR_LEVEL_CHOICES= [\r\n ('Year Level', \r\n (\r\n ('First Year', 'First Year'),\r\n ('Second Year', 'Second Year'),\r\n ('Third Year', 'Third Year'),\r\n ('Fourth Year', 'Fourth Year'),\r\n )\r\n ),\r\n ]\r\n user_type = forms.ChoiceField(choices=USER_TYPE_CHOICES, required=True)\r\n program = forms.ChoiceField(choices=PROGRAM_TYPE_CHOICES, required=True)\r\n id_number = forms.CharField(required=False)\r\n first_name = forms.CharField(required=True)\r\n middle_name = forms.CharField(required=False)\r\n last_name = forms.CharField(required=True)\r\n suffix_name = forms.CharField(required=False)\r\n address = forms.CharField(required=True)","repo_name":"Yani22/DIRECTORY","sub_path":"registerapp/forms.py","file_name":"forms.py","file_ext":"py","file_size_in_byte":1908,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"17"} +{"seq_id":"25660230278","text":"import math\nimport logging\n\nfrom maya.api import OpenMaya\nfrom maya import cmds\n\n\nLOG = logging.getLogger(__name__)\n\n\ndef getAllChild(node):\n dagNode = OpenMaya.MFnDagNode(node)\n\n children = []\n\n for childIndex in range(dagNode.childCount()):\n child = dagNode.child(childIndex) \n if not child.hasFn(OpenMaya.MFn.kJoint):\n continue\n children.append(child)\n\n result = []\n\n if children:\n for child in children:\n result.append(child)\n result.extend(getAllChild(child))\n\n return result\n\n\ndef getChildren(node):\n result = []\n\n dagNode = OpenMaya.MFnDagNode(node)\n\n for index in range(dagNode.childCount()):\n child = dagNode.child(index)\n if child.hasFn(OpenMaya.MFn.kJoint):\n result.append(child)\n\n return result\n\n\ndef packRotation(node, preserveChildren):\n wm, r, ra, jo = getMatrices(node)\n setRotationMatrices(node, jo, preserveChildren)\n\n\ndef getMatrices(node):\n nodeName = OpenMaya.MFnDagNode(node).getPath()\n\n r = cmds.getAttr('{0}.r'.format(nodeName))\n r = [math.radians(x) for x in r[0]]\n ra = cmds.getAttr('{0}.ra'.format(nodeName))\n ra = [math.radians(x) for x in ra[0]]\n jo = cmds.getAttr('{0}.jo'.format(nodeName))\n jo = [math.radians(x) for x in jo[0]]\n\n wm = OpenMaya.MMatrix(cmds.getAttr('{0}.wm'.format(nodeName)))\n pm = OpenMaya.MMatrix(cmds.getAttr('{0}.pm'.format(nodeName)))\n\n r = OpenMaya.MEulerRotation(*r).asMatrix() * pm\n ra = OpenMaya.MEulerRotation(*ra).asMatrix() * pm\n jo = OpenMaya.MEulerRotation(*jo).asMatrix() * pm\n\n return wm, r, ra, jo\n\n\ndef setRotationMatrices(node, orientMatrix, preserveChildren=True):\n if preserveChildren:\n children = getChildren(node)\n matrices = [getMatrices(j) for j in children]\n\n wm, r, ra, jo = getMatrices(node)\n r = OpenMaya.MMatrix()\n ra = orientMatrix * r.inverse() * jo.inverse()\n setMatrices(node, wm, r, ra, jo)\n\n if preserveChildren:\n for child, childm in zip(children, matrices):\n setMatrices(child, *childm)\n\n\ndef setMatrices(node, worldMatrix, rotationMatrix, rotateAxisMatrix, orientMatrix, translate=True, rotate=True):\n nodeName = OpenMaya.MFnDagNode(node).fullPathName()\n\n pim = OpenMaya.MMatrix(cmds.getAttr('{0}.pim'.format(nodeName)))\n\n matrix = worldMatrix * pim\n \n if rotate:\n wm, r, ra, jo = getMatrices(node)\n\n rEuler = OpenMaya.MTransformationMatrix(rotationMatrix).rotation()\n rEuler = [math.degrees(rEuler.x), math.degrees(rEuler.y), math.degrees(rEuler.z)]\n LOG.info(rEuler)\n\n raEuler = OpenMaya.MTransformationMatrix(rotateAxisMatrix).rotation()\n raEuler = [math.degrees(raEuler.x), math.degrees(raEuler.y), math.degrees(raEuler.z)]\n LOG.info(raEuler)\n\n joEuler = OpenMaya.MTransformationMatrix(orientMatrix * pim * r * pim).rotation()\n joEuler = [math.degrees(joEuler.x), math.degrees(joEuler.y), math.degrees(joEuler.z)]\n LOG.info(joEuler)\n\n cmds.setAttr(nodeName + '.r', *rEuler)\n cmds.setAttr(nodeName + '.ra', *raEuler)\n cmds.setAttr(nodeName + '.jo', *joEuler)\n \n if translate:\n t = [matrix.getElement(3, 0), matrix.getElement(3, 1), matrix.getElement(3, 2)]\n cmds.setAttr(nodeName + '.t', *t)","repo_name":"ricksilliker/dragonfly","sub_path":"src/dragonfly/joints.py","file_name":"joints.py","file_ext":"py","file_size_in_byte":3319,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"17"} +{"seq_id":"38960523700","text":"def reverse_str(string):\n r = ''\n for i in range(len(string)):\n if string[i] == '(':\n r += ')'\n else:\n r += '('\n return r\n\n\ndef proper(string):\n left, right = 0, 0\n for i in range(len(string)):\n if string[i] == '(':\n left += 1\n else:\n right += 1\n\n if left < right:\n return False\n\n return True\n\n\ndef divide(string):\n left, right = 0, 0\n u, v = '', ''\n for i in range(len(string)):\n if string[i] == '(':\n left += 1\n else:\n right += 1\n if left == right:\n u = string[:i + 1]\n v = string[i + 1:]\n break\n\n return u, v\n\n\ndef solution(p):\n if len(p) == 0 or p == '':\n return p\n\n u, v = divide(p)\n if proper(u):\n return u + solution(v)\n else:\n reverse = reverse_str(u[1:-1])\n return '(' + solution(v) + ')' + reverse\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n####################################################################################\na = solution(\"(()())()\")\nprint(a, a == \"(()())()\")\nb = solution(\")(\")\nprint(b, b == \"()\")\nc = solution(\"()))((()\")\nprint(c, c == \"()(())()\")\n","repo_name":"kobeomseok95/codingTest","sub_path":"programmers/level2/60058_4.py","file_name":"60058_4.py","file_ext":"py","file_size_in_byte":1193,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"17"} +{"seq_id":"37152380928","text":"import queue\nEDGE_DISTANCE = 6\n\ndef bfs(graph, dist, S):\n q = queue.Queue()\n dist[S] = 0\n q.put(S)\n\n while not q.empty():\n start = q.get()\n for v in graph[start]:\n if(dist[v] == -1): #if dist = -1 means this vertice has not visted yet\n dist[v] = dist[start] + EDGE_DISTANCE\n q.put(v)\n \n\ndef main():\n # step 1: init number of test case\n test_case = int(input())\n for _ in range(test_case):\n # step 2: init number of node and edges and graphs\n N, M = map(int, input().strip().split())\n graphList = [[] for _ in range(N)] \n \n # Read the edges of the graph by descresing each with one as the node count from 1\n for _ in range(M):\n u, v = map(int, input().strip().split())\n graphList[u-1].append(v-1)\n graphList[v-1].append(u-1)\n # input start vertice\n S = int(input())-1\n \n # init distance array with -1 \n dist = [-1]*N\n\n #perform BFS to update distance array\n bfs(graphList, dist, S)\n # print distance\n for i in range(N):\n if i != S:\n print(dist[i], end=\" \")\n print()\n\n\nif __name__ == \"__main__\":\n main()","repo_name":"nhlong20/blueBigO-Solutions","sub_path":"5. BFS/BFS_shortest_reach.py","file_name":"BFS_shortest_reach.py","file_ext":"py","file_size_in_byte":1114,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"17"} +{"seq_id":"4936647814","text":"import unittest\nfrom Expenses import Expenses\nfrom contextlib import contextmanager\nfrom StringIO import StringIO\nimport sys\n\n@contextmanager\ndef captured_output():\n new_out, new_err = StringIO(), StringIO()\n old_out, old_err = sys.stdout, sys.stderr\n try:\n sys.stdout, sys.stderr = new_out, new_err\n yield sys.stdout, sys.stderr\n finally:\n sys.stdout, sys.stderr = old_out, old_err\n\nclass ExpensesTest(unittest.TestCase):\n\n def test_equal_print_expenses(self):\n exp = Expenses()\n exp.concepts = [\"food\",\"transportation\",\"gym\"]\n exp.quantities = [\"10\",\"15\",\"15\"]\n with captured_output() as (out, err):\n exp.print_expenses(exp.concepts)\n output = out.getvalue().strip()\n self.assertEqual(output, \"10 food\\n15 transportation\\n15 gym\")\n\n def test_not_equal_print_expenses(self):\n exp = Expenses()\n exp.concepts = [\"food\",\"transportation\",\"gym\"]\n exp.quantities = [\"10\",\"15\",\"15\"]\n with captured_output() as (out, err):\n exp.print_expenses(exp.concepts)\n output = out.getvalue().strip()\n self.assertNotEqual(output, \"10 food\\n15 transportation\\n20 gym\")\n\n def test_equal_print_total(self):\n exp = Expenses()\n operation = \"Added\"\n quantity = \"4\"\n activity = \"gym\"\n total = \"45\"\n with captured_output() as (out, err):\n exp.print_total(operation, quantity, activity, total)\n output = out.getvalue().strip()\n self.assertEqual(output, \"4 pesos Added to gym - Total: 45 pesos\")\n\n def test_not_equal_print_total(self):\n exp = Expenses()\n operation = \"Added\"\n quantity = \"4\"\n activity = \"gym\"\n total = \"45\"\n with captured_output() as (out, err):\n exp.print_total(operation, quantity, activity, total)\n output = out.getvalue().strip()\n self.assertNotEqual(output, \"4 pesos Added to gym - Total: 46 pesos\")\n\n def test_wrong_option_process_input(self):\n exp = Expenses()\n user_input = \"Hi\"\n with captured_output() as (out, err):\n exp.process_input(user_input)\n output = out.getvalue().strip()\n self.assertEqual(output, \"Not an option\")\n\n def test_wrong_concept_add_expense(self):\n exp = Expenses()\n quantity = '6'\n concept = \"g\"\n with captured_output() as (out, err):\n exp.add_expense(quantity, concept)\n output = out.getvalue().strip()\n self.assertEqual(output, \"The concept is incorrect\")\n\n def test_not_digit_add_expense(self):\n exp = Expenses()\n quantity = 'r'\n concept = \"gym\"\n with captured_output() as (out, err):\n exp.add_expense(quantity, concept)\n output = out.getvalue().strip()\n self.assertEqual(output, \"The 2nd parameter has to be a number\")\n\n def test_read_file(self):\n exp = Expenses()\n exp.path_file = \"test.txt\"\n exp.read_expenses_file()\n self.assertNotEqual(len(exp.concepts),0)\n\n def test_empty_read_file(self):\n exp = Expenses()\n exp.path_file = \"test_empty.txt\"\n exp.read_expenses_file()\n with captured_output() as (out, err):\n exp.read_expenses_file()\n output = out.getvalue().strip()\n self.assertEqual(len(exp.concepts), 0)\n self.assertEqual(output, \"The file is empty\")\n\nif __name__ == '__main__':\n unittest.main()","repo_name":"patricianeira/Expenses_exercise","sub_path":"ExpensesTest.py","file_name":"ExpensesTest.py","file_ext":"py","file_size_in_byte":3467,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"17"} +{"seq_id":"6414313321","text":"import mysql.connector\n\n\nclass ConexaoBancoDados:\n\n def conexao_aberta(self):\n try:\n conexao = mysql.connector.connect(user = \"root\", password = \"\", host = \"localhost\", database = \"BD_ESCOLA\")\n cursor = conexao.cursor()\n self.conexao = conexao\n self.cursor = cursor\n print(\"_\"*80)\n print(\"Conexão aberta.\")\n\n except:\n print(\"_\"*80)\n print(\"Erro ao conectar com o banco de dados\")\n\n\n def conexao_fechada(self):\n try:\n if self.conexao.is_connected():\n self.conexao.close()\n print(\"_\"*80)\n print(\"Conexão fechada.\")\n\n except:\n print(\"_\"*80)\n print(\"Erro ao tentar fechar a conexão.\")\n \n\n\"\"\"conectar = ConexaoBancoDados()\nconectar.conexao_aberta()\nconectar.conexao_fechada()\"\"\"\n","repo_name":"JSilverio1997/Python_Cadastro_Aluno","sub_path":"Conexao_Banco_Dados.py","file_name":"Conexao_Banco_Dados.py","file_ext":"py","file_size_in_byte":881,"program_lang":"python","lang":"pt","doc_type":"code","stars":0,"dataset":"github-code","pt":"17"} +{"seq_id":"2390769791","text":"import numpy as np\nfrom plyfile import PlyData\n\n\ndef project_vertices(vertices, pose, cam):\n vertices = np.concatenate(\n (vertices, np.ones((vertices.shape[0], 1))), axis=1)\n projected = np.matmul(np.matmul(cam, pose), vertices.T)\n projected /= projected[2, :]\n projected = projected[:2, :].T\n return projected\n\n\ndef get_2d_corners(xy):\n x_min = np.min(xy[:, 0])\n x_max = np.max(xy[:, 0])\n y_min = np.min(xy[:, 1])\n y_max = np.max(xy[:, 1])\n return x_min, y_min, x_max, y_max\n\n\ndef corner2center(x1, y1, x2, y2):\n xc = (x1 + x2) / 2\n yc = (y1 + y2) / 2\n w = x2 - x1\n h = y2 - y1\n return xc, yc, w, h\n\n\ndef load_ply(path):\n with open(path, 'rb') as f:\n content = PlyData.read(f)\n xyz = np.vstack([content['vertex']['x'],\n content['vertex']['y'],\n content['vertex']['z']]).T\n return xyz\n\n\ndef align_model(xyz, transform_mat):\n xyzw = np.concatenate((xyz, np.ones((xyz.shape[0], 1))), axis=1)\n xyzw = np.matmul(transform_mat, xyzw.T)\n xyzw /= xyzw.T[:, 3]\n xyz = xyzw.T[:, :3]\n return xyz","repo_name":"ecr23xx/kp6d","sub_path":"data/ycb/utils.py","file_name":"utils.py","file_ext":"py","file_size_in_byte":1108,"program_lang":"python","lang":"en","doc_type":"code","stars":4,"dataset":"github-code","pt":"15"} +{"seq_id":"12038871929","text":"import folium\nimport pandas\nimport json\n\ndata = pandas.read_csv(\"Volcanoes_USA.txt\")\nlat = list(data[\"LAT\"])\nlon = list(data[\"LON\"])\nstat = list(data[\"STATUS\"])\nelev = list(data[\"ELEV\"])\nvType = list(data[\"TYPE\"])\n\ndef color_producer(elevation):\n if elevation < 1000:\n return 'green'\n elif 1000 <= elevation < 3000:\n return 'orange'\n else:\n return 'red'\n\nmap = folium.Map(zoom_start=6, tiles=\"Mapbox Bright\")\nfg = folium.FeatureGroup(name=\"Markers\")\nfg1 = folium.FeatureGroup(name=\"Population\")\n\n\nfor lt, ln, st, el, vt in zip(lat, lon, stat, elev, vType):\n fg.add_child(folium.CircleMarker(location = [lt, ln],\n popup=\"Status: {} | Elevation: {} | Type: {}\".format(st, el, vt), fill_color=color_producer(el),\n fill=True, color='#D3D3D3', fill_opacity=1))\n\nwith open(\"world.json\", 'r', encoding='utf-8-sig') as f:\n\tfg1.add_child(folium.GeoJson(data=json.load(f),\t\n\tstyle_function=lambda x: {'fillColor':'green' if x['properties']['POP2005'] < 10000000\n\telse 'orange' if 10000000 <= x['properties']['POP2005'] < 20000000 else 'red'}))\n\nmap.add_child(fg)\nmap.add_child(fg1)\nmap.add_child(folium.LayerControl())\n\nmap.save(\"Map1.html\")\n","repo_name":"nicholasvb89/geo_map","sub_path":"map1.py","file_name":"map1.py","file_ext":"py","file_size_in_byte":1171,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"15"} +{"seq_id":"15544506831","text":"# Imporatations\nfrom .base import SSDPRequete\nfrom .exceptions import SSDPErreur\n\nfrom base.decorateurs import verif_type\nfrom base.objets import FStr\nfrom helper import Helper\n\nfrom datetime import timedelta, datetime\nimport re\n\n# Variables\nhelper = Helper()\n\n# Fonction\ndef get_uuid(reg):\n if reg.groupdict().get(\"uuid\") != None:\n return reg.groupdict().get(\"uuid\").split('::')[0]\n else:\n return reg.groupdict().get(\"uuid\")\n\n# Classes\nclass SSDPNotify(SSDPRequete):\n '''\n Représente une requête d'avertissement (notify)\n '''\n \n # Attributs\n _default = {\n \"methode\": \"NOTIFY\",\n \"host\": \"239.255.255.250:1900\",\n }\n \n # Regex\n _re_nt_uuid = re.compile(r\"^uuid:(?P.+)$\", re.IGNORECASE)\n _re_nt_urn = re.compile(r\"^urn:(?P.+):(?P(device)|(service)):(?P.+):(?P[0-9]+)$\", re.IGNORECASE)\n \n _re_usn = re.compile(r\"^uuid:(?P.+?)(::upnp:rootdevice)?$\", re.IGNORECASE)\n _re_usn_urn = re.compile(r\"^uuid:(?P.+?)::urn:(?P[^:]+):(?P(device)|(service)):(?P.+):(?P[0-9]+)$\", re.IGNORECASE)\n \n _re_cachecontrol = re.compile(r\"^max-age ?= ?(?P[0-9]+)\", re.IGNORECASE)\n \n # Méthodes spéciales\n @verif_type(requete=(bytes, type(None)), ip_client=(tuple, type(None)), donnees=(dict, type(None)))\n def __init__(self, requete=None, ip_client=None, date=None, donnees=None):\n super(SSDPNotify, self).__init__(requete, ip_client, date, donnees)\n \n if donnees:\n pass\n \n elif hasattr(self, \"methode\"):\n if self.methode == \"NOTIFY\":\n self._analyse_notify()\n \n else:\n raise SSDPErreur(\"Ceci n'est pas une requête NOTIFY\", self.message)\n \n def __repr__(self):\n try:\n return \"\".format(self.adresseClient, self.dateReception, self.nts)\n \n except AttributeError:\n return \"\".format(self.nt)\n \n # Méthodes privées\n def _analyse_notify(self):\n # Vérification de la présence de NT, NTS & USN\n nts = self.headers.get(\"NTS\")\n nt = self.headers.get(\"NT\")\n usn = self.headers.get(\"USN\")\n \n if not nts or not nt or not usn:\n raise ValueError(\"Requête invalide ! Le(s) header(s) {} est/sont nécessaires !\".format(\n ((\"nts, \" if not nts else \"\") + (\"nt, \" if not nt else \"\") + (\"usn, \" if not usn else \"\"))[:-2]),\n )\n \n self.nt = nt\n self.usn = usn\n self.nts = nts\n \n if nts == \"ssdp:alive\":\n # Vérification de la présence de CACHE-CONTROL, SERVER & LOCATION\n cc = self.headers.get(\"CACHE-CONTROL\")\n srv = self.headers.get(\"SERVER\")\n loc = self.headers.get(\"LOCATION\")\n \n if not cc or not srv or not loc:\n raise ValueError(\"Requête invalide ! Le(s) header(s) {} est/sont nécessaires !\".format(\n ((\"cc, \" if not cc else \"\") + (\"srv, \" if not srv else \"\") + (\"loc, \" if not loc else \"\"))[:-2]),\n )\n \n self.cache_control = cc\n self.location = loc\n self.server = srv\n \n elif nts == \"ssdp:byebye\":\n pass\n \n # Méthodes de classe\n @classmethod\n @verif_type(location=str, nts=str, uuid=str, type=(str, type(None)), maxage=int, rootdevice=bool, nt_uuid=bool, nom_domaine=str, service=bool, version=str)\n def generer(cls, location, nts, uuid, type=None, maxage=helper.NOTIFY_MAX_AGE, rootdevice=False, nt_uuid=False, nom_domaine=\"schemas-upnp-org\", service=False, version=\"1\"):\n if rootdevice:\n nt = \"upnp:rootdevice\"\n \n elif nt_uuid:\n nt = \"uuid:{}\".format(uuid)\n \n else:\n if not type:\n raise ValueError(\"Argument type nécessaire\")\n \n nt = \"urn:{}:{}:{}:{}\".format(nom_domaine, \"service\" if service else \"device\", type, version)\n \n if nts not in (\"ssdp:alive\", \"ssdp:byebye\"):\n raise ValueError(\"L'argument nts doit valoir soit 'ssdp:alive', soit 'ssdp:byebye'\")\n \n donnees = {\n \"nt\": nt,\n \"nts\": nts,\n \"usn\": nt if nt_uuid else \"uuid:{}::{}\".format(uuid, nt),\n }\n \n if nts == \"ssdp:alive\":\n donnees[\"cache_control\"] = \"max-age = {:d}\".format(maxage)\n donnees[\"location\"] = location\n \n return cls(donnees=donnees)\n \n # Propriétés\n # Headers\n @property\n def nts(self):\n return self._nts\n \n @nts.setter\n @verif_type(nts=str)\n def nts(self, nts):\n if nts not in (\"ssdp:alive\", \"ssdp:byebye\"):\n raise ValueError(\"Mauvaise valeur de NTS\")\n \n self._nts = nts\n self.headers[\"NTS\"] = nts\n \n @property\n def nt(self):\n return self._nt\n \n @nt.setter\n @verif_type(nt=str)\n def nt(self, nt):\n nt_uuid = self._re_nt_uuid.match(nt)\n nt_urn = self._re_nt_urn.match(nt)\n \n self._rootdevice = False\n self._nt_uuid = False\n self._nt_urn = False\n if nt == \"upnp:rootdevice\":\n self._rootdevice = True\n \n elif nt_urn:\n if self.uuid:\n if self.uuid != get_uuid(nt_urn):\n raise ValueError(\"Valeurs de NT et de USN incohérentes : UUID différents\")\n \n else:\n self._uuid = get_uuid(nt_urn)\n \n if self.nom_domaine:\n if self.nom_domaine != nt_urn.groupdict().get(\"nom_domaine\"):\n raise ValueError(\"Valeurs de NT et de USN incohérentes : Nom de Domaine différents\")\n else:\n self._nom_domaine = nt_urn.groupdict().get(\"nom_domaine\")\n \n if self.objet:\n if self.objet != nt_urn.groupdict().get(\"objet\"):\n raise ValueError(\"Valeurs de NT et de USN incohérentes : Objets différents\")\n else:\n self._objet = nt_urn.groupdict().get(\"objet\")\n \n if self.type:\n if self.type != nt_urn.groupdict().get(\"type\"):\n raise ValueError(\"Valeurs de NT et de USN incohérentes : Types différents\")\n else:\n self._type = nt_urn.groupdict().get(\"type\")\n \n if self.version:\n if self.version != nt_urn.groupdict().get(\"version\"):\n raise ValueError(\"Valeurs de NT et de USN incohérentes : Versions différents\")\n else:\n self._version = nt_urn.groupdict().get(\"version\")\n \n elif nt_uuid:\n if self.uuid:\n if self.uuid != get_uuid(nt_uuid):\n raise ValueError(\"Valeurs de NT et de USN incohérentes : UUID différents\")\n \n else:\n self._uuid = get_uuid(nt_uuid)\n \n if self.rootdevice != (\"upnp:rootdevice\" in nt):\n raise ValueError(\"Valeurs de NT et de USN incohérentes\")\n \n else:\n raise ValueError(\"Mauvaise valeur de NT \" + nt)\n \n self._nt = nt\n self.headers[\"NT\"] = nt\n \n @property\n def usn(self):\n return self._usn\n \n @usn.setter\n @verif_type(usn=str)\n def usn(self, usn):\n re_usn = self._re_usn.match(usn)\n usn_urn = self._re_usn_urn.match(usn)\n \n if usn_urn:\n if self.uuid:\n if self.uuid != get_uuid(usn_urn):\n raise ValueError(\"Valeurs de NT et de USN incohérentes : UUID différents\")\n \n else:\n self._uuid = get_uuid(usn_urn)\n \n if self.nom_domaine:\n if self.nom_domaine != usn_urn.groupdict().get(\"nom_domaine\"):\n raise ValueError(\"Valeurs de NT et de USN incohérentes : Nom de Domaine différents\")\n else:\n self._nom_domaine = usn_urn.groupdict().get(\"nom_domaine\")\n \n if self.objet:\n if self.objet != usn_urn.groupdict().get(\"objet\"):\n raise ValueError(\"Valeurs de NT et de USN incohérentes : Objets différents\")\n else:\n self._objet = usn_urn.groupdict().get(\"objet\")\n \n if self.type:\n if self.type != usn_urn.groupdict().get(\"type\"):\n raise ValueError(\"Valeurs de NT et de USN incohérentes : Types différents\")\n else:\n self._type = usn_urn.groupdict().get(\"type\")\n \n if self.version:\n if self.version != usn_urn.groupdict().get(\"version\"):\n raise ValueError(\"Valeurs de NT et de USN incohérentes : Versions différents\")\n else:\n self._version = usn_urn.groupdict().get(\"version\")\n \n elif re_usn:\n if self.uuid:\n if self.uuid != get_uuid(re_usn):\n raise SSDPErreur(\"Requêtes invalide ! Valeurs de NT et de USN incohérentes : UUID différents\", self.message)\n \n else:\n self._uuid = get_uuid(re_usn)\n \n if self.rootdevice != (\"upnp:rootdevice\" in usn):\n raise ValueError(\"Valeurs de NT et de USN incohérentes\")\n \n else:\n raise ValueError(\"Mauvaise valeur de USN \" + usn)\n \n self._usn = usn\n self.headers[\"USN\"] = usn\n \n @property\n def cache_control(self):\n return self._cache_control\n \n @cache_control.setter\n @verif_type(cc=str)\n def cache_control(self, cc):\n re_cc = self._re_cachecontrol.match(cc)\n if re_cc:\n self._maxage = int(re_cc.groupdict().get(\"maxage\"))\n \n else:\n raise ValueError(\"Mauvaise valeur pour CACHE-CONTROL\")\n \n self._cache_control = cc\n self.headers[\"CACHE-CONTROL\"] = cc\n \n @property\n def location(self):\n return self._location\n \n @location.setter\n @verif_type(loc=str)\n def location(self, loc):\n self._location = loc\n self.headers[\"LOCATION\"] = loc\n \n @property\n def server(self):\n return self._server\n \n @server.setter\n @verif_type(srv=str)\n def server(self, srv):\n self._server = srv\n self.headers[\"SERVER\"] = srv\n \n # Valeurs\n @property\n def uuid(self):\n if hasattr(self, \"_uuid\"):\n return self._uuid\n \n else:\n return None\n \n @property\n def nom_domaine(self):\n if hasattr(self, \"_nom_domaine\"):\n return self._nom_domaine\n \n else:\n return FStr(\"schemas-upnp-org\")\n \n @property\n def objet(self):\n if hasattr(self, \"_objet\"):\n return self._objet\n \n else:\n return None\n \n @property\n def type(self):\n if hasattr(self, \"_type\"):\n return self._type\n \n else:\n return None\n \n @property\n def version(self):\n if hasattr(self, \"_version\"):\n return self._version\n \n else:\n return None\n \n @property\n def rootdevice(self):\n if hasattr(self, \"_rootdevice\"):\n return self._rootdevice\n \n else:\n return False\n \n @property\n def maxage(self):\n if hasattr(self, \"_maxage\"):\n return self._maxage\n \n else:\n return 0\n \n @property\n def valide(self):\n if self.nts == \"ssdp:byebye\":\n return True\n \n return datetime.now() <= self.dateReception + timedelta(seconds=self.maxage)\n","repo_name":"Jujulego/pyupnp","sub_path":"protocoles/ssdp/requetes/notify.py","file_name":"notify.py","file_ext":"py","file_size_in_byte":11996,"program_lang":"python","lang":"fr","doc_type":"code","stars":0,"dataset":"github-code","pt":"15"} +{"seq_id":"70209298252","text":"#!/usr/bin/env python\n# coding=utf-8\n\n#要用py2 来跑\n\nfrom wsgiref.simple_server import make_server\n\n\ndef RunServer(environ, start_response):\n start_response('200 OK', [('Content-Type', 'text/html')])\n url = environ[\"PATH_INFO\"]\n\n if url == \"/new\":\n msg = \"new\"\n elif url == \"/bbs\":\n msg = \"bbs\"\n else:\n msg = \"404\"\n return msg\n\n\nif __name__ == '__main__':\n httpd = make_server('', 8003, RunServer)\n print(\"http://127.0.0.1:8003/new\")\n print(\"http://127.0.0.1:8003/bbs\")\n httpd.serve_forever()\n","repo_name":"lannyMa/tornado_info","sub_path":"00web框架的本质/01实现基础路由/start.py","file_name":"start.py","file_ext":"py","file_size_in_byte":548,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"15"} +{"seq_id":"6699633497","text":"from flask import Flask,request,render_template\nfrom Model import predict\nimport json\n\n\nUPLOAD_FOLDER = './static/uploads/'\n\n\n\n# create the flask object\napp = Flask(__name__)\napp.secret_key = \"secret key\"\napp.config['UPLOAD_FOLDER'] = UPLOAD_FOLDER\napp.config['MAX_CONTENT_LENGTH'] = 16 * 1024 * 1024\n@app.route('/')\ndef index():\n return render_template('index.html')\n@app.route('/predict',methods=['GET','POST'])\ndef prediction(file):\n data = file\n if data == None:\n return 'Got None'\n else:\n # model.predict.predict returns a dictionary\n prediction = predict.pred(data)\n return json.dumps(str(prediction))\n@app.route('/uploader', methods = ['GET', 'POST'])\ndef upload_file():\n if request.method == 'POST':\n f = request.files['file']\n f.save((UPLOAD_FOLDER+f.filename))\n \n result=prediction(UPLOAD_FOLDER+f.filename)\n return result\nif __name__ == \"__main__\":\n app.run(host='0.0.0.0',debug=True)","repo_name":"abdumhmd/WebApp","sub_path":"app.py","file_name":"app.py","file_ext":"py","file_size_in_byte":961,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"15"} +{"seq_id":"4930651653","text":"class Solution:\n def canFinish(self, numCourses: int, prerequisites: List[List[int]]) -> bool:\n def dfs(v):\n if v in visited:\n return True\n if v in curr:\n self.circle = True\n return False\n\n if v in edges:\n curr.add(v)\n for neighbor in edges[v]:\n if not dfs(neighbor):\n return False\n curr.remove(v)\n visited.add(v)\n return True\n\n edges = {}\n for pair in prerequisites:\n if pair[1] in edges:\n edges[pair[1]].add(pair[0])\n else:\n edges[pair[1]] = {pair[0]}\n\n visited = set()\n curr = set()\n self.circle = False\n for v in range(numCourses):\n if not dfs(v):\n return False\n return True\n","repo_name":"ZongyuWu97/LeetCode","sub_path":"DFS/Course_Schedule.py","file_name":"Course_Schedule.py","file_ext":"py","file_size_in_byte":903,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"15"} +{"seq_id":"15315380699","text":"# 三个方法:\n# isInteger() ,判断当前存储的对象是否为 int;\n# getInteger() , 如果当前存储的元素是 int 型的,那么返回当前的结果 int,否则调用会失败;\n# getList() ,如果当前存储的元素是 List 型的,那么返回该 List,否则调用会失败。\n\nclass NestedIterator(object):\n # 迭代:在出栈过程中判断是数字或是列表,列表直接展开入栈\n def __init__(self, nestedList):\n \"\"\"\n Initialize your data structure here.\n :type nestedList: List[NestedInteger]\n \"\"\"\n # 利用栈存储嵌套列表内的元素\n self.stack = []\n for i in range(len(nestedList)-1,-1,-1):\n self.stack.append(nestedList[i])\n\n def next(self):\n \"\"\"\n :rtype: int\n \"\"\"\n res = self.stack.pop()\n return res.getInteger()\n \n def hasNext(self):\n \"\"\"\n :rtype: bool\n \"\"\"\n while self.stack:\n cur = self.stack[-1]\n # 判断栈顶元素是否为数字\n if cur.isInteger():\n return True\n # 将列表弹出-展开-逆序入栈\n self.stack.pop()\n for i in range(len(cur.getList())-1, -1, -1):\n self.stack.append(cur.getList()[i])\n return False\n # 递归:利用队列在初始化时候递归展开所有子列表\n \"\"\"\n # 深度优先搜索\n def dfs(self, nests):\n for nest in nests:\n # 判断是否为数字,是数字入队列尾部,是列表继续递归\n if nest.isInteger():\n self.queue.append(nest.getInteger())\n else:\n self.dfs(nest.getList())\n \n def __init__(self, nestedList):\n # 初始化过程中展开所有列表\n self.queue = collections.deque()\n self.dfs(nestedList)\n\n def next(self):\n # 队列方法:popleft()弹出最左侧元素\n return self.queue.popleft()\n\n def hasNext(self):\n # 因为已经全部展开所以就看当前队列内是否还有元素\n return len(self.queue)\n \"\"\"","repo_name":"Luminary2822/LeetCode_Codings_Python","sub_path":"dailyExec/341-flattenNestedListIterator.py","file_name":"341-flattenNestedListIterator.py","file_ext":"py","file_size_in_byte":2161,"program_lang":"python","lang":"zh","doc_type":"code","stars":0,"dataset":"github-code","pt":"15"} +{"seq_id":"34036260848","text":"from itertools import chain\nfrom sklearn.metrics import classification_report, confusion_matrix\nfrom sklearn.preprocessing import LabelBinarizer\nimport leveldb\nfrom pycrfsuite import ItemSequence\nfrom gensim.models import Word2Vec\nimport re\n# print('load level dbs and word2vec model')\natom_db = leveldb.LevelDB('data/atom_db')\nbigram_db = leveldb.LevelDB('data/bigram_db')\n# w2v_model = Word2Vec.load('/home/leebird/Projects/word2vec/word2vec/500-vec')\n\nupper_number = re.compile(r'^[A-Z0-9]+$')\nupper = re.compile(r'[A-Z]+')\nall_upper = re.compile(r'^[A-Z]+$')\nnumber = re.compile(r'[0-9]+')\npunctuation = re.compile(r'^[^A-Za-z0-9]+$')\n\ninclude_context = True\ninclude_db = True\n\n\ndef word2features(sent, i):\n global atom_db, bigram_db, upper_number, punctuation\n global include_context, include_db\n # global w2v_model\n features = {}\n\n word = sent[i][0]\n postag = sent[i][1]\n\n is_upper_number = (True if upper_number.match(word) is not None\n and upper.search(word) is not None\n and number.search(word) is not None\n else False)\n\n is_punctuation = False if punctuation.match(word) is None else True\n\n is_all_upper = False if all_upper.match(word) is None else True\n\n try:\n atom_db.Get(word.lower().encode('utf-8'))\n in_db = True\n except KeyError:\n in_db = False\n\n # try:\n # vec = w2v_model[word.lower()]\n # for j, ele in enumerate(vec):\n # features['wordvec_'+str(j)] = ele\n # except KeyError:\n # pass\n\n features.update({\n 'bias': True,\n 'word.lower': word.lower(),\n 'word[-3:]': word[-3:],\n 'word[-2:]': word[-2:],\n 'word[+3:]': word[0:3],\n 'word[+2:]': word[0:2],\n 'word.isupper': is_all_upper,\n 'word.istitle': word.istitle(),\n 'word.isdigit': word.isdigit(),\n 'word.isfirst': (i == 0),\n 'word.is_upper_number': is_upper_number,\n 'word.is_punct': is_punctuation,\n 'postag': postag,\n 'postag[:2]': postag[:2],\n })\n\n if include_db:\n features.update({\n 'word.in_db': in_db,\n })\n\n if i > 0:\n word1 = sent[i - 1][0]\n postag1 = sent[i - 1][1]\n\n word1_word = word1.lower() + '|' + word.lower()\n\n try:\n bigram_db.Get(word1_word.encode('utf-8'))\n in_db = True\n except KeyError:\n in_db = False\n\n if include_context:\n features.update({\n '-1:word.lower': word1.lower(),\n '-1:word[-3:]': word1[-3:],\n '-1:word[-2:]': word1[-2:],\n '-1:word[+3:]': word1[0:3],\n '-1:word[+2:]': word1[0:2],\n # '-1:word.istitle': word1.istitle(),\n # '-1:word.isupper': word1.isupper(),\n '-1:postag': postag1,\n '-1:postag[:2]': postag1[:2],\n\n # '<2:word.lower': word1.lower(),\n # '<2:word.istitle': word1.istitle(),\n # '<2:word.isupper': word1.isupper(),\n # '<2:postag': postag1,\n # '<2:postag[:2]': postag1[:2],\n\n '-1:word.lower|word.lower': word1_word,\n '-1:postag|postag': postag1 + '|' + postag,\n '-1:postag[:2]|postag[:2]': postag1[:2] + '|' + postag[:2],\n })\n if include_db:\n features.update({\n 'db_-1:word.lower|word.lower': in_db,\n })\n else:\n features.update({'BOS': True})\n\n if i > 1:\n word1 = sent[i - 1][0]\n postag1 = sent[i - 1][1]\n word2 = sent[i - 2][0]\n postag2 = sent[i - 2][1]\n word2_word1 = word2.lower() + '|' + word1.lower()\n\n try:\n bigram_db.Get(word2_word1.encode('utf-8'))\n in_db = True\n except KeyError:\n in_db = False\n\n if include_context:\n features.update({\n '-2:word.lower': word2.lower(),\n # '-2:word[-3:]': word2[-3:],\n # '-2:word[-2:]': word2[-2:],\n # '-2:word[+3:]': word2[0:3],\n # '-2:word[+2:]': word2[0:2],\n # '-2:word.istitle': word2.istitle(),\n # '-2:word.isupper': word2.isupper(),\n '-2:postag': postag2,\n '-2:postag[:2]': postag2[:2],\n\n # '<2:word.lower': word2.lower(),\n # '<2:word.istitle': word2.istitle(),\n # '<2:word.isupper': word2.isupper(),\n # '<2:postag': postag2,\n # '<2:postag[:2]': postag2[:2],\n\n '-2:word.lower|-1:word.lower': word2_word1,\n '-2:postag|-1:postag': postag2 + '|' + postag1,\n '-2:postag[:2]|-1:postag[:2]': postag2[:2] + '|' + postag1[:2],\n })\n if include_db:\n features.update({\n 'db_-2:word.lower|-1:word.lower': in_db,\n })\n\n if i < len(sent) - 1:\n word1 = sent[i + 1][0]\n postag1 = sent[i + 1][1]\n\n word_word1 = word.lower() + '|' + word1.lower()\n\n try:\n bigram_db.Get(word_word1.encode('utf-8'))\n in_db = True\n except KeyError:\n in_db = False\n\n if include_context:\n features.update({\n '+1:word.lower': word1.lower(),\n '+1:word[-3:]': word1[-3:],\n '+1:word[-2:]': word1[-2:],\n '+1:word[+3:]': word1[0:3],\n '+1:word[+2:]': word1[0:2],\n # '+1:word.istitle': word1.istitle(),\n # '+1:word.isupper': word1.isupper(),\n '+1:postag': postag1,\n '+1:postag[:2]': postag1[:2],\n\n # '>2:word.lower': word1.lower(),\n # '>2:word.istitle': word1.istitle(),\n # '>2:word.isupper': word1.isupper(),\n # '>2:postag': postag1,\n # '>2:postag[:2]': postag1[:2],\n\n 'word.lower|+1:word.lower': word_word1,\n 'postag|+1:postag': postag + '|' + postag1,\n 'postag[:2]|+1:postag[:2]': postag[:2] + '|' + postag1[:2],\n })\n if include_db:\n features.update({\n 'db_word.lower|+1:word.lower': in_db,\n })\n else:\n features.update({'EOS': True})\n\n if i < len(sent) - 2:\n word1 = sent[i + 1][0]\n postag1 = sent[i + 1][1]\n word2 = sent[i + 2][0]\n postag2 = sent[i + 2][1]\n\n word1_word2 = word1.lower() + '|' + word2.lower()\n\n try:\n bigram_db.Get(word1_word2.encode('utf-8'))\n in_db = True\n except KeyError:\n in_db = False\n\n if include_context:\n features.update({\n '+2:word.lower': word2.lower(),\n # '+2:word[-3:]': word2[-3:],\n # '+2:word[-2:]': word2[-2:],\n # '+2:word[+3:]': word2[0:3],\n # '+2:word[+2:]': word2[0:2],\n # '+2:word.istitle': word2.istitle(),\n # '+2:word.isupper': word2.isupper(),\n '+2:postag': postag2,\n '+2:postag[:2]': postag2[:2],\n \n # '>2:word.lower': word2.lower(),\n # '>2:word.istitle': word2.istitle(),\n # '>2:word.isupper': word2.isupper(),\n # '>2:postag': postag2,\n # '>2:postag[:2]': postag2[:2],\n \n '+1:word.lower|+2:word.lower': word1_word2,\n '+1:postag|+2:postag': postag1 + '|' + postag2,\n '+1:postag[:2]|+2:postag[:2]': postag1[:2] + '|' + postag2[:2],\n })\n if include_db:\n features.update({\n 'db_+1:word.lower|+2:word.lower': in_db,\n })\n\n # for j in range(i - 1, -1, -1):\n # if sent[j][1].startswith('N'):\n # features.append('-1:noun.lower=' + sent[j][0].lower())\n # break\n #\n # for j in range(i, len(sent)):\n # if sent[j][1].startswith('N'):\n # features.append('+1:noun.lower=' + sent[j][0].lower())\n # break\n\n return features\n\n\ndef sent2features(sent):\n return ItemSequence([word2features(sent, i) for i in range(len(sent))])\n\n\ndef sent2labels(sent):\n return [index[-1] for index in sent]\n\n\ndef sent2tokens(sent):\n return [index[0] for index in sent]\n\n\ndef get_sentences(sentence_file):\n with open(sentence_file, 'r') as handler:\n sentence = []\n for line in handler:\n line = line.strip()\n if len(line) == 0:\n yield sentence\n sentence = []\n else:\n tokens = tuple(line.split('\\t'))\n sentence.append(tokens)\n\n\ndef bio_classification_report(y_true, y_pred):\n \"\"\"\n Classification report for a list of BIO-encoded sequences.\n It computes token-level metrics and discards \"O\" labels.\n\n Note that it requires scikit-learn 0.15+ (or a version from github master)\n to calculate averages properly!\n \"\"\"\n lb = LabelBinarizer()\n y_true_combined = lb.fit_transform(list(chain.from_iterable(y_true)))\n y_pred_combined = lb.transform(list(chain.from_iterable(y_pred)))\n\n tagset = set(lb.classes_) - {'O'}\n tagset = sorted(tagset, key=lambda tag: tag.split('-', 1)[::-1])\n class_indices = {cls: idx for idx, cls in enumerate(lb.classes_)}\n\n return classification_report(\n y_true_combined,\n y_pred_combined,\n labels=[class_indices[cls] for cls in tagset],\n target_names=tagset,\n )","repo_name":"leebird/disease-mention-recognition","sub_path":"src/utils.py","file_name":"utils.py","file_ext":"py","file_size_in_byte":9559,"program_lang":"python","lang":"en","doc_type":"code","stars":3,"dataset":"github-code","pt":"15"} +{"seq_id":"27145231172","text":"from django.shortcuts import get_object_or_404\nfrom products.models import Product\n\n\ndef bag_contents(request):\n \"\"\"Context to make bag contents available throughout the website\"\"\"\n\n bag_items = []\n total = 0\n number_of_products = 0\n bag = request.session.get('bag', {})\n\n for item_id, item_data in bag.items():\n if isinstance(item_data, int):\n product = get_object_or_404(Product, pk=item_id)\n total += item_data * product.price\n number_of_products += item_data\n bag_items.append({\n 'item_id': item_id,\n 'quantity': item_data,\n 'product': product,\n })\n else:\n product = get_object_or_404(Product, pk=item_id)\n for flavour, quantity in item_data['items_by_flavour'].items():\n total += quantity * product.price\n number_of_products += quantity\n bag_items.append({\n 'item_id': item_id,\n 'quantity': quantity,\n 'product': product,\n 'flavour': flavour,\n })\n\n context = {\n 'bag_items': bag_items,\n 'total': total,\n 'number_of_products': number_of_products,\n }\n\n return context\n","repo_name":"Code-Institute-Submissions/SweetMagic","sub_path":"bag/contexts.py","file_name":"contexts.py","file_ext":"py","file_size_in_byte":1291,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"15"} +{"seq_id":"44778447480","text":"import numpy as np\nfrom tensorflow import keras\nfrom tensorflow.keras import layers\n\n\ndef _wrap_layer(name,\n input_layer,\n build_output,\n dropout_rate=0.0,\n trainable=True):\n \"\"\"Wrap layers with residual, normalization and dropout.\n :param name: Prefix of names for internal layers.\n :param input_layer: Input layer.\n :param dropout_rate: Dropout rate.\n :param trainable: Whether the layers are trainable.\n :return: Output layer.\n \"\"\"\n if dropout_rate > 0.0:\n dropout_layer = keras.layers.Dropout(\n rate=dropout_rate,\n name='%s-Dropout' % name,\n )(build_output)\n else:\n dropout_layer = build_output\n if isinstance(input_layer, list):\n input_layer = input_layer[0]\n print(\"INPUT LAYER\", input_layer)\n print(\"BUILD OUTPUT\", build_output)\n print(\"DROPOUT\", dropout_layer)\n add_layer = keras.layers.Add(name='%s-Add' % name)([input_layer, dropout_layer])\n normal_layer = keras.layers.LayerNormalization(\n trainable=trainable,\n name='%s-Norm' % name,\n )(add_layer)\n return normal_layer\n\n\ndef attention_builder(name,\n head_num,\n key_dim,\n input_layer,\n trainable=True):\n \"\"\"Get multi-head self-attention builder.\n :param input_layer:\n :param key_dim:\n :param name: Prefix of names for internal layers.\n :param head_num: Number of heads in multi-head self-attention.\n :param trainable: Whether the layer is trainable.\n :return:\n \"\"\"\n\n def _attention_builder(query, value):\n return layers.MultiHeadAttention(\n num_heads=head_num,\n key_dim=key_dim,\n trainable=trainable,\n name=name,\n )(query, value)\n\n return _attention_builder(query=input_layer, value=input_layer)\n\n\ndef feed_forward_builder(name,\n hidden_dim,\n activation,\n input_layer,\n trainable=True):\n \"\"\"Get position-wise feed-forward layer builder.\n :param input_layer:\n :param name: Prefix of names for internal layers.\n :param hidden_dim: Hidden dimension of feed forward layer.\n :param activation: Activation for feed-forward layer.\n :param trainable: Whether the layer is trainable.\n :return:\n \"\"\"\n\n def _feed_forward_builder(x):\n return layers.Dense(\n units=hidden_dim,\n activation=activation,\n trainable=trainable,\n name=name,\n )(x)\n\n return _feed_forward_builder(input_layer)\n\n\ndef get_encoder_component(name,\n input_layer,\n head_num,\n key_dim,\n feed_forward_activation='tanh',\n dropout_rate=0.0,\n trainable=True):\n \"\"\"Multi-head self-attention and feed-forward layer.\n :param key_dim: depth of query and key\n :param name: Prefix of names for internal layers.\n :param input_layer: Input layer.\n :param head_num: Number of heads in multi-head self-attention.\n :param feed_forward_activation: Activation for feed-forward layer.\n :param dropout_rate: Dropout rate.\n :param trainable: Whether the layers are trainable.\n :return: Output layer.\n \"\"\"\n attention_name = '%s-MultiHeadSelfAttention' % name\n feed_forward_name = '%s-FeedForward' % name\n attention_layer = _wrap_layer(\n name=attention_name,\n input_layer=input_layer,\n build_output=attention_builder(\n key_dim=key_dim,\n name=attention_name,\n head_num=head_num,\n trainable=trainable,\n input_layer=input_layer\n ),\n dropout_rate=dropout_rate,\n trainable=trainable,\n )\n feed_forward_layer = _wrap_layer(\n name=feed_forward_name,\n input_layer=attention_layer,\n build_output=feed_forward_builder(\n name=feed_forward_name,\n hidden_dim=key_dim,\n activation=feed_forward_activation,\n trainable=trainable,\n input_layer=input_layer\n ),\n dropout_rate=dropout_rate,\n trainable=trainable,\n )\n return feed_forward_layer\n","repo_name":"AaronWGoh/PerformancePredictionForLearningToRankSystems","sub_path":"transformer.py","file_name":"transformer.py","file_ext":"py","file_size_in_byte":4341,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"15"} +{"seq_id":"70252146891","text":"from flask import Blueprint, request\nimport json\nimport time\n\nfrom hootbot.helpers import endpoint_helpers\nfrom hootbot.logging.logger import bot_log\nfrom hootbot.models.dao.zendesk_ticket import ZendeskTicket\nfrom hootbot.models.enums.payloads import Payloads\nfrom hootbot.models.enums.session_states import SessionStates\nfrom hootbot.actions.facebook.facebook_actions_dict import facebook_actions_dict\nfrom hootbot.database.database import db\nfrom hootbot.api.facebook import facebook_requests\nfrom hootbot.database.database import redis_store\nfrom hootbot.helpers.endpoint_helpers import validate_email\nfrom hootbot.models.dao.user import User\nfrom hootbot.actions.facebook import facebook_actions\nfrom hootbot.api.wit import wit_requests\nfrom hootbot.actions.wit import wit_actions\nfrom hootbot.api.zendesk import zendesk_requests\nfrom hootbot.constants import constants\n\nfacebook_api = Blueprint(\"facebook_api\", __name__)\n\n\n@facebook_api.route('/', methods=['GET'])\ndef handle_verification():\n bot_log(\"Handling Verification...\")\n if request.args.get('hub.verify_token', '') == 'hootastic':\n bot_log(\"Verification successful!\")\n return request.args.get('hub.challenge', '')\n else:\n bot_log(\"Verification failed!\")\n return 'Error, wrong validation token'\n\n\n@facebook_api.route('/', methods=['POST'])\ndef handle_messages():\n payload = request.get_data()\n handle_messaging_events(payload)\n return \"ok\"\n\n\ndef handle_messaging_events(payload):\n \"\"\"\n Handles a POST from the Messenger API, corresponding to an interaction from a user.\n :param payload: The JSON payload from the POST request.\n \"\"\"\n try:\n data = json.loads(payload)\n messaging_events = data['entry'][0]['messaging']\n for event in messaging_events:\n recipient_id = event['sender']['id']\n res = zendesk_flow(recipient_id)\n if not res:\n return\n # Add this user's Facebook Page ID to the database if it doesn't yet exist\n user = User.get_or_create(search_key={'id': recipient_id}, fb_id=recipient_id)[0]\n if not handle_support_paths(event, user):\n return\n # Handle the cases where the message is either raw text or a postback\n elif 'postback' in event:\n handle_postback(event)\n elif 'message' in event and 'text' in event['message']:\n handle_text_message(event)\n elif endpoint_helpers.event_is_image(event):\n wit_actions.handle_failed_interpretation(event)\n else:\n bot_log(\"Unable to handle messaging event %s\" % event)\n except (KeyError, ValueError) as e:\n bot_log(\"Handling of message events failed with following message: %s\" % e)\n\n\ndef zendesk_flow(recipient_id):\n \"\"\"\n Temporary function to handle the migration of users with currently open tickets when Zendesk was turned on.\n This function should be removed once all of these tickets have been closed and migrated.\n \"\"\"\n fb_json = facebook_requests.get_user_info(recipient_id)\n first_name = fb_json['first_name']\n last_name = fb_json['last_name']\n name = str(first_name + last_name).strip().replace(' ', '').lower()\n users = User.query.filter_by(first_name=name).all()\n for user in users:\n if user.id == user.zendesk_id:\n new_user = User(fb_id=recipient_id, first_name=first_name, last_name=last_name, zendesk_id=user.zendesk_id)\n db.session().add(new_user)\n ZendeskTicket.query.filter_by(user_id=user.zendesk_id).delete()\n User.query.filter_by(id=user.id).delete()\n facebook_requests.post_text(recipient_id,\n \"Hello! We've recently activated a bot on our Facebook page. To continue \"\n \"helping you with your active support issue, please provide your email.\")\n redis_store.set(recipient_id, SessionStates.PROVIDING_EMAIL.value)\n db.session().commit()\n return False\n db.session().commit()\n return True\n\n\ndef handle_postback(event):\n \"\"\"\n Handles a postback due to a user interacting with the bot.\n :param event: JSON containing information about the interaction.\n \"\"\"\n try:\n # Parse the key from the postback, removing 'POSTBACK_' and passing to the dictionary\n query_payload = Payloads(event[\"postback\"][\"payload\"].split(\"?=\")[0])\n facebook_actions_dict[query_payload](event)\n except (KeyError, IndexError, TypeError, ValueError) as e:\n bot_log(\"Handling of postback failed with the following message: %s\" % e.message)\n raise\n\n\ndef handle_support_paths(event, user):\n \"\"\"\n Helper method to handle different states of a customer support flow a user may be in.\n This section has various different rules and is thus heavily commented for clarification.\n :param event: JSON containing information about the interaction.\n :param user: The User object these paths are for\n :return: True if execution should continue handling the event, False if not.\n \"\"\"\n recipient_id = event['sender']['id']\n user_state = redis_store.get(recipient_id)\n\n # If this is a postback and the user has open tickets, we can't go through a normal postback flow\n # because that will interfere with the Zendesk integration and adding comments to the ticket.\n # Instead, we don't allow them to interact with buttons while a ticket is currently open.\n if 'postback' in event and (user.get_open_tickets()\n or user_state == SessionStates.DEFINING_SUPPORT_REQUEST.value\n or user_state == SessionStates.ADDING_COMMENT_TO_TICKET.value):\n facebook_requests.post_text(recipient_id, constants.LET_YOU_GET_BACK_TO_THAT)\n # This state occurs after the user had a solved, but not closed, ticket, and we asked them whether\n # they wanted to add a comment to the solved ticket, create a new ticket, or keep learning.\n # We take action on what they replied in the below code block.\n elif user_state == SessionStates.REPLYING_TO_RECENT_TICKET_QUESTION.value:\n redis_store.delete(recipient_id)\n if 'postback' in event:\n handle_postback(event)\n else:\n facebook_requests.post_text(recipient_id, \"Please select one of the options in the menu below!\")\n facebook_actions.recent_ticket_question_action(event)\n # When a user wants to create a ticket, if their user object does not have an email already attached to it\n # in the database, we ask them for it and handle validation in the following branch.\n elif user_state == SessionStates.PROVIDING_EMAIL.value:\n if 'message' in event and 'text' in event['message']:\n message = event['message']['text'].strip()\n if message.lower() == 'cancel':\n redis_store.delete(recipient_id)\n facebook_actions.social_networks_action(event)\n elif validate_email(event['message']['text']):\n user = User.query.filter_by(id=recipient_id).first()\n user.email = event['message']['text']\n db.session().commit()\n redis_store.delete(recipient_id)\n facebook_requests.post_text(recipient_id, constants.SUPPORT_REQUEST_NEW_EMAIL)\n redis_store.set(recipient_id, SessionStates.DEFINING_SUPPORT_REQUEST.value)\n else:\n facebook_requests.post_text(recipient_id, constants.INVALID_EMAIL)\n else:\n facebook_requests.post_text(recipient_id, constants.INVALID_EMAIL)\n # This state occurs when the user said they wanted to create a ticket, and they have no other\n # active/solved tickets in the database. In this case, we asked them to define what they wanted\n # support for. First, we need their email, so we ask for that if we didn't already have it, which is handled above.\n # Following, we ask for them to define their request, and create a ticket/add comments with these messages.\n # We also handle the edge case where the user presses a button while we're expecting text.\n elif user_state == SessionStates.DEFINING_SUPPORT_REQUEST.value:\n zendesk_requests.create_ticket_helper(event, user)\n redis_store.delete(recipient_id)\n # This state occurs when the user said they wanted to add a comment to their recently solved ticket.\n # If they have more than one solved ticket we raise an exception as this is an unexpected state.\n # We then add a comment to the solved ticket and reopen the ticket.\n elif user_state == SessionStates.ADDING_COMMENT_TO_TICKET.value:\n solved_tickets = user.get_solved_tickets()\n if len(solved_tickets) > 1:\n raise ValueError(\"User has more than one 'solved' ticket - unsure which ticket to reopen.\")\n ticket = solved_tickets[0]\n # Re-open the Zendesk ticket and add the comment\n zendesk_requests.reopen_ticket(ticket.id)\n zendesk_requests.verify_user_helper(user.zendesk_id)\n zendesk_requests.add_comment_helper(recipient_id, ticket.id, event)\n redis_store.delete(recipient_id)\n # Finally, handle the general state of the user having tickets attached to them.\n elif user.tickets:\n open_tickets = user.get_open_tickets()\n solved_tickets = user.get_solved_tickets()\n # Having more than one open or one solved ticket is an invalid state\n if len(open_tickets) > 1 or len(solved_tickets) > 1:\n raise ValueError(\"User has more than one 'open' or 'solved' ticket - unsure which ticket to target.\")\n # If the user has an open ticket, we simply assume they're adding a comment to their ticket\n if open_tickets:\n zendesk_requests.verify_user_helper(user.zendesk_id)\n zendesk_requests.add_comment_helper(recipient_id, open_tickets[0].id, event)\n # If the user has a solved ticket we ask them which actions they'd like to take (add to, create new, learn)\n elif solved_tickets:\n facebook_actions.recent_ticket_question_action(event)\n else:\n raise AttributeError(\"User has tickets, but they're neither solved nor open - invalid state\")\n else:\n # If none of these states evaluated to true, the user is not currently involved with support at all.\n # We retrieve their name if it doesn't exist, then return True to continue onto the normal flow.\n if not user.first_name or not user.last_name:\n facebook_requests.populate_user_info(user)\n return True\n return False\n\n\ndef handle_text_message(event):\n \"\"\"\n Handles a general text message sent by the user - runs NLP to try to interpret the text.\n :param event: JSON containing information about the interaction.\n \"\"\"\n event['message']['text'] = event['message']['text'].encode('utf-8')\n resp = wit_requests.get_intent(event['message']['text'])\n try:\n wit_actions.run_actions(event, resp)\n except (KeyError, IndexError, TypeError):\n bot_log(\"Failed to interpret user message: %s\" % event['message']['text'])\n wit_actions.handle_failed_interpretation(event)\n","repo_name":"justintrudell/hootbot","sub_path":"hootbot/endpoints/facebook/messenger_endpoints.py","file_name":"messenger_endpoints.py","file_ext":"py","file_size_in_byte":11270,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"15"} +{"seq_id":"12514197436","text":"menu = '''\r\nBEM VINDO AO BANCO X\r\n\r\nEscolha uma operação:\r\n\r\n[1] Depositar\r\n[2] Sacar\r\n[3] Extrato\r\n[0] Sair\r\n\r\n=> '''\r\n\r\nsaldo = 0\r\nlimite = 500\r\nextrato = ''\r\nnumero_saques = 0\r\nLIMITE_SAQUES = 3\r\n\r\nwhile True:\r\n opcao = input(menu)\r\n\r\n if opcao == '1':\r\n print('=============== DEPÓSITO ===============')\r\n valor = float(input('Informe o valor do DEPÓSITO => R$ '))\r\n\r\n if valor > 0:\r\n saldo += valor\r\n extrato += f'DEPÓSITO => R$ {valor:.2f}\\n'\r\n print(f'Depósito de R${valor:.2f} realizado com sucesso.')\r\n else:\r\n print('Falha na operação! Valor informado é inválido.')\r\n\r\n elif opcao == '2':\r\n print('=============== SAQUE ===============')\r\n valor = float(input('Informe o valor do SAQUE => R$ '))\r\n excedeu_saldo = valor > saldo\r\n excedeu_limite = valor > limite\r\n excedeu_saques = numero_saques >= LIMITE_SAQUES\r\n\r\n if excedeu_saldo:\r\n print(f'Falha na operação! Seu saldo é de R${saldo:.2f} Saldo insuficiente.')\r\n elif excedeu_limite:\r\n print('Falha na operação! Valor excede o limite.')\r\n elif excedeu_saques:\r\n print('Falha na operação! Número máximo de saques excedido.')\r\n elif valor > 0:\r\n saldo -= valor\r\n extrato += f'SAQUE => R$ {valor:.2f}\\n'\r\n numero_saques += 1\r\n print(f'Saque de R${valor:.2f} realizado com sucesso.')\r\n else:\r\n print('Falha na operação! Valor informado é inválido.')\r\n\r\n elif opcao == '3':\r\n print('=============== EXTRATO ===============')\r\n print('Não foram registradas movimentações.' if not extrato else extrato)\r\n print(f'\\nSALDO => R$ {saldo:.2f}')\r\n print('=======================================')\r\n\r\n elif opcao == '0':\r\n break\r\n\r\n else:\r\n print('OPERAÇÃO INVÁLIDA, RETORNANDO AO MENU INICIAL.')\r\n","repo_name":"brunovdl/Dio-Python","sub_path":"sistema_bancario_dio_python.py","file_name":"sistema_bancario_dio_python.py","file_ext":"py","file_size_in_byte":1967,"program_lang":"python","lang":"pt","doc_type":"code","stars":0,"dataset":"github-code","pt":"15"} +{"seq_id":"7271758837","text":"from django.contrib import admin\nfrom django.contrib.auth.models import Permission\nfrom django.contrib.contenttypes.models import ContentType\n\nfrom .models import Resource\n\n\n# Register your models here.\nclass ResourceAdmin(admin.ModelAdmin):\n def save_model(self, request, obj, form, change):\n if form.is_valid():\n resource = form.save()\n resource.save()\n content_type = ContentType.objects.get(id=5)\n permission = Permission.objects.create(codename=resource.codename,\n name=resource.codename,\n content_type=content_type)\n permission.save()\n super().save_model(request, obj, form, change)\n\n\nadmin.site.register(Resource, ResourceAdmin)\n","repo_name":"Xiexdong023/django_permission_dynamic","sub_path":"test01/admin.py","file_name":"admin.py","file_ext":"py","file_size_in_byte":808,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"15"} +{"seq_id":"14156033737","text":"### FUNÇÃO PARA VERIFICAR SE É UMA FORMULA OU NÃO\ndef principal(a):\n\n if a.count(\"(\") != a.count(\")\"):\n return \"FALSO\"\n\n if len(a) == 1 and a.islower() and a.isalpha(): \n return \"x\"\n\n elif \"-\" in a:\n\n x = a.find(\"-\")\n\n if x == len(a)-1:\n return \"FALSO\"\n\n if a[x+1].isalpha() or a[x+1] == \"(\":\n\n a = a[0:x]+a[x+1:]\n return \"-\" + principal(a)\n\n else:\n return \"FALSO\"\n \n else:\n\n if \"(\" not in a and \")\" not in a:\n return \"FALSO\"\n\n elif a[0] == \"(\" and a[-1] == \")\":\n\n a = a[1:-1]\n\n aux = 0\n i = 0\n while i < len(a)+1:\n if a[i] == \"(\":\n aux += 1\n\n if a[i] == \")\":\n aux -= 1\n \n if aux <= 0:\n x = i\n i = len(a)\n\n i += 1\n \n parte1 = a[0:x+1]\n parte2 = a[x+2:len(a)]\n \n if x == len(a)-1:\n return \"FALSO\"\n\n elif a[x+1] in CONECTIVOS:\n return principal(parte1) + a[x+1] + principal(parte2)\n\n return \"FALSO\"\n\n\n### FUNÇÕES PARA VERIFICAR AS SUBFORMULAS\ndef veriRepe(a, sub):\n if a not in sub:\n return sub.append(a)\n else:\n return sub\n\n\ndef veriSub(a):\n sub = []\n i = 0\n\n while i < len(a): \n\n if a[i].isalpha():\n veriRepe(a[i], sub)\n \n if a[i] == \"-\":\n if a[i+1].isalpha():\n veriRepe(a[i]+a[i+1], sub)\n\n if a[i+1] == \"(\":\n \n j = i+2\n aux = 1\n while j < len(a):\n if a[j] == \"(\":\n aux += 1\n if a[j] == \")\":\n aux -= 1\n if aux == 0:\n aux = j\n j = len(a)\n\n j += 1\n\n veriRepe(a[i:aux+1], sub)\n \n if a[i] == \"(\":\n \n j = i+1\n aux = 1\n while j < len(a):\n if a[j] == \"(\":\n aux += 1\n if a[j] == \")\":\n aux -= 1\n if aux == 0:\n aux = j\n j = len(a)\n\n j += 1\n\n veriRepe(a[i:aux+1], sub)\n i += 1\n\n return(sub)\n\ndef main():\n\n print(\"#\"*33)\n print(\" Verificador de Fórmula Lógica \")\n print(\"#\"*33)\n print()\n\n print('Símbolos Átomicos -> {\\033[1;32ma, b, c, ..., x, y, z\\033[m}')\n print('Símbolos auxiliares -> {\\033[1;32m( )\\033[m}')\n print('{\\033[1;32m-\\033[m} significando negação')\n print('{\\033[1;32m&\\033[m} significando conjução')\n print('{\\033[1;32m#\\033[m} significando disjunção')\n print('{\\033[1;32m>\\033[m} significando implicação')\n\n print(\"Exemplo:\\033[1;32m (-(a#b)>(a&b)) \\033[m\")\n print()\n\n formula = input(\"digite uma formula com ou sem espaços entre os caracteres: \")\n\n semespaco = \"\"\n for i in range(len(formula)):\n if formula[i] != \" \":\n semespaco = semespaco + formula[i]\n\n resultado = principal(semespaco)\n\n if \"FALSO\" in resultado:\n print(\"\\n>>> NÃO É FORMULA\")\n\n else:\n\n listOrdem = sorted(veriSub(semespaco), key=len)\n print(\"\\n>>> É FORMULA\")\n print(\">>> As subformulas são:\", listOrdem)\n print(\">>> A complexidade é:\", len(resultado))\n\nCONECTIVOS = [\">\" , \"&\", \"#\"]\nmain()\n","repo_name":"moisesocosta/Codigos","sub_path":"Faculdade/Lógica/Trabalho-1/TrabalhoDeLogica1.py","file_name":"TrabalhoDeLogica1.py","file_ext":"py","file_size_in_byte":3685,"program_lang":"python","lang":"pt","doc_type":"code","stars":0,"dataset":"github-code","pt":"15"} +{"seq_id":"31791329235","text":"import json\nimport sys\nimport os\n\nout_subattrbuteIndex = {}\nout_hotelAttributeIndex = {}\n\ndef convertSentimentToInt(sentiment):\n sentiment_case = sentiment.lower().replace(' ', '')\n if 'verynegative' == sentiment_case:\n return '0'\n if 'negative' == sentiment_case:\n return '1'\n if 'neutral' == sentiment_case:\n return '2'\n if 'positive' == sentiment_case:\n return '3'\n if 'verypositive' == sentiment_case:\n return '4'\n\ndef addOrInsert(locationKey, attr, subAttr, hotelId, reviewId, probability, sentiment):\n sentimentInt = convertSentimentToInt(sentiment)\n \n if locationKey not in out_subattrbuteIndex:\n out_subattrbuteIndex[locationKey] = {}\n if attr not in out_subattrbuteIndex[locationKey]:\n out_subattrbuteIndex[locationKey][attr] = {}\n if subAttr not in out_subattrbuteIndex[locationKey][attr]:\n out_subattrbuteIndex[locationKey][attr][subAttr] = {}\n if hotelId not in out_subattrbuteIndex[locationKey][attr][subAttr]:\n out_subattrbuteIndex[locationKey][attr][subAttr][hotelId] = []\n \n out_subattrbuteIndex[locationKey][attr][subAttr][hotelId].append(str((reviewId, probability, sentimentInt)))\n \n # do it for hotelid\n if locationKey not in out_hotelAttributeIndex:\n out_hotelAttributeIndex[locationKey] = {}\n if hotelId not in out_hotelAttributeIndex[locationKey]:\n out_hotelAttributeIndex[locationKey][hotelId] = {}\n if attr not in out_hotelAttributeIndex[locationKey][hotelId]:\n out_hotelAttributeIndex[locationKey][hotelId][attr] = {} \n if subAttr not in out_hotelAttributeIndex[locationKey][hotelId][attr]:\n out_hotelAttributeIndex[locationKey][hotelId][attr][subAttr] = {}\n if sentimentInt not in out_hotelAttributeIndex[locationKey][hotelId][attr][subAttr]:\n out_hotelAttributeIndex[locationKey][hotelId][attr][subAttr][sentimentInt] = 0.0\n out_hotelAttributeIndex[locationKey][hotelId][attr][subAttr][sentimentInt] = out_hotelAttributeIndex[locationKey][hotelId][attr][subAttr][sentimentInt] + float(probability)\n\nif __name__ == \"__main__\":\n inputDir = sys.argv[1]\n listFiles = os.listdir(inputDir)\n basePath = os.path.join(os.getcwd(), inputDir)\n for fName in listFiles:\n path = os.path.join(basePath, fName)\n data = json.loads(open(path, 'r').read())\n for key in data:\n hotelDictionary = data[key]\n for hotelId in hotelDictionary:\n reviewDictionary = hotelDictionary[hotelId]\n for reviewId in reviewDictionary:\n attributeDictionary = reviewDictionary[reviewId]\n for attr in attributeDictionary:\n metaprobability, subAttrDetails = attributeDictionary[attr]\n for subAttrDet in subAttrDetails:\n #print ('subAttrDetails: ' + str(subAttrDet))\n subAttr = subAttrDet['subAttr']\n sentiment = subAttrDet['sentiment']\n probability = subAttrDet['probability']\n sentimentInt = convertSentimentToInt(sentiment)\n # strKey = str((subAttr, sentimentInt))\n # if strKey not in out_subattrbuteIndex:\n # out_subattrbuteIndex[strKey] = {}\n #print('prob, metaprob: ' + str(probability) + ' : ' + str(metaprobability))\n #print ('types: ' + str(type(strKey)) + ' : ' + str(type(hotelId)))\n # out_subattrbuteIndex[strKey][hotelId] = [str((reviewId, probability*metaprobability))]\n addOrInsert(key, attr, subAttr, hotelId, reviewId, probability*metaprobability, sentiment)\n \n \n f = open('sentiment.json', 'w')\n f.write(json.dumps(out_subattrbuteIndex))\n f.close()\n f = open('hotel.json', 'w')\n f.write(json.dumps(out_hotelAttributeIndex))\n f.close()","repo_name":"anupamme/gcs-python","sub_path":"scoring4-reduce.py","file_name":"scoring4-reduce.py","file_ext":"py","file_size_in_byte":4034,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"15"} +{"seq_id":"24695044861","text":"from django.urls import path\nfrom . import views\n\n# layout/\nurlpatterns = [\n path('view-all/', views.ClassLayoutList.as_view()), # get\n path('view/', views.ClassLayoutDetail.as_view()), # get\n path('create/', views.ClassLayoutCreate.as_view()), # post\n path('update/', views.ClassLayoutUpdate.as_view()), # post\n path('refund/', views.ClassLayoutRefund.as_view()), # post\n path('delete/', views.ClassLayoutDelete.as_view()), # delete\n]\n","repo_name":"muiboonyang/anywhere-fitness","sub_path":"gym_classes/urls.py","file_name":"urls.py","file_ext":"py","file_size_in_byte":492,"program_lang":"python","lang":"en","doc_type":"code","stars":3,"dataset":"github-code","pt":"15"} +{"seq_id":"72071178892","text":"from . import *\nfrom vizdoom import *\nfrom collections import deque\nimport os\nfrom utils import policy_rewards\nfrom utils import doom\nimport cv2\n\nclass Net(torch.nn.Module):\n\n def __init__(self, action_size, stack_size):\n super(Net, self).__init__()\n self.conv1 = torch.nn.Conv2d(stack_size, 32, 8, 4)\n self.bn1 = torch.nn.BatchNorm2d(32)\n self.conv2 = torch.nn.Conv2d(32, 64, 4, 2)\n self.bn2 = torch.nn.BatchNorm2d(64)\n self.conv3 = torch.nn.Conv2d(64, 128, 4, 2)\n self.bn3 = torch.nn.BatchNorm2d(128)\n\n self.fc1 = torch.nn.Linear(128*3*3, 512)\n self.head = torch.nn.Linear(512, action_size)\n\n def forward(self, x):\n x = F.elu(self.bn1(self.conv1(x)))\n x = F.elu(self.bn2(self.conv2(x)))\n x = F.elu(self.bn3(self.conv3(x)))\n x = F.elu(self.fc1(x.view(-1, 128*3*3)))\n x = self.head(x)\n return x\n\n\nclass DoomBasic(object):\n\n def __init__(self, model_path, doom_config_path, doom_scenario_path, device=None):\n self._model_path = model_path\n self._env = doom.create_environment(doom_config_path, doom_scenario_path)\n self._state_size = 84\n self._stack_size = 4\n self._device =torch.device(device) if device \\\n else torch.device(\"cuda\" if torch.cuda.is_available() else \"cpu\")\n self._action_size = self._env.get_available_buttons_size()\n self._net = Net(self._action_size, self._stack_size).to(self._device)\n self.possible_actions = np.identity(3, dtype=int).tolist()\n\n def __del__(self):\n self._env.close()\n\n\n def preprocess_frame(self, frame):\n frame = frame[30:-10, 30:-30]\n frame = frame / 255.\n frame = cv2.resize(frame, (self._state_size, self._state_size))\n return frame\n\n\n def stacked_state(self, frame, frame_stack=None):\n frame = self.preprocess_frame(frame)\n if frame_stack:\n frame_stack.append(frame)\n else:\n frame_stack = deque([np.zeros((self._state_size, self._state_size), dtype=np.int) for _ in range(self._stack_size)], maxlen=self._stack_size)\n for _ in range(self._stack_size):\n frame_stack.append(frame)\n state = np.stack(frame_stack, axis=0)\n state = torch.tensor(state, dtype=torch.float32).unsqueeze(0).to(self._device)\n return state, frame_stack\n\n def run_eposide(self, gamma):\n self._env.new_episode()\n state, stacked_frames = self.stacked_state(self._env.get_state().screen_buffer)\n eposide_rewards = []\n eposide_actions = []\n eposide_logits = []\n done = False\n while not done:\n logits = self._net(state)\n action_probability_distribution = F.softmax(logits).cpu().detach().numpy()\n action = np.random.choice(range(action_probability_distribution.shape[1]),\n p=action_probability_distribution.ravel())\n reward = self._env.make_action(self.possible_actions[action])\n done = self._env.is_episode_finished()\n if done:\n next_frame = np.zeros((self._state_size, self._state_size), dtype=np.int)\n else:\n next_frame = self._env.get_state().screen_buffer\n\n state, stacked_frames = self.stacked_state(next_frame, stacked_frames)\n eposide_logits.append(logits.squeeze(0))\n eposide_actions.append(action)\n eposide_rewards.append(reward)\n discount_eposide_rewards = policy_rewards.discount_episode_rewards(gamma, eposide_rewards)\n return eposide_logits, eposide_actions, discount_eposide_rewards, np.sum(eposide_rewards)\n\n\n def train(self, num_batchs, batch_eposides, lr=1e-4, gamma=0.95, resume=False):\n if resume and os.path.exists(self._model_path):\n self._net.load_state_dict(torch.load(self._model_path))\n criterion = torch.nn.CrossEntropyLoss(reduction='none')\n optimizer = torch.optim.RMSprop(self._net.parameters(), lr)\n for i in range(num_batchs):\n logits = []\n actions = []\n discount_rewards = []\n rewards = []\n optimizer.zero_grad()\n for _ in range(batch_eposides):\n eposide_logits, eposide_actions, discount_eposide_rewards, eposide_reward = self.run_eposide(gamma)\n logits.extend(eposide_logits)\n actions.extend(eposide_actions)\n discount_rewards.extend(discount_eposide_rewards)\n rewards.append(eposide_reward)\n discount_rewards = policy_rewards.normailize_rewards(discount_rewards)\n batch_actions = torch.tensor(actions, dtype=torch.long).to(self._device)\n batch_logits = torch.stack(logits)\n batch_discount_rewards = torch.tensor(discount_rewards, dtype=torch.float32).to(self._device)\n batch_reward = np.sum(rewards)\n loss = criterion(batch_logits, batch_actions)\n loss = (loss * batch_discount_rewards).mean()\n loss.backward()\n # for group in optimizer.param_groups:\n # for p in group['params']:\n # p.grad = -1 * p.grad\n # for param in self._net.parameters():\n # param.grad.data.clamp_(-1, 1)\n\n optimizer.step()\n print(\"==========================================\")\n print(\"Batch: \", i+1, \"/\", num_batchs)\n print(\"-----------\")\n print(\"Number of training episodes: {}\".format((i+1)*batch_eposides))\n print(\"Batch reward: {}\".format(batch_reward))\n print(\"Mean Reward of that batch {}\".format(batch_reward/batch_eposides))\n print(\"Batch Loss: {}\".format(loss))\n torch.save(self._net.state_dict(), self._model_path)\n print(\"Training Done ! \")\n\n\nclass DoomHealth(DoomBasic):\n\n def preprocess_frame(self, frame):\n # frame = cv2.cvtColor(frame, cv2.COLOR_RGB2GRAY)\n frame = frame[80:, :]\n frame = frame / 255.\n frame = cv2.resize(frame, (self._state_size, self._state_size))\n return frame\n","repo_name":"balansky/reinforcement_learning","sub_path":"policy/doom.py","file_name":"doom.py","file_ext":"py","file_size_in_byte":6166,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"15"} +{"seq_id":"41124824919","text":"\"\"\"\nUtility functions\n\"\"\"\nfrom typing import Optional\n\nfrom colorclass import Color\n\nCOLORS = {\n \"Property value\": \"autoyellow\",\n \"Down payment\": \"automagenta\",\n \"Monthly payment\": \"autogreen\",\n \"Term\": \"autocyan\",\n}\n\n\ndef normalize_rate(rate: float) -> float:\n \"\"\"\n normalize rate to unit\n :param rate:\n :return:\n \"\"\"\n if rate > 100:\n raise Exception(\"Invalid interest rate\")\n return rate / 100 if rate > 0.5 else rate\n\n\ndef add_color(field: str, text: Optional[str] = None) -> str:\n \"\"\"\n Add color to fields\n :param field:\n :param text:\n :return:\n \"\"\"\n text = text or field\n if field in COLORS:\n return Color(f\"{{{COLORS[field]}}}{text}{{/{COLORS[field]}}}\")\n return text\n","repo_name":"sofglide/mortgage-simulator","sub_path":"mortgage_simulator/utils.py","file_name":"utils.py","file_ext":"py","file_size_in_byte":748,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"15"} +{"seq_id":"7191992179","text":"class Solution:\n def combination_rec(self, start, k, tail, target, res):\n if target <= 0:\n return\n \n if k == 1:\n if target >= start and target <= 9:\n new_tail = list(tail)\n new_tail.append(target)\n res.append(new_tail)\n return\n \n for n in range(start, 11 - k):\n tail.append(n)\n self.combination_rec(n + 1, k - 1, tail, target - n, res)\n tail.pop()\n \n \n def combinationSum3(self, k: int, n: int) -> List[List[int]]:\n res = []\n self.combination_rec(1, k, list(), n, res)\n return res\n","repo_name":"leakvoid/leetcode_solutions","sub_path":"216_combination_sum.py","file_name":"216_combination_sum.py","file_ext":"py","file_size_in_byte":668,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"15"} +{"seq_id":"34314764532","text":"# The isBadVersion API is already defined for you.\n# @param version, an integer\n# @return an integer\n# def isBadVersion(version):\n\nclass Solution:\n def firstBadVersion(self, n):\n \"\"\"\n :type n: int\n :rtype: int\n \"\"\"\n \n # def update_n(x):\n # if isBadVersion(x):\n # return x\n # else:\n # return x\n start = 1\n end = n\n while start', Login)\nroot0.mainloop()\n\n# 建立连接\ns = socket.socket(socket.AF_INET, socket.SOCK_STREAM)\ns.connect((IP, int(PORT)))\nif user:\n s.send(user.encode()) # 发送用户名\nelse:\n s.send('用户名不存在'.encode())\n user = IP + ':' + PORT\n\n# 聊天窗口\nroot1 = tkinter.Tk()\nroot1.geometry(\"640x480\")\nroot1.title('群聊')\nroot1.resizable(0,0)\n\nlistbox = ScrolledText(root1)\nlistbox.place(x=0, y=0, width=1280, height=320)\nlistbox.tag_config('tag1', foreground='red',backgroun=\"yellow\")\nlistbox.insert(tkinter.END, 'welcome to the chatroom\\n', 'tag1')\nlistbox.insert(tkinter.END, \"To send private message, \\n please use \\\"message sender ~ receiver\\\" formate \", 'tag1')\nINPUT = tkinter.StringVar()\nINPUT.set('')\nentryIuput = tkinter.Entry(root1, width=120, textvariable=INPUT)\nentryIuput.place(x=5,y=320,width=480,height=170)\n\n# 在线用户列表\nlistbox1 = tkinter.Listbox(root1)\nlistbox1.place(x=420, y=0, width=400, height=320)\n\ndef send(*args):\n message = entryIuput.get() + '~' + user + '~' + chat\n s.send(message.encode())\n INPUT.set('')\n\nsendButton = tkinter.Button(root1, text =\"\\n SEND \\n \",anchor = 'n',command =\nsend,font=('Helvetica', 18),bg = 'white')\nsendButton.place(x=585,y=320,width=55,height=300)\nroot1.bind('', send)\n\ndef receive():\n global uses\n try:\n while True:\n data = s.recv(1024)\n data = data.decode()\n print(data)\n try:\n uses = json.loads(data)\n listbox1.delete(0, tkinter.END)\n listbox1.insert(tkinter.END, \"当前在线用户\")\n #listbox1.tag_config('tag5', foreground='yellow')\n listbox1.insert(tkinter.END, \"My user name is :\" + str(user))\n listbox1.insert(tkinter.END, \"------Online User List-------\")\n for x in range(len(uses)):\n listbox1.insert(tkinter.END, uses[x])\n users.append('------Group chat-------')\n except:\n try:\n data = data.split('~')\n message = data[0]\n userName = data[1]\n chatwith = data[2]\n message = '\\n' + message\n if chatwith == '------Group chat-------': # 群聊\n if userName == user:\n listbox.insert(tkinter.END, message)\n else:\n listbox.insert(tkinter.END, message)\n elif userName == user or chatwith == user: # 私聊\n if userName == user:\n listbox.tag_config('tag2', foreground='red')\n listbox.insert(tkinter.END, message, 'tag2')\n else:\n listbox.tag_config('tag3', foreground='green')\n listbox.insert(tkinter.END, message,'tag3')\n \n listbox.see(tkinter.END)\n except Exception as e:\n print(e)\n print(\"incorrect usage\")\n pass\n except:\n print(\"end of using\")\nr = threading.Thread(target=receive)\nr.start() # 开始线程接收信息\nroot1.mainloop()\ns.close()","repo_name":"HarryHy/Design_wire_protocal_chatroom","sub_path":"client.py","file_name":"client.py","file_ext":"py","file_size_in_byte":5028,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"15"} +{"seq_id":"35106167996","text":"from shelf.health import Health\nfrom shelf.health_status import HealthStatus\nfrom tests.test_base import TestBase\nimport multiprocessing\n\n\nclass HealthTest(TestBase):\n def setUp(self):\n super(HealthTest, self).setUp()\n self.config = {\n \"buckets\": [\n {\n \"referenceName\": \"hi\"\n },\n {\n \"referenceName\": \"hello\"\n },\n {\n \"referenceName\": \"other\"\n },\n {\n \"referenceName\": \"four\",\n },\n {\n \"referenceName\": \"five\"\n }\n ]\n }\n manager = multiprocessing.Manager()\n self.health = Health(self.config, manager)\n\n def test_get_failing_ref_name_list(self):\n self.health.refNames = {\n \"hi\": False,\n \"hello\": True,\n \"other\": False,\n }\n\n expected = [\n \"hi\",\n \"other\"\n ]\n\n actual = self.health.get_failing_ref_name_list()\n # I sort them because the order in which dictionaries will iterate\n # through items is not reliable by design.\n self.assertEqual(sorted(expected), sorted(actual))\n\n def test_get_passing_ref_name_list(self):\n self.health.refNames = {\n \"hello\": False\n }\n\n expected = [\n \"hi\",\n \"other\",\n \"four\",\n \"five\"\n ]\n\n actual = self.health.get_passing_ref_name_list()\n self.assertEqual(sorted(expected), sorted(actual))\n\n def run_get_status(self, elasticsearch, refNames, expected):\n self.health.refNames = refNames\n self.health.elasticsearch = elasticsearch\n status = self.health.get_status()\n self.assertEqual(expected, status)\n\n def test_get_status_20_percent_failing_bucket(self):\n self.run_get_status(\n True,\n {\n \"four\": False,\n \"five\": True, # Just for fun, shouldn't break anything.\n },\n HealthStatus.CRITICAL\n )\n\n def test_get_status_less_than_20_percent_failing_bucket(self):\n # I have to inflate the number of total buckets so that\n # I can have more than 0% but less than 20% failing.\n self.config[\"buckets\"].append({\n \"referenceName\": \"six\"\n })\n\n self.run_get_status(\n True,\n {\n \"four\": False,\n },\n HealthStatus.WARNING\n )\n\n def test_get_status_passing(self):\n self.run_get_status(\n True,\n {\n \"four\": True,\n \"five\": True,\n },\n HealthStatus.OK\n )\n\n def test_elasticsearch_unhealthy(self):\n self.run_get_status(\n False,\n {\n \"four\": True,\n \"five\": True,\n },\n HealthStatus.CRITICAL\n )\n\n def test_elasticsearch_unhealthy_with_failing_buckets_less_than_20_percent(self):\n self.config[\"buckets\"].append({\n \"referenceName\": \"six\"\n })\n self.run_get_status(\n False,\n {\n \"four\": False,\n },\n HealthStatus.CRITICAL\n )\n","repo_name":"AbsentSemicolon/shelf","sub_path":"tests/health_test.py","file_name":"health_test.py","file_ext":"py","file_size_in_byte":3346,"program_lang":"python","lang":"en","doc_type":"code","dataset":"github-code","pt":"15"} +{"seq_id":"19686633204","text":"import json\nfrom unicodedata import normalize\n\nisascii = lambda word: len(word) == len(word.encode())\n\n\ndef remover_acentos(text: str):\n return normalize('NFKD', text).encode('ASCII', 'ignore').decode('ASCII')\n\n\ndef normalize_frase(frase: str):\n return remover_acentos(frase).replace(\"?\", \"\").replace(\",\", \"\").replace(\" \", \"_\")\n\n\ndef load_json(file):\n return json.loads(open(file=file, mode=\"r\", encoding=\"utf-8\").read())\n\n\ndef save_as_json(value, filename, indent=2, sort_keys=False):\n print(\n json.dumps(value, indent=indent, sort_keys=sort_keys, ensure_ascii=False),\n file=open(filename, mode='w', encoding=\"UTF-8\"),\n flush=True\n )\n\n\ndef extract_answers(correct_answers):\n answers = []\n for answer in correct_answers:\n for triple in answer[\"triples\"]:\n elements = []\n for element in triple:\n try:\n\n new_element = str(element) \\\n .replace(\"*\", \"\") \\\n # .replace(\"___\", \"_\") \\\n # .replace(\"__\", \"_\") \\\n # .replace(\"(\", \"\") \\\n # .replace(\")\", \"\") \\\n # .lower()\n elements.append(new_element)\n except Exception as e:\n print(e)\n raise e\n answers.append(elements)\n return answers\n\n\ndef carregar_frases(arquivo):\n frases = []\n with open(arquivo, mode=\"r\", encoding=\"UTF-8\") as frases_arquivo:\n for frase in frases_arquivo:\n frase = frase.replace(\"\\n\", \"\")\n if not frase:\n continue\n if frase.startswith(\"#\"):\n continue\n frases.append(frase)\n\n return frases\n\n\ndef to_list(type, size, slm1_only_l1_option):\n for i, frase in enumerate(frases):\n if type is \"base\":\n slm1_only_l1_option = ''\n size = 'base'\n try:\n name = base_path.format(i, frase=normalize_frase(frase), size=size, type=type,\n slm1_only_l1_option=slm1_only_l1_option + '/')\n analysis = load_json(name)\n except Exception as e:\n analysis = [{\"resposta\": {\"ranking_time_only\": -1, \"ranking_time\": -1, \"total_time\": -1}}]\n print(\"file not found!\", e)\n\n slm1_only_l1_option = slm1_only_l1_option if slm1_only_l1_option else 'base'\n size = size if size else 'base'\n\n if i not in analysis_map:\n analysis_map[i] = {}\n if not size in analysis_map[i]:\n analysis_map[i][size] = {}\n if not type in analysis_map[i][size]:\n analysis_map[i][size][type] = {}\n if not slm1_only_l1_option in analysis_map[i][size][type]:\n analysis_map[i][size][type][slm1_only_l1_option] = {}\n\n analysis_map[i][\"frase\"] = frase\n analysis_map[i][size][type][slm1_only_l1_option][\"ranking_time\"] = analysis[0][\"resposta\"].get(\n \"ranking_time\", -1)\n analysis_map[i][size][type][slm1_only_l1_option][\"ranking_time_only\"] = analysis[0][\"resposta\"].get(\n \"ranking_time_only\", -1)\n try:\n analysis_map[i][size][type][slm1_only_l1_option][\"total_time\"] = analysis[0][\"resposta\"][\"total_time\"]\n except Exception as e:\n print(i, size, type, slm1_only_l1_option, e)\n analysis_map[i][size][type][slm1_only_l1_option][\"total_time\"] = -1\n analysis_map[i][size][type][slm1_only_l1_option][\"timeout\"] = analysis[0][\"resposta\"].get(\"timeout\", \"-1\")\n\n correct_answers = analysis[0][\"resposta\"].get(\"correct_answer\", [])\n has_correct_answer = False\n\n if correct_answers:\n has_correct_answer = True\n\n\n\n answers = extract_answers(correct_answers)\n analysis_map[i][size][type][slm1_only_l1_option][\"answers\"] = answers\n analysis_map[i][size][type][slm1_only_l1_option][\"has_answer\"] = has_correct_answer\n\n if analysis[0][\"resposta\"].get(\"timeout\", False):\n answer_size = \"-1\"\n else:\n answer_size = len(answers)\n analysis_map[i][size][type][slm1_only_l1_option][\"answer_size\"] = answer_size\n\n data = {}\n data[\"id\"] = i\n data[\"size\"] = size\n data[\"type\"] = type\n data[\"slm1_only_l1_option\"] = slm1_only_l1_option\n data[\"ranking_time\"] = analysis[0][\"resposta\"].get(\"ranking_time\", -1)\n data[\"ranking_time_only\"] = analysis[0][\"resposta\"].get(\"ranking_time_only\", -1)\n data[\"total_time\"] = analysis[0][\"resposta\"].get(\"total_time\", -1)\n data[\"has_answer\"] = has_correct_answer\n data[\"answer_size\"] = answer_size\n data[\"timeout\"] = analysis[0][\"resposta\"].get(\"timeout\", \"-1\")\n\n lsizes = analysis[0][\"resposta\"].get(\"l_sizes\", [])\n for index, lsize in enumerate(lsizes):\n data[\"l\" + str(index + 1) + \"size\"] = lsize\n analysis_map[i][size][type][slm1_only_l1_option][\"l\" + str(index + 1) + \"size\"] = lsize\n\n analysis_list.append(data)\n\n\nbase_path = \"../resultados2/{type}/{slm1_only_l1_option}{size}/{:0>3d}-slm1-x{size}-{frase}.json\"\nfrases = carregar_frases(\"../phrases/qald7.txt\")\n\nanalysis_map = {}\nanalysis_list = []\ntypes = [\"slm1\"]\nslm1_only_l1_options = [\"True\", \"False\"]\nsizes = ['10', '30', '50', '75', '100', '150', '200', '300', '400', '500']\n\nfor type in types:\n for slm1_only_l1_option in slm1_only_l1_options:\n for size in sizes:\n to_list(type, size, slm1_only_l1_option)\n\nto_list(\"base\", \"base\", \"base\")\n\nanalysis_list.sort(key=lambda x: x[\"id\"])\nsave_as_json(analysis_map, \"../analyses/base_sl1m/analysis_map_pre.json\")\nsave_as_json(analysis_list, \"../analyses/base_sl1m/analysis_list.json\")\n\nprint(\"##################################################################################\")\nanalysis_map = {}\nanalysis_list = []\ntypes = [\"all2\", \"all3\", \"all4\"]\nslm1_only_l1_options = [\"True\", \"False\"]\nsizes = ['10', '30', '50', '75', '100', '150', '200', '300', '400', '500', '750']\n\nfor type in types:\n for slm1_only_l1_option in slm1_only_l1_options:\n for size in sizes:\n to_list(type, size, slm1_only_l1_option)\nto_list(\"base\", \"base\", \"base\")\nanalysis_list.sort(key=lambda x: x[\"id\"])\nsave_as_json(analysis_map, \"../analyses/all/analysis_map_pre.json\")\nsave_as_json(analysis_list, \"../analyses/all/analysis_list.json\")","repo_name":"Ensepro/ensepro-experiments-sl1m","sub_path":"scripts/step2_run_qald_analysis.py","file_name":"step2_run_qald_analysis.py","file_ext":"py","file_size_in_byte":6412,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"15"} +{"seq_id":"74528848651","text":"import pandas as pd\nimport numpy as np\nimport warnings\nimport sys\nwarnings.filterwarnings('ignore')\n\nfirst_arg = sys.argv[1]\nsecond_arg = sys.argv[2]\ngenre = sys.argv[3]\n\n# input list of imdbIds and ratings as two arrays\n\ndef recommend(first_arg,second_arg,genre) :\n\n\timdbIds = first_arg.split(\", \")\n\timdbRatings = second_arg.split(\", \")\n\n\toutput = {}\n\tdf = pd.read_csv('src/main/java/recommend/ratings.csv', usecols=['userId','movieId','rating'])\n\n\tmovie_titles = pd.read_csv('src/main/java/recommend/movies.csv', usecols=['movieId','title','genres'])\n\timdb_to_id = pd.read_csv('src/main/java/recommend/links.csv', usecols=['movieId','imdbId'])\n\n\tratings = pd.DataFrame(df.groupby('movieId')['rating'].mean())\n\tratings['numRatings'] = pd.DataFrame(df.groupby('movieId')['rating'].count())\n\n\tmovie_matrix = df.pivot_table(index='userId', columns='movieId', values='rating')\n\n\tfor i in range(len(imdbIds)):\n\t\tid = imdb_to_id.loc[imdb_to_id.loc[:,'imdbId'] == int(imdbIds[i]),:]['movieId'].values[0]\n\t\tmovie = movie_matrix[id] ## the rating correlations between this movie and the other movies\n\n\t\tsimilar_to_movie = movie_matrix.corrwith(movie)\n\n\t\tcorr_movie = pd.DataFrame(similar_to_movie, columns=['correlation'])\n\t\tcorr_movie.dropna(inplace=True)\n\t\tcorr_movie = corr_movie.join(ratings['numRatings'])\n\n\t\t#corr_movie.join(imdb_to_id, on = 'movieId', how = 'left')\n\t\tcorr_movie = pd.merge(corr_movie,imdb_to_id, left_on = 'movieId', right_on = 'movieId')\n\t\tcorr_movie = pd.merge(corr_movie,movie_titles, left_on = 'movieId', right_on = 'movieId')\n\n\t\tif genre != \"\": \n\t\t\tcorr_movie = corr_movie[corr_movie['genres'].str.contains(genre)]\n\n\t\tif (int(imdbRatings[i]) > 5):\n\t\t \tnew = corr_movie[corr_movie['numRatings'] > 80].sort_values(by='correlation', ascending=False).head(21)\n\t\telse:\n\t\t\tnew = corr_movie[corr_movie['numRatings'] > 80].sort_values(by='correlation', ascending=True).head(21)\n\n\t\tfor index,row in new.iterrows():\n\t\t\tif int(row['imdbId']) in output.keys():\n\t\t\t\toutput[int(row['imdbId'])] += int(imdbRatings[i])*abs(row['correlation'])\n\t\t\telse:\n\t\t\t\toutput[int(row['imdbId'])] = int(imdbRatings[i])*abs(row['correlation'])\n\n\trecs = sorted(output, key=output.get, reverse=True)[:21]\n\tfor j in range(len(imdbIds),len(recs)):\n\t\tprint(str(recs[j]))\n\treturn\nrecommend(first_arg, second_arg, genre)\n#recommend([\"114709\"],[\"10\"])\n","repo_name":"ypmagic/myMovieList","sub_path":"src/main/java/recommend/recommend.py","file_name":"recommend.py","file_ext":"py","file_size_in_byte":2335,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"15"} +{"seq_id":"40735721989","text":"from telegram import Bot\nfrom telegram import Update\nfrom telegram import ParseMode\nfrom telegram import InlineKeyboardButton\nfrom telegram import InlineKeyboardMarkup\nfrom telegram.ext import Updater\nfrom telegram.ext import CommandHandler\nfrom telegram.ext import MessageHandler\nfrom telegram.ext import Filters\nfrom telegram.ext import CallbackQueryHandler\n\nfrom boter.config import TG_TOKEN\n\n# callback_data - це те що верне телеграм при нажатті на кожну кнопку\n#через це кожен ідентифікатор повинен бути унікальним\nCALLBACK_BUTTON1_1000CC = \"callback_button1_1000cc\"\nCALLBACK_BUTTON2_600CC = \"callback_button2_600cc\"\nCALLBACK_BUTTON3_300CC = \"callback_button3_300cc\"\nCALLBACK_BUTTON4_150CC = \"callback_button4_150cc\"\nCALLBACK_BUTTON5_INFO_OF_POWER = \"callback_button5_info_of_power\"\nCALLBACK_BUTTON6_100KM = \"callback_button6_100km\"\nCALLBACK_BUTTON7_200KM = \"callback_button7_200km\"\nCALLBACK_BUTTON8_300KM = \"callback_button8_300km\"\nCALLBACK_BUTTON9_400KM = \"callback_button9_400km\"\nCALLBACK_BUTTON10_500KM = \"callback_button10_500km\"\nCALLBACK_BUTTON11_BACK = \"callback_button11_BACK\"\n\n\nTITLES = {\n CALLBACK_BUTTON1_1000CC: \"1000cc 🏍\",\n CALLBACK_BUTTON2_600CC: \"600cc 🏍\",\n CALLBACK_BUTTON3_300CC: \"300cc 🏍\",\n CALLBACK_BUTTON4_150CC: \"150cc 🏍\",\n CALLBACK_BUTTON5_INFO_OF_POWER: \"Info of power ℹ️\",\n CALLBACK_BUTTON6_100KM: \"100 km 🛣\",\n CALLBACK_BUTTON7_200KM: \"200 km 🛣\",\n CALLBACK_BUTTON8_300KM: \"300 km 🛣\",\n CALLBACK_BUTTON9_400KM: \"400 km 🛣\",\n CALLBACK_BUTTON10_500KM: \"500 km 🛣\",\n CALLBACK_BUTTON11_BACK: \"BACK 🔙\"\n}\n\ndef get_base_inline_keyboard():\n keyboard = [\n [\n InlineKeyboardButton(TITLES[CALLBACK_BUTTON1_1000CC], callback_data=CALLBACK_BUTTON1_1000CC),\n InlineKeyboardButton(TITLES[CALLBACK_BUTTON2_600CC], callback_data=CALLBACK_BUTTON2_600CC),\n InlineKeyboardButton(TITLES[CALLBACK_BUTTON3_300CC], callback_data=CALLBACK_BUTTON3_300CC),\n InlineKeyboardButton(TITLES[CALLBACK_BUTTON4_150CC], callback_data=CALLBACK_BUTTON4_150CC),\n ],\n [\n InlineKeyboardButton(TITLES[CALLBACK_BUTTON5_INFO_OF_POWER],callback_data=CALLBACK_BUTTON5_INFO_OF_POWER),\n ]\n ]\n return InlineKeyboardMarkup(keyboard)\n\ndef get_keyboard():\n keyboard = [\n [\n InlineKeyboardButton(TITLES[CALLBACK_BUTTON6_100KM], callback_data=CALLBACK_BUTTON6_100KM),\n InlineKeyboardButton(TITLES[CALLBACK_BUTTON7_200KM], callback_data=CALLBACK_BUTTON7_200KM),\n InlineKeyboardButton(TITLES[CALLBACK_BUTTON8_300KM], callback_data=CALLBACK_BUTTON8_300KM),\n ],\n [\n InlineKeyboardButton(TITLES[CALLBACK_BUTTON9_400KM], callback_data=CALLBACK_BUTTON9_400KM),\n InlineKeyboardButton(TITLES[CALLBACK_BUTTON10_500KM], callback_data=CALLBACK_BUTTON10_500KM),\n ],\n [\n InlineKeyboardButton(TITLES[CALLBACK_BUTTON11_BACK], callback_data=CALLBACK_BUTTON11_BACK),\n ],\n ]\n return InlineKeyboardMarkup(keyboard)\n\n#@debug_requests\ndef keyboadr_callback_hendler(bot: Bot, update: Update, chat_data=None, **kwargs):\n \"\"\"Обробник УСІХ кнопок з УСІХ клавіатур\n \"\"\"\n query = update.callback_query\n data = query.data\n now = datatime.datatime.now()\n\n chat_id = update.effective_message.chat_id\n current_text = update.effective_message.text\n\n\n\n\n if data == CALLBACK_BUTTON1_1000CC:\n query.edit_message_text(\n text='Please choose range what do you need.',\n reply_markup=get_keyboard(),\n )\n\n bot.send_message(\n chat_id=chat_id,\n text=\"You are choose \\n callback_query.data{}\". format(data),\n reply_markup=get_keyboard(),\n )\n\n elif data == CALLBACK_BUTTON2_600CC:\n query.edit_message_text(\n text='Please choose range what do you need.',\n reply_markup=get_keyboard(),\n )\n\n bot.send_message(\n chat_id=chat_id,\n text=\"You are choose \\n callback_query.data{}\".format(data),\n reply_markup=get_keyboard(),\n )\n\n elif data == CALLBACK_BUTTON3_300CC:\n query.edit_message_text(\n text='Please choose range what do you need.',\n reply_markup=get_keyboard(),\n )\n\n bot.send_message(\n chat_id=chat_id,\n text=\"You are choose \\n callback_query.data{}\".format(data),\n reply_markup=get_keyboard(),\n )\n\n elif data == CALLBACK_BUTTON4_150CC:\n query.edit_message_text(\n text='Please choose range what do you need.',\n reply_markup=get_keyboard(),\n )\n\n bot.send_message(\n chat_id=chat_id,\n text=\"You are choose \\n callback_query.data{}\".format(data),\n reply_markup=get_keyboard(),\n )\n elif data == CALLBACK_BUTTON5_INFO_OF_POWER:\n query.edit_message_text(\n text=current_text,\n parse_mode=ParseMode.MARKDOWN,\n )\n bot.send_message(\n chat_id=chat_id,\n text=\"125 – 150 см3, що приблизно дорівнює 6 - 15 kW (8-25 HP) потужності\\n\\\n 250 – 300 см3, що приблизно дорівнює 20 - 45 kW (25-60 HP) потужності\\n\\\n 500 – 750 см3, що приблизно дорівнює 55 – 80 kW (70-110 HP) потужності\\n\\\n 1000 – 1300 см3, що приблизно дорівнює 90 - 150 kW (120-200 HP) потужності\\n\\\n Ці позиції закривають основні категорії напрямків розробки.\\n\\ncallback_query.data{}\".format(data),\n reply_markup=get_base_inline_keyboard(CALLBACK_BUTTON11_BACK),\n )\n elif data == CALLBACK_BUTTON11_BACK:\n query.edit_message_text(\n text=current_text,\n reply_markup=get_base_inline_keyboard(),\n )\n\n\n\n\n\n\n\ndef do_start(bot: Bot, update: Update):\n bot.send_message(\n chat_id=update.message.chat_id,\n text=\"Hello! Which model do you want to change?\",\n reply_markup=get_base_inline_keyboard()\n )\ndef do_echo(bot: Bot, update: Update):\n chat_id = update.message.chat_id\n text = update.message.text\n if text == BUTTON1_HELP:\n return do_help(bot=bot, update=update)\n elif text == BUTTON2_TIME:\n return do_time(bot=bot, update=update)\n else:\n reply_text = \"Ваш ID = {}\\n\\n{}\".format(chat_id, text)\n bot.send_message(\n chat_id=chat_id,\n text=reply_text,\n reply_markup=get_base_inline_keyboard(),\n )\n\ndef main():\n bot = Bot(\n token=TG_TOKEN,\n )\n updater = Updater(\n bot=bot,\n )\n\n start_handler = CommandHandler(\"start\", do_start)\n message_hendler = MessageHandler(Filters.text, do_echo)\n buttons_handler = CallbackQueryHandler(callback=keyboadr_callback_hendler, pass_chat_data=True)\n\n\n updater.dispatcher.add_handler(start_handler)\n updater.dispatcher.add_handler(message_hendler)\n updater.dispatcher.add_handler(buttons_handler)\n\n\n updater.start_polling()\n updater.idle()\n\nif __name__ =='__main__':\n main()\n\n","repo_name":"BariSmith/telegrambot","sub_path":"venv/boter/main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":7384,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"15"} +{"seq_id":"21848424902","text":"num1, num2 =eval(input(\"请输入两个整数,以逗号隔开:\"))\nnum1 = int(num1)\nnum2 = int(num2)\nif num1 > num2:\n smaller = num2\nelse:\n smaller = num1\nfor i in range(1, smaller+1):\n if(num1 % i == 0 and num2 % i == 0):\n yue = i\nbei = num1 * num2 / yue\nprint(\"两个整数的最大公约数为:{},最大公倍数为:{}。\".format(yue,bei))\n","repo_name":"12ain/Python_Code","sub_path":"基础代码/公约数公倍数计算.py","file_name":"公约数公倍数计算.py","file_ext":"py","file_size_in_byte":368,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"15"} +{"seq_id":"30040133851","text":"\"\"\"\nTitle: 04 Prepare: Checkpoint - Unit Conversion\nAuthor: Leonardo Severo\n\nPurpose: Write a program to convert from Fahrenheit to Celsius. \n\"\"\"\n\n#Prompt\nfahrenheit = float(input(\"What is the temperature in Fahrenheit? \"))\n\n#Calculate\ncelsius = (fahrenheit - 32) * 5/9\n\n#Display\nprint(f\"The temperature in Celsius is {celsius:.1f} degrees.\")\n\n\n\n\n\n\n#Sample solution\n\"\"\"\ndegrees_f = float(input(\"What is the temperature in Fahrenheit? \"))\ndegrees_c = (degrees_f - 32) * 5 / 9\n\nprint(f\"The temperature in Celsius is {degrees_c:.1f} degrees.\")\n\"\"\"","repo_name":"severoleonardo/Python-Exercices","sub_path":"W04 - Solving Problems Using Variables and Expressions/unit_conversion.py","file_name":"unit_conversion.py","file_ext":"py","file_size_in_byte":544,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"15"} +{"seq_id":"40045795987","text":"\"\"\"\r\nPHYS 3142 FINAL RROJECT:\r\n\r\nDiffusion-limited aggregation\r\n\r\nThis file is used to make 2D DLA animation\r\n\r\nParamter:\r\n\tgrid: a simple lattice (cluster)\r\n\tgrid_size: the length of grid length\r\n\tRmax: the maximum distance from the seed to the outermost particle\r\n\tparticlecount: the number of particle in cluster\r\n\tPnn: the sticking probability at the nearest neighbor sites \r\n\tPsnn: the sticking probability at the second nearest neighbor sites \r\n\r\n\"\"\"\r\n### import #########################\r\nimport numpy as np\r\nimport matplotlib.pyplot as plt\r\nimport time\r\nimport imageio\r\nimport os\r\nfrom matplotlib.colors import ListedColormap,LinearSegmentedColormap\r\n####################################\r\n\r\nstart = time.time()\r\n\r\n\r\n\r\n\r\n##############Initialization##################\r\n# initialize Parameters\r\nPnn = 1\r\ngrid_size = 400\r\nnum_particles = 10000\r\nRmax = 3\r\nparticlecount = 0\r\nneedGif = True\r\n# Initialize the grid\r\ngrid = np.zeros((grid_size, grid_size))\r\n\r\n# Place the initial seed in the center\r\ncenter = grid_size // 2\r\ngrid[center, center] = 1\r\n##############################################\r\n\r\n\r\n# function to estimatethat whether a particle aggregate\r\ndef aggregate(x, y):\r\n\tif (grid[x+1][y] == 1) or (grid[x][y+1] == 1) or (grid[x-1][y] == 1) or (grid[x][y-1] == 1):\r\n\t\treturn True\r\n\treturn False\r\ncmap = LinearSegmentedColormap.from_list(\"newocean\",[\"black\",'midnightblue','deepskyblue','cyan','white'])\r\nInterval = []\r\n# simulation of Diffusion-limited aggregation\r\ndef dla(needGif):\r\n\t# global function to update paramter\r\n cmap = LinearSegmentedColormap.from_list(\"newocean\",[\"black\",'midnightblue','deepskyblue','cyan','white'])\r\n intervalSavePic = range(2,10000,250)\r\n global Rmax\r\n global particlecount\r\n k = 0\r\n \r\n\t# ensure there is num_particles in the cluster\r\n while( particlecount < num_particles ):\r\n\r\n\t\t#randomly generate a particle at random pos(x,y)\r\n angle = 2 * np.pi * np.random.rand()\r\n x = center + int((Rmax+5) * np.cos(angle))\r\n y = center + int((Rmax+5) * np.sin(angle))\r\n\r\n\r\n Notkill = True\r\n FLAG = True\r\n # simulate the process of random walk\r\n while FLAG:\r\n\r\n # random walk\r\n rand = int(4 * np.random.random())\r\n if(rand == 0):\r\n x, y = x-1, y\r\n elif(rand == 1):\r\n x, y = x+1, y\r\n elif(rand == 2):\r\n x, y = x, y-1\r\n else:\r\n x, y = x, y+1\r\n \r\n # estimate that whether a particle should be killed(out of 3*Rmax or out of grid)\r\n if not ((0 < x < grid_size - 1 and 0 < y < grid_size - 1) \\\r\n and ((x-center)*(x-center)+(y-center)*(y-center)<(3*Rmax)*(3*Rmax))):\r\n \r\n Notkill = False\r\n break\r\n \r\n\r\n # checking of the nearest neighbor sites is started if \r\n # \tthe particle reaches the distance ð�‘…ð�‘šð�‘Žð�‘¥ + 2 from the cluster\r\n if ((x-center)*(x-center)+(y-center)*(y-center)<=(Rmax+2)*(Rmax+2)):\r\n\r\n\r\n\r\n if (grid[x+1][y] != 0) or (grid[x][y+1] != 0) or (grid[x-1][y] != 0) or (grid[x][y-1] != 0):\r\n \r\n grid[x, y] = (num_particles-particlecount)/num_particles#1 # particle aggregated\r\n Notkill = True \r\n particlecount += 1\r\n\r\n break\t\r\n\r\n # if particle is not killed, update Rmax\r\n if(Notkill):\r\n if abs(x - center) > Rmax or abs(y - center) > Rmax:\r\n Rmax = max(abs(x - center), abs(y - center))\r\n \r\n\r\n if particlecount in intervalSavePic:\r\n print(\"still working, have added \", \" Added to cluster: \", particlecount)\r\n\r\n if needGif:\r\n if particlecount in intervalSavePic:\r\n print(\"save picture\")\r\n Interval.append(particlecount) #append to the used count\r\n label=str(particlecount)\r\n plt.title(\"DLA Cluster\", fontsize=20)\r\n plt.matshow(grid, interpolation='nearest',cmap=cmap)\r\n plt.xlabel(\"$x$\", fontsize=15)\r\n plt.ylabel(\"$y$\", fontsize=15)\r\n plt.savefig(\"images/cluster{}.png\".format(k), dpi=200)\r\n k+=1\r\n plt.close()\r\n\r\n\t\t\r\n\r\n\r\n\r\n# Simulate DLA\r\ndla(True)\r\n\r\nprint(\"Pnn = 1\")\r\nprint(f\"The number of particle in cluster is {particlecount}\")\r\nprint(f\"The simulate cost {time.time()-start}s\")\r\n\r\n#Plot the result\r\nplt.title(\"DLA Cluster\", fontsize=20)\r\nplt.matshow(grid, interpolation='nearest',cmap=cmap)#plt.cm.Blues) #ocean, Paired\r\nplt.xlabel(\"$x$\", fontsize=15)\r\nplt.ylabel(\"$y$\", fontsize=15)\r\nplt.savefig(\"images/cluster.png\", dpi=200)\r\nplt.close()\r\n\r\nif needGif:\r\n with imageio.get_writer('images/movie.gif', mode='I') as writer:\r\n j=0\r\n for i in Interval:\r\n filename=\"images/cluster\"+str(j)+\".png\"\r\n image = imageio.imread(filename)\r\n writer.append_data(image) \r\n j+=1 \r\n image = imageio.imread(\"images/cluster.png\")\r\n writer.append_data(image)\r\n\r\nfor i in Interval:\r\n filename=\"images/cluster\"+str(i)+\".png\"\r\n os.remove(filename)","repo_name":"shepherdhenry/Diffusion-limited-aggregation-DLA","sub_path":"DLA/dla_ani.py","file_name":"dla_ani.py","file_ext":"py","file_size_in_byte":5313,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"15"} +{"seq_id":"37326612269","text":"#Python code for reversestring or palidrome\n\nprint(\"Welcome to Musaif coding world\")\n\ndef palidromeFun():\n s = input(\"Enter value to know it is palidrome or not\\n :\")\n UserInput = s.lower() \n\n if UserInput == UserInput[::-1]:\n print(UserInput, \"Yes given name is palidrome: \")\n \n else:\n print(UserInput,\"Not a palidrome\")\n \n \n \ndef loopFun():\n print(\"Reversing the string: \\n\")\n name1 = input(\"enter the string which your trying to reverse:\\n\")\n name = name1[::-1]\n print(\"Reverse of your value is : \",name)\n \n \n \nloopFun()\npalidromeFun()","repo_name":"Musaif786/python-basic","sub_path":"palidrome.py","file_name":"palidrome.py","file_ext":"py","file_size_in_byte":597,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"15"} +{"seq_id":"3011993104","text":"import datetime as dt\nimport math\nimport typing\n\nimport pytest\n\nfrom src import configuraptor\n\nfrom .constants import _load_toml\n\n\ndef test_example_is_valid_toml():\n data = _load_toml()\n\n assert data\n\n\nclass AbsHasName:\n # can be inherited by other classes with a 'name' attribute.\n name: str\n\n\n# class FirstExtraName:\n# first: str\n# last: str\n#\n#\n# class FirstExtraPoint:\n# x: int\n# y: int\n#\n#\n# class FirstExtraAnimalType(AbsHasName):\n# ...\n#\n#\n# class FirstExtraAnimal:\n# type: FirstExtraAnimalType\n#\n#\n# class FirstExtra:\n# name: FirstExtraName\n# point: FirstExtraPoint\n# animal: FirstExtraAnimal\n\n\nclass First:\n string: str\n list_of_string: list[str]\n list_of_int: list[int]\n list_of_float: list[float]\n list_of_numbers: list[float | int]\n some_boolean: bool\n number: float | int\n not_a_number: math.nan\n datetime: dt.datetime\n datetimes: list[dt.datetime]\n extra: typing.Optional[dict[str, typing.Any]]\n\n\nclass FruitDetails:\n color: str\n shape: str\n\n\nclass FruitVariety(AbsHasName):\n ...\n\n\nclass Fruit(AbsHasName):\n varieties: list[FruitVariety]\n physical: typing.Optional[FruitDetails]\n\n\nclass SecondExtra:\n allowed: bool\n\n\nclass Tool:\n first: First\n fruits: list[Fruit]\n second_extra: SecondExtra\n\n\nclass ToolWithInit(Tool):\n more_props: str\n\n def __init__(self, more_properties: str):\n self.more_props = more_properties\n\n\ndef test_new_instances():\n data = _load_toml()\n\n tool = configuraptor.load_into(ToolWithInit, data, init=dict(more_properties=\"more kwargs\"))\n assert tool.more_props == \"more kwargs\"\n assert tool.fruits\n\n\nclass SomethingWithInit:\n def __init__(self, arg1, arg2, kwarg1, kwarg2=None):\n assert arg1\n assert arg2\n assert kwarg1\n assert kwarg2\n\n\ndef test_mixed_init():\n configuraptor.load_into(\n SomethingWithInit,\n {},\n init=(\n [1, 2],\n dict(\n kwarg1=1,\n kwarg2=2,\n ),\n ),\n )\n\n configuraptor.load_into(\n SomethingWithInit,\n {},\n init=dict(\n arg1=1,\n arg2=2,\n kwarg1=1,\n kwarg2=2,\n ),\n )\n\n configuraptor.load_into(SomethingWithInit, {}, init=[1, 2, 3, 4])\n\n # invalid init:\n with pytest.raises(ValueError):\n configuraptor.load_into(\n SomethingWithInit,\n {},\n init=33,\n )\n\n\ndef test_existing_instances():\n data = _load_toml()\n\n inst1 = ToolWithInit(\"some setup\")\n\n normal_tool = configuraptor.load_into(Tool, data)\n inst1_extended = configuraptor.load_into(inst1, data)\n assert inst1_extended is inst1\n\n assert inst1.fruits\n\n assert inst1_extended.first.extra[\"name\"][\"first\"] == normal_tool.first.extra[\"name\"][\"first\"]\n\n with pytest.raises(ValueError):\n configuraptor.load_into(inst1, data, init=dict(more_properties=\"Should not be allowed!\"))\n","repo_name":"trialandsuccess/configuraptor","sub_path":"tests/test_toml_existing.py","file_name":"test_toml_existing.py","file_ext":"py","file_size_in_byte":2998,"program_lang":"python","lang":"en","doc_type":"code","stars":5,"dataset":"github-code","pt":"15"} +{"seq_id":"3452773727","text":"class Solution:\n def checkInclusion(self, s1: str, s2: str) -> bool:\n s1Count = defaultdict(int)\n s2Count = defaultdict(int)\n left = 0\n for c in s1:\n s1Count[c] += 1\n\n for right in range(len(s2)):\n s2Count[s2[right]] += 1\n if right - left + 1 == len(s1):\n if s2Count == s1Count:\n return True\n\n s2Count[s2[left]] -= 1\n if s2Count[s2[left]] == 0:\n s2Count.pop(s2[left])\n \n left += 1\n\n return False","repo_name":"ante-neh/A2SVCompetetiveProgramming","sub_path":"0567-permutation-in-string/0567-permutation-in-string.py","file_name":"0567-permutation-in-string.py","file_ext":"py","file_size_in_byte":586,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"15"} +{"seq_id":"28111573415","text":"'''\nType seven numbers, insert in a single list;\nThis list separates ODD from EVEN numbers;\nAt the end show all them in crescent order;\nE.g. numbers = [[ODD_num],[EVEN_num]]\nshow separated\n'''\nodd_even_list = [[],[]]\nfor i in range(0,7):\n num = int(input(f'Type the {i+1}º number: '))\n if num%2 == 0:\n odd_even_list[0].append(num)\n else:\n odd_even_list[1].append(num)\norder = sorted(odd_even_list)\nprint(f'The odd and even list ordened is : {order}')\nprint(f'The EVEN list is : {order[1]}')\nprint(f'The ODD list is : {order[0]}')","repo_name":"cristian-santiago/Python","sub_path":"Python-codes-CeV/85-Odd_even_list.py","file_name":"85-Odd_even_list.py","file_ext":"py","file_size_in_byte":551,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"15"} +{"seq_id":"10147928265","text":"import zipfile\nimport tarfile\nimport os\nimport plugin_and_module_param\nimport shutil\n\n\ndef create_folder(folder):\n if not os.path.exists(folder):\n os.makedirs(folder)\n print(\"---new folder[%s] ok ---\\n\" % (folder))\n\n\ndef write_plugin(res_path, plugin):\n # include/AFNamePlugin.hpp\n dir_path = os.path.join(res_path, plugin.lower(),\n plugin_and_module_param.include_path)\n create_folder(dir_path)\n file_middle_name = plugin[0].upper() + plugin[1:]\n print(\"plugin file name = \" + file_middle_name)\n file_name = \"AF\" + file_middle_name + \"Plugin\"\n with open(\n os.path.join(dir_path,\n file_name + plugin_and_module_param.hpp_ext),\n 'w') as f:\n f.write(u'''/*\n * This source file is part of ARK\n * For the latest info, see https://github.com/ArkNX\n *\n * Copyright (c) 2013-2020 ArkNX authors.\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\"),\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n *\n */\n\n#pragma once\n\n#include \"interface/AFIPlugin.hpp\"\n#include \"base/AFPluginManager.hpp\"\n\nnamespace ark {\n\nARK_DECLARE_PLUGIN(AF''' + file_middle_name + '''Plugin)\n\n} // namespace ark''')\n\n # interface\n dir_path = os.path.join(res_path, plugin,\n plugin_and_module_param.interface_path)\n create_folder(dir_path)\n\n # src/AFNamePlugin.cpp\n dir_path = os.path.join(res_path, plugin, plugin_and_module_param.src_path)\n create_folder(dir_path)\n with open(\n os.path.join(dir_path,\n file_name + plugin_and_module_param.cpp_ext),\n 'w') as f:\n f.write(u'''/*\n * This source file is part of ARK\n * For the latest info, see https://github.com/ArkNX\n *\n * Copyright (c) 2013-2020 ArkNX authors.\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\"),\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n *\n */\n\n#include \"''' + plugin.lower() + '''/include/AF''' + file_middle_name +\n '''Plugin.hpp\"\n\nnamespace ark {\n\nARK_DECLARE_PLUGIN_DLL_FUNCTION(AF''' + file_middle_name + '''Plugin)\n\nvoid AF''' + file_middle_name + '''Plugin::Install()\n{\n // install module\n}\n\nvoid AF''' + file_middle_name + '''Plugin::Uninstall()\n{\n // uninstall module\n}\n\n} // namespace ark\n''')\n\n # name/CMakeLists.txt\n with open(\n os.path.join(res_path, plugin.lower(),\n plugin_and_module_param.cmake_file),\n 'w') as f:\n f.write(u'''BUILD_PLUGIN_MACRO(AF''' + file_middle_name + '''Plugin)''')\n\n # plugin/CMakeLists.txt\n f = open(os.path.join(res_path, plugin_and_module_param.cmake_file), 'r')\n lines = []\n for line in f:\n lines.append(line)\n s = \"add_subdirectory(\" + plugin.lower() + \")\"\n if lines[len(lines) - 1].find(s) == -1:\n s = \"\\n\" + s\n lines.append(s)\n s = ''.join(lines)\n f = open(os.path.join(res_path, plugin_and_module_param.cmake_file), 'w+')\n f.write(s)\n f.close()\n del lines[:]\n\n\ndef write_module(module, plugin, res_path):\n # include/AFCNameModule.hpp\n dir_path = os.path.join(res_path, plugin.lower(),\n plugin_and_module_param.include_path)\n module_middle_name = module[0].upper() + module[1:]\n file_name = \"AFC\" + module_middle_name + \"Module\"\n\n with open(\n os.path.join(dir_path,\n file_name + plugin_and_module_param.hpp_ext),\n 'w') as f:\n f.write(u'''/*\n * This source file is part of ARK\n * For the latest info, see https://github.com/ArkNX\n *\n * Copyright (c) 2013-2020 ArkNX authors.\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\"),\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n *\n */\n\n#pragma once\n\n#include \"base/AFPluginManager.hpp\"\n#include \"''' + plugin.lower() + '''/interface/AFI''' + module_middle_name +\n '''Module.hpp\"\n\nnamespace ark {\n\nclass AFC''' + module_middle_name + '''Module final : public AFI''' +\n module_middle_name + '''Module\n{\n ARK_DECLARE_MODULE_FUNCTIONS\npublic:\n // TODO\n\nprivate:\n // TODO\n\n};\n\n} // namespace ark\n\n''')\n\n # interface/AFINameModule.hpp\n dir_path = os.path.join(res_path, plugin.lower(),\n plugin_and_module_param.interface_path)\n file_name = \"AFI\" + module_middle_name + \"Module\"\n\n with open(\n os.path.join(dir_path,\n file_name + plugin_and_module_param.hpp_ext),\n 'w') as f:\n f.write(u'''/*\n * This source file is part of ARK\n * For the latest info, see https://github.com/ArkNX\n *\n * Copyright (c) 2013-2020 ArkNX authors.\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\"),\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n *\n */\n\n#pragma once\n\n#include \"interface/AFIModule.hpp\"\n\nnamespace ark {\n\nclass AFI''' + module_middle_name + '''Module : public AFIModule \n{\npublic:\n //virtual method\n};\n\n} // namespace ark\n\n''')\n\n # src/AFCNameModule.cpp\n dir_path = os.path.join(res_path, plugin.lower(),\n plugin_and_module_param.src_path)\n file_name = \"AFC\" + module_middle_name + \"Module\"\n\n with open(\n os.path.join(dir_path,\n file_name + plugin_and_module_param.cpp_ext),\n 'w') as f:\n f.write(u'''/*\n * This source file is part of ARK\n * For the latest info, see https://github.com/ArkNX\n *\n * Copyright (c) 2013-2020 ArkNX authors.\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\"),\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n *\n */\n\n#include \"''' + plugin.lower() + '''/include/AFC''' + module_middle_name +\n '''Module.hpp\"\n\nnamespace ark {\n //method realization\n\n} // namespace ark\n\n''')\n\n # src/AFNamePlugin.cpp\n file_name = \"AF\" + plugin.capitalize() + \"Plugin\"\n path = os.path.join(dir_path, file_name + plugin_and_module_param.cpp_ext)\n file = open(path, \"r\", encoding=\"utf-8\")\n lines = []\n for line in file:\n lines.append(line)\n\n i = 0\n flag = False\n for line in lines: # 依次读取每行\n i = i + 1\n if not flag and line[0:1] != \"#\":\n continue\n flag = True\n if flag and line[0:1] != \"#\":\n if line == \"\\n\":\n continue\n else:\n break\n lines.insert(\n i - 2, \"#include \\\"\" + plugin + \"/include/AFC\" + module_middle_name +\n \"Module.hpp\\\"\\n\")\n\n for i in range(i, len(lines)):\n i = i + 1\n if lines[i].find(\"Install\") != -1:\n while True:\n i = i + 1\n if lines[i].find(\"}\") != -1:\n break\n lines.insert(\n i, \"\\tARK_REGISTER_MODULE(AFI\" + module_middle_name +\n \"Module, AFC\" + module_middle_name + \"Module);\\n\")\n while True:\n if lines[i].find(\"{\") != -1 and lines[i - 1].find(\n \"Uninstall\") != -1:\n break\n i = i + 1\n i = i + 1\n if lines[i].find(\"// uninstall module\") != -1:\n i = i + 1\n lines.insert(\n i, \"\\tARK_DEREGISTER_MODULE(AFI\" + module_middle_name +\n \"Module, AFC\" + module_middle_name + \"Module);\\n\")\n break\n\n s = ''.join(lines)\n f = open(path, 'w+')\n f.write(s)\n f.close()\n del lines[:]\n \ndef print_success(detail):\n print(\"\\033[32;1m[Succeed] %s\\033[0m\" % detail)\n\ndef print_error(detail):\n print(\"\\033[31;1m[Error] %s\\033[0m\" % detail)\n \nif __name__ == \"__main__\":\n # files = os.listdir(plugin_and_module_param.plugin_path)\n # plugin_list = []\n # for i in files:\n # if i != plugin_and_module_param.cmake_file and i != plugin_and_module_param.readme_file:\n # plugin_list.append(i)\n # # plugin name-id\n # while True:\n # val = input(\n # '\\nplease choose generating plugin type.\\n\\n0. quit\\n\\n1. common plugin\\n\\n2. plugin in specified project\\n\\n3. add module\\n\\nYou choose : '\n # )\n # if val == \"0\":\n # break\n # if val == \"3\":\n # while True:\n # module = input('\\nplease input module name : ')\n # if module.isalpha():\n # s = '\\nPlease choose which plugin is the module served for.\\n\\n0. back\\n\\n1. common plugin\\n\\n2. plugin in specified project\\n\\nYou choose : '\n # plugin_type = input(s)\n # if plugin_type == \"0\":\n # continue\n # else:\n # if plugin_type == \"1\":\n # path = plugin_and_module_param.plugin_path\n # if plugin_type == \"2\":\n # path = plugin_and_module_param.server_path\n # files = os.listdir(path)\n # plugin_list = []\n # for i in files:\n # if i != plugin_and_module_param.cmake_file and i != plugin_and_module_param.readme_file:\n # plugin_list.append(i)\n # s = \"There are such plugins:\\n\\n\"\n # s = s + str(0) + '. ' + 'quit\\n\\n'\n # for i in range(0, len(plugin_list)):\n # s = s + str(i + 1) + '. ' + plugin_list[i] + '\\n\\n'\n # s = s + 'You choose : '\n # plugin = input(s)\n # if int(plugin) in range(1, len(plugin_list) + 1):\n # write_module(module, plugin_list[int(plugin) - 1],\n # path)\n # break\n # else:\n # if int(plugin) == 0:\n # break\n # else:\n # print(\"Please choose correct number.\\n\")\n # break\n # if val == \"1\":\n # res_path = plugin_and_module_param.plugin_path\n # print(\"res_path: \" + res_path)\n # while True:\n # val = input('\\nplease input plugin name : ')\n # if val.isalpha():\n # print(\"plugin %s start to generate --------\" % (val))\n # write_plugin(res_path, val)\n # break\n # if val == \"2\":\n # res_path = plugin_and_module_param.server_path\n # print(\"res_path: \" + res_path)\n # while True:\n # val = input('\\nplease input plugin name : ')\n # if val.isalpha():\n # print(\"plugin %s start to generate --------\" % (val))\n # write_plugin(res_path, val)\n # break\n\n plugin_dirs = plugin_and_module_param.plugin_dir.split(\",\")\n for i, val in enumerate(plugin_dirs):\n plugin_dirs[i] = os.path.join(plugin_and_module_param.base_dir, val)\n\n while True:\n print('\\n--------------------------------------------------------------------------------------------\\nPlugin dir List: ')\n for i, val in enumerate(plugin_dirs):\n print(\" %s -> %s\" % (i, val))\n val = input(\n '\\nUsage : [(split by `,`)]' +\n '\\n eg: add 0 plugin -> add a plugin' +\n '\\n eg: add 1 plugin module1,module2 -> add some modules, plugin will be created if not exist' +\n '\\n\\nInput: '\n )\n \n inputList = val.split()\n if (len(inputList) < 3) or (len(inputList) > 4):\n print_error(\"format error for command : `%s`\" % (val))\n continue\n\n if inputList[0] == \"add\":\n plugin_dir = \"\"\n plugin_name = inputList[2]\n module_names = []\n\n # get the plugin dir\n try:\n plugin_dir_index = int(inputList[1])\n if plugin_dir_index > len(inputList):\n print_error(\"overflow for arg : %d \\nmax index is %d\" % (plugin_dir_index, len(inputList)-1))\n continue\n plugin_dir = plugin_dirs[plugin_dir_index]\n except Exception:\n print_error(\"non-int for arg : `%s`\" % (inputList[1]))\n continue\n\n # get modules\n if len(inputList) == 4:\n module_names = inputList[3].split(\",\")\n # deduplication\n list(filter(lambda x:module_names.count(x) == 1, module_names))\n \n # build plugin if not exist \n if not os.path.exists(os.path.join(plugin_dir, plugin_name.lower())):\n write_plugin(plugin_dir, plugin_name)\n\n # build modules\n for module in module_names:\n write_module(module, plugin_name, plugin_dir)\n \n print_success('build success')\n else:\n print_error(\"invalid arg : `%s`\" % (inputList[0]))\n\n","repo_name":"OpenArkStudio/ARK","sub_path":"build/tools/plugin_and_module_tool/plugin_and_module_tool.py","file_name":"plugin_and_module_tool.py","file_ext":"py","file_size_in_byte":15394,"program_lang":"python","lang":"en","doc_type":"code","stars":431,"dataset":"github-code","pt":"15"} +{"seq_id":"38806553520","text":"\"\"\"utilities for tests\"\"\"\n\nimport numpy as np\nimport xarray as xr\n\n\ndef get_obj(mode: int) -> xr.DataArray | xr.Dataset:\n rng = np.random.RandomState(0)\n\n if mode in {0, 1}: # 0 = 1D, 1 = 3D\n ndim = 1 if mode == 0 else 3\n dims = [\"x\", \"y\", \"z\"]\n shapes = [9, 12, 15]\n coords = {\"x\": np.arange(shapes[0]) * 0.2}\n if ndim >= 2:\n coords[\"z\"] = np.linspace(0, 1, shapes[2])\n coords[\"time\"] = (\"x\",), np.linspace(0, 1, shapes[0])\n da = xr.DataArray(rng.randn(*shapes[:ndim]), dims=dims[:ndim], coords=coords)\n da.attrs[\"comment\"] = \"dummy comment.\"\n # scalar coordinate\n da[\"scalar\"] = 3.141592\n return da\n elif mode == 2:\n da = get_obj(mode=1)\n return da.chunk({\"x\": 5, \"y\": 4, \"z\": 5})\n elif mode == 3:\n ds = xr.Dataset({})\n ds[\"a\"] = get_obj(mode=0)\n ds[\"b\"] = get_obj(mode=1)\n return ds\n elif mode == 5:\n return get_obj(mode=1)\n","repo_name":"hippalectryon-0/xr-scipy","sub_path":"tests/testings.py","file_name":"testings.py","file_ext":"py","file_size_in_byte":980,"program_lang":"python","lang":"en","doc_type":"code","stars":56,"dataset":"github-code","pt":"15"} +{"seq_id":"32445147373","text":"from rest_framework import viewsets\nfrom rest_framework.views import APIView\nfrom rest_framework.response import Response\nfrom rest_framework.parsers import JSONParser\nfrom rest_framework.renderers import JSONRenderer\nfrom django.http import Http404\nfrom rest_framework import status\nfrom movies.models import Genre, Movie, MovieRole\nfrom rest_framework import exceptions\nfrom movies.serializers import GenreSerializer, MovieSerializer, MovieRoleSerializer\nfrom role.decorators import iam\nimport logging\nLOGGER = logging.getLogger(__name__)\n\n\nclass BaseAPIView(APIView):\n parser_classes = (JSONParser,)\n renderer_classes = (JSONRenderer,)\n\nclass GenreAPIView(BaseAPIView):\n \"\"\"\n APIView for Genre CRUD\n \"\"\"\n def get_object(self, id):\n try:\n return Genre.objects.get(id = id)\n except Genre.DoesNotExist:\n raise exceptions.ValidationError({\"success\": False,\n \"error\": {\n \"genre_errors\": [\n \"genre details not found\"\n ]\n }\n })\n\n def get(self, request):\n id = request.query_params.get('genre_id',None)\n if id:\n genre = self.get_object(id)\n serializer = GenreSerializer(genre)\n else:\n genre = Genre.objects.all()\n serializer = GenreSerializer(genre, many=True)\n \n return Response({'data':serializer.data,'success':True}, status=status.HTTP_200_OK)\n\n def post(self, request, format=None):\n serializer = GenreSerializer(data=request.data)\n if serializer.is_valid():\n try:\n serializer.save()\n except:\n return Response({'error':serializer.errors, 'success':False}, status=status.HTTP_400_BAD_REQUEST)\n return Response({'data':serializer.data,'success':True}, status=status.HTTP_201_CREATED)\n return Response({'error':serializer.errors, 'success':False}, status=status.HTTP_400_BAD_REQUEST)\n\n def put(self, request,format=None):\n id = request.data.get('genre_id',None)\n genre = self.get_object(id)\n if genre:\n serializer = GenreSerializer(genre, data=request.data)\n if serializer.is_valid():\n serializer.save()\n return Response({'data':serializer.data,'success':True}, status=status.HTTP_200_OK)\n return Response({'error':serializer.errors, 'success':False}, status=status.HTTP_400_BAD_REQUEST)\n\n def delete(self, request, format=None):\n id = request.data.get('genre_id',None)\n genre = self.get_object(id)\n if genre:\n genre.delete()\n return Response({'success':True},status=status.HTTP_204_NO_CONTENT)\n return Response({'error':{'genre':[\"NOT PRESENT\"]}, 'success':False}, status=status.HTTP_400_BAD_REQUEST)\n\n\nclass MovieAPIView(BaseAPIView):\n \"\"\"\n APIView for Movie CRUD\n \"\"\"\n def get_object(self, id):\n try:\n return Movie.objects.get(id=id, is_active = True)\n except Movie.DoesNotExist:\n raise exceptions.ValidationError({\"success\": False,\n \"error\": {\n \"movie_errors\": [\n \"movie details not found\"\n ]\n }\n })\n\n \n @iam(permission = 'read_movie')\n def get(self, request, auth, format=None, *args, **kwargs):\n id = request.query_params.get('movie_id',None)\n role_exists = Movie.objects.filter(role__permission__slug = \"read_movie\", role__user_role__id = auth['user_id'], is_active = True)\n if id:\n role_exists = role_exists.filter(id = id)\n if auth['is_admin'] or role_exists.exists():\n movie = self.get_object(id)\n serializer = MovieSerializer(movie)\n else:\n return Response({'data':[],'success':True}, status=status.HTTP_200_OK)\n\n else:\n if auth['is_admin']:\n movie = Movie.objects.filter(is_active = True)\n else:\n movie = role_exists.distinct('id')\n serializer = MovieSerializer(movie, many=True)\n \n return Response({'data':serializer.data,'success':True}, status=status.HTTP_200_OK)\n\n @iam(permission = 'create_movie')\n def post(self, request, auth, format=None, *args, **kwargs):\n serializer = MovieSerializer(data=request.data)\n if serializer.is_valid():\n serializer.save()\n return Response({'data':serializer.data,'success':True}, status=status.HTTP_201_CREATED)\n return Response({'error':serializer.errors, 'success':False}, status=status.HTTP_400_BAD_REQUEST)\n\n @iam(permission = 'update_movie') \n def put(self, request, auth, format=None, *args, **kwargs):\n id = request.data.get('movie_id',None)\n movie = self.get_object(id)\n serializer = MovieSerializer(movie, data=request.data)\n if movie:\n role_exists = Movie.objects.filter(role__permission__slug = \"update_movie\", role__user_role__id = auth['user_id'], id=id, is_active= True ).distinct('id')\n if auth['is_admin'] or role_exists.exists() :\n\n if serializer.is_valid():\n # try:\n serializer.save()\n # except Exception as e:\n # Response({'error':e.message, 'success':False}, status=status.HTTP_400_BAD_REQUEST)\n return Response({'data':serializer.data,'success':True}, status=status.HTTP_200_OK)\n return Response({'error':{'unauthorized':[\"UNAUTHORIZED USER\"]}, 'success':False}, status=status.HTTP_400_BAD_REQUEST) \n return Response({'error':{'movie':[\"NOT PRESENT\"]}, 'success':False}, status=status.HTTP_400_BAD_REQUEST)\n\n\n @iam(permission = 'delete_movie') \n def delete(self, request, auth, format=None, *args, **kwargs):\n id = request.data.get('movie_id',None)\n movie = self.get_object(id)\n if movie :\n role_exists = Movie.objects.filter(role__permission__slug = \"delete_movie\", role__user_role__id = auth[\"user_id\"], id=id, is_active= True ).distinct('id')\n if auth['is_admin'] or role_exists.exists() :\n movie.is_active = False\n movie.save()\n return Response({'success':True})\n else:\n return Response({'error':{'unauthorized':[\"UNAUTHORIZED USER\"]}, 'success':False}, status=status.HTTP_400_BAD_REQUEST) \n return Response({'error':{'movie':[\"NOT PRESENT\"]}, 'success':False}, status=status.HTTP_400_BAD_REQUEST)\n\nclass MovieRoleAPIView(BaseAPIView):\n \"\"\"\n APIView for MovieRole CRUD\n \"\"\"\n def get_object(self, role_id, movie_id):\n try:\n return MovieRole.objects.get(role_id = role_id, movie_id = movie_id)\n except MovieRole.DoesNotExist:\n raise exceptions.ValidationError({\"success\": False,\n \"error\": {\n \"movie_role_errors\": [\n \"Movie-Role details not found\"\n ]\n }\n })\n\n @iam(permission = 'read_movie_role')\n def get(self, request, auth, format=None, *args, **kwargs):\n role_id = request.query_params.get('role_id',None)\n movie_id = request.query_params.get('movie_id',None)\n if role_id and movie_id:\n movie_role = self.get_object(role_id,movie_id)\n serializer = MovieRoleSerializer(movie_role)\n else:\n movie_role = MovieRole.objects.all()\n serializer = MovieRoleSerializer(movie_role, many=True)\n \n return Response({'data':serializer.data,'success':True}, status=status.HTTP_200_OK)\n\n @iam(permission = 'create_movie_role')\n def post(self, request, auth, format=None, *args, **kwargs):\n serializer = MovieRoleSerializer(data=request.data)\n # print request.data\n # print serializer.is_valid()\n if serializer.is_valid():\n serializer.save()\n return Response({'data':serializer.data,'success':True}, status=status.HTTP_201_CREATED)\n return Response({'error':serializer.errors, 'success':False}, status=status.HTTP_400_BAD_REQUEST)\n\n @iam(permission = 'delete_movie_role') \n def delete(self, request, auth, format=None, *args, **kwargs):\n role_id = request.data.get('role_id',None)\n movie_id = request.data.get('movie_id',None)\n movie_role = self.get_object(role_id,movie_id)\n if movie_role:\n movie_role.delete()\n return Response({'success':True})\n return Response({'error':{'movie-role':[\"NOT PRESENT\"]}, 'success':False}, status=status.HTTP_400_BAD_REQUEST)\n","repo_name":"nanubau/imdb_role","sub_path":"movies/v1/views.py","file_name":"views.py","file_ext":"py","file_size_in_byte":8798,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"15"} +{"seq_id":"31325749412","text":"from tkinter import*\r\nfrom tkinter import ttk\r\nfrom tkinter import messagebox\r\n\r\n\r\nGUI=Tk()\r\nGUI.title('โปรแกรมบันทึกข้อมูล')#ชื่อหน้าต่าง\r\nGUI.geometry('400x400') #ขนาด\r\n\r\nL1=Label(GUI,text='โปรแกรมบันทึกข้อมูล')\r\nL1.place(x=130,y=20) #ตำแหน่งตัวหนังสือ\r\n\r\n#สร้างชื่อปุ่ม\r\n#B1= Frame(GUI)\r\n#B1.place(x=100, y=80)\r\n#B2= ttk.Button(B1,text='วันนี้วันอะไร')\r\n#B2.pack(ipadx=20,ipady=20)\r\n\r\n#กดแล้วมีข้อความออกมา\r\ndef Button2():\r\n text= 'วันอังคาร'\r\n messagebox.showinfo(text)\r\n\r\nB1= Frame(GUI)\r\nB1.place(x=100, y=80)\r\n\r\nB2= ttk.Button(B1,text='วันนี้วันอะไร',command=Button2)\r\nB2.pack(ipadx=20,ipady=20)\r\n\r\n#วิชาที่เรียน\r\ndef Button3():\r\n text= 'คณิต,ไทย'\r\n messagebox.showinfo('วิชาที่เรียนวันนี้',text)\r\n \r\nB2= Frame(GUI)\r\nB2.place(x=100, y=180)\r\nB3= ttk.Button(B1,text='เรียนวิชาอะไร',command=Button3)\r\nB3.pack(ipadx=20,ipady=20)\r\n\r\n#เวลลาเลิกเรียน\r\ndef Button4():\r\n text= '15.00 น.'\r\n messagebox.showinfo('เวลาเลิกเรียน',text)\r\n\r\nB3= Frame(GUI)\r\nB3.place(x=100,y=250)\r\nB4= ttk.Button(B1,text='เลิกเรียนกี่โมง',command=Button4)\r\nB4.pack(ipadx=20,ipady=20)\r\n\r\n\r\n#โปรแกรมพิเศษ\r\ndef Button5():\r\n text= 'ดูหนัง'\r\n messagebox.showinfo('โปรแกรมพิเศษ',text)\r\n\r\nB4= Frame(GUI)\r\nB4.place(x=100,y=350)\r\nB5= ttk.Button(B1,text='มีโปรแกรมพิเศษไหม?',command=Button5)\r\nB5.pack(ipadx=20,ipady=20)\r\n\r\n\r\n\r\n\r\n","repo_name":"SirinyaTL/python101","sub_path":"ep2/GUI knowledge2.py","file_name":"GUI knowledge2.py","file_ext":"py","file_size_in_byte":1878,"program_lang":"python","lang":"th","doc_type":"code","stars":0,"dataset":"github-code","pt":"15"} +{"seq_id":"41624164334","text":"# Working correctly\n\nimport csv\nimport re\nimport pandas as pd\n\n# Open the input log file\ninput_file = '/Users/anas/Documents/UoR/MSc Project/Report/Logs/20230301_anon.log'\noutput_file = '/Users/anas/Documents/UoR/MSc Project/Report/Logs/logtxt.csv'\n\n# Create a dataframe\ndata = pd.DataFrame()\n\ndef read_log_file(input_file, data):\n with open(input_file, 'r') as file, open(output_file, 'w', newline='') as csvfile:\n # Create a CSV writer\n writer = csv.writer(csvfile)\n # Read each line\n for line in file:\n # Use regular expressions to extract keys and values\n matches = re.findall(r'\\$([\\w-]+)=\\'([\\w\\-:]+)\\'', line)\n if matches:\n record = {}\n for match in matches:\n key = match[0]\n value = match[1]\n record[key] = value\n \n # Append record to the data frame\n data = pd.concat([data, pd.DataFrame([record])], ignore_index=True)\n\n # Write the data frame to csv file \n \"\"\" if writer is not None:\n if csvfile.tell() == 0:\n writer.writerow(record.keys())\n writer.writerow(record.values())`\n \"\"\"\n return data\n\ndf = read_log_file(input_file, data)\nprint(df.info())\n# # Introducing multi processing\n# import re\n# import csv\n# import pandas as pd\n# from concurrent.futures import ThreadPoolExecutor, as_completed\n# import time\n# import threading\n\n# # Create an empty DataFrame\n# data = pd.DataFrame()\n\n# # Function to process each line and extract key-value pairs\n# def process_line(line):\n# matches = re.findall(r\"\\$(\\w+)='([^']*)'\", line)\n# if matches:\n# record = {}\n# for match in matches:\n# key = match[0]\n# value = match[1]\n# record[key] = value\n# return record\n\n# # Open the input file and create the output CSV file\n# start_time = time.time()\n\n# input_file = '/Users/anas/Documents/UoR/MSc Project/Report/Logs/20230301_anon.log'\n# output_file = '/Users/anas/Documents/UoR/MSc Project/Report/Logs/logtxt.csv'\n\n# with open(input_file, 'r') as file, open(output_file, 'w', newline='') as csvfile:\n# # Create a CSV writer\n# writer = csv.writer(csvfile)\n \n# # Create a thread pool executor with 1000 threads\n# with ThreadPoolExecutor(max_workers=50) as executor:\n# # Process each line using threads\n# futures = []\n# lock = threading.Lock()\n# counter = 0\n \n# for line in file:\n# future = executor.submit(process_line, line)\n# future.line = line # Attach the line to the future for error reporting\n \n# with lock:\n# counter += 1\n\n# futures.append(future)\n \n# # Write header to the CSV file\n# header_written = False\n \n# # Iterate over the futures and write to CSV file\n# for future in as_completed(futures):\n# try:\n# result = future.result()\n# if result:\n# # Append the record to the DataFrame\n# # data = data.append(result, ignore_index=True)\n \n# # Write header and values to the CSV file\n# if writer is not None:\n# if not header_written:\n# writer.writerow(result.keys()) # Write header once\n# header_written = True\n# writer.writerow(result.values()) # Write values\n \n# except Exception as e:\n# print(f\"An error occurred while processing line: {future.line}\")\n# print(f\"Error: {str(e)}\")\n \n# with lock:\n# counter -= 1\n# if counter == 0:\n# break\n\n# # Display the DataFrame\n# print(data)\n\n# # Calculate execution time\n# end_time = time.time()\n# execution_time = end_time - start_time\n# print(f\"Execution time: {execution_time} seconds\")","repo_name":"ibnaleem/ECMWF-Query-Prediction","sub_path":"MultiprocessingFileReadingAndWriting.py","file_name":"MultiprocessingFileReadingAndWriting.py","file_ext":"py","file_size_in_byte":4158,"program_lang":"python","lang":"en","doc_type":"code","dataset":"github-code","pt":"15"} +{"seq_id":"18570355838","text":"import requests as r\nimport json\nurl = 'https://r0.nzcsc.org.nz/challenge7/'\n\nheaders = {\n \"Content-Type\": \"application/x-www-form-urlencoded\",\n \"Host\": \"r0.nzcsc.org.nz\",\n \"Origin\": \"https://r0.nzcsc.org.nz\",\n \"Referer\": \"https://r0.nzcsc.org.nz/challenge7/\",\n \"User-Agent\": \"Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/83.0.4103.61 Safari/537.36\"\n}\n\n\ndef print_res(command):\n resp = r.post(url, data=get_data(command), headers=headers)\n text = resp.text # type: str\n table = text[text.index(\"\") + 7: text.index(\"
\")]\n table = table.replace('', \"\")\n table = table.replace(\"\", \" \").replace(\"\", \"\").replace(\"\", \"\").replace(\"\", \"\")\n print(\"--------start--------\")\n for row in table.split(\"\"):\n print(row)\n print(\"--------done---------\")\n\n\ndef get_res(name, table, where = None):\n if where is not None:\n whereq = f' WHERE {where}'\n else:\n whereq = ''\n q = f'fakename\\' UNION ALL SELECT 1,2,3,4,{name} from {table}{whereq};-- '\n print(q)\n resp = r.post(url, data=get_data(q), headers=headers)\n text = resp.text # type: str\n table = text[text.index(\"\") + 7: text.index(\"
\")]\n table = table.replace('', \"\")\n table = table.replace(\"\", \" \").replace(\"\", \"\").replace(\"\", \"\").replace(\"\", \"\")\n data = []\n for row in table.split(\"\")[1:]:\n data.append(row.split(' ')[3])\n return data\n\n# andrew' UNION ALL SELECT 1, id, surname, admin_no, school from tsebehtsiworc; --\ndef main3():\n while 1:\n try:\n print_res(input('Enter search: '))\n except Exception as e:\n print(e)\n\n\ndef main():\n print('getting tables')\n tables = get_res('table_name', 'information_schema.tables')\n print(tables)\n table_cols = {}\n for table_name in tables:\n try:\n cols = get_res('column_name', 'information_schema.columns', f'table_name=\"{table_name}\"')\n table_cols[table_name] = cols\n except:\n pass\n print(table_cols)\n\n\ndef get_data(fname):\n return f'firstn={fname}&subit=Check'\n\n\nif __name__ == '__main__':\n main()\n","repo_name":"Samdaaman/Cyber-Security","sub_path":"Previous Challenges/2020-NZCSC/Round0/c7.py","file_name":"c7.py","file_ext":"py","file_size_in_byte":2260,"program_lang":"python","lang":"en","doc_type":"code","stars":2,"dataset":"github-code","pt":"15"} +{"seq_id":"13567496621","text":"#!/usr/bin/env python3\n# -*- coding: utf-8 -*-\n\n__author__ = 'komorebi'\n\nimport tkinter as tk\nfrom tkinter import ttk, messagebox\nfrom tkinter.filedialog import askopenfilename, asksaveasfile\nfrom PIL import ImageTk, Image, ImageFont, ImageDraw\nimport os\n\n\nclass ImageWaterMark:\n\n def __init__(self, master):\n self.master = master\n master.title(\"Image Watermark Desktop\")\n self.upload_button = tk.Button(\n master, text='Upload', command=self.upload)\n self.upload_button.grid(column=0, row=0)\n self.canvas = tk.Canvas(width=200, height=200) # set canvas size\n self.canvas.grid(column=0, row=1, columnspan=3)\n self.img = None\n self.img_copy = None\n self.image_on_canvas = None\n self.add_wt_success = 0 # marks whether the watermark added successfully\n\n self.input_label = tk.Label(master, text='Watermark:')\n self.input_label.grid(column=0, row=2)\n\n self.input_entry = tk.Entry(master)\n self.input_entry.grid(column=1, row=2)\n\n self.add_button = tk.Button(\n master,\n text='Add Watermark',\n command=self.add_watermark)\n self.add_button.grid(column=2, row=2)\n\n self.download_button = tk.Button(\n master, text='Download', command=self.save)\n self.download_button.grid(column=0, row=3)\n\n def upload(self):\n f_types = [('Jpg Files', '*.jpg'), ('Png Files', '*.png'),\n ('Bmp Files', '*.bmp')] # supported file\n # open file choose dialog and return the selected filename\n filename = askopenfilename(filetypes=f_types)\n img = Image.open(filename) # return an image object\n img_resized = img.resize((200, 200)) # resize img\n self.img_copy = img_resized.copy()\n self.img_copy.filename = filename\n self.img = ImageTk.PhotoImage(img_resized)\n # the center of the img will locate at 100,100\n self.image_on_canvas = self.canvas.create_image(\n 100, 100, image=self.img)\n\n # tkinter PhotoImage does not support jpg, so we need to use\n # PIL.ImageTk.PhotoImage\n # self.img = ImageTk.PhotoImage(file=filename) # return an image object\n # self.canvas.create_image(100, 100, image=self.img)\n\n def get_watermark(self):\n if not self.img:\n messagebox.showerror(\n title='error',\n message='Please upload photo first!')\n else:\n watermark = self.input_entry.get()\n if len(watermark) == 0:\n messagebox.showerror(\n title='error', message='Please fill watermark!')\n else:\n return watermark\n\n def add_watermark(self):\n wt = self.get_watermark()\n font = ImageFont.truetype('Symbol.ttf', 20) # set font\n draw = ImageDraw.Draw(self.img_copy)\n draw.text((10, 10), wt, (255, 255, 255), font=font) # add watermark\n self.img = ImageTk.PhotoImage(self.img_copy)\n self.canvas.itemconfig(\n self.image_on_canvas,\n image=self.img) # update canvas image\n self.add_wt_success = 1\n\n def save(self):\n if self.add_wt_success == 1:\n img_name_list = os.path.split(self.img_copy.filename)[1].split('.')\n self.img_copy.filename = img_name_list[0] + \\\n '_wt.' + img_name_list[1] # rename photo\n file = asksaveasfile(initialfile=self.img_copy.filename)\n self.img_copy.save(file.name) # save img to path selected by user\n else:\n messagebox.showerror(\n title='error',\n message='Pleas add watermark first!')\n\n\nroot = tk.Tk()\nimage_watermark = ImageWaterMark(root)\nroot.mainloop()\n","repo_name":"lost-komorebi/100-days-of-code","sub_path":"(Day_84)Image_watermark_desktop/main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":3777,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"15"} +{"seq_id":"36227268542","text":"#!/usr/bin/env python\n'''Script for making sure all the AHF files we need exist.\n\n@author: Zach Hafen\n@contact: zachary.h.hafen@gmail.com\n@status: Development\n'''\n\nimport os\nimport sys\n\nimport galaxy_dive.read_data.ahf as read_ahf\n\n########################################################################\n# Input Paramaters\n########################################################################\n\n# Get the directory the AHF data is in\nsdir = os.path.abspath( sys.argv[1] )\n\n# Get the indices\nsnum_start = int( sys.argv[2] )\nsnum_end = int( sys.argv[3] )\nsnum_step = int( sys.argv[4] )\n\nif len( sys.argv ) > 5:\n file_str = sys.argv[5]\nelse:\n file_str = 'AHF_halos'\n\n########################################################################\n# Perform the calculation.\n########################################################################\n\nahf_reader = read_ahf.AHFReader( sdir )\nassert ahf_reader.check_files_exist( snum_start, snum_end, snum_step, file_str )\n\n","repo_name":"agurvich/ahf_wrapper","sub_path":"check_ahf_files_exist.py","file_name":"check_ahf_files_exist.py","file_ext":"py","file_size_in_byte":965,"program_lang":"python","lang":"de","doc_type":"code","stars":0,"dataset":"github-code","pt":"15"} +{"seq_id":"20546849567","text":"import matplotlib.pyplot as plt\nimport numpy as np\nimport xarray as xr\nimport matplotlib\nimport cartopy.crs as ccrs\n\n\ndef creatimg():\n matplotlib.use('Agg')\n\n plt.rcParams.update({'font.size': 20})\n plt.rcParams['font.sans-serif'] = ['SimHei']\n plt.rcParams['axes.unicode_minus'] = False\n\n file_path = \"./nc_data/2022-12-12/gfs.t00z.pgrb2.0p25_1hr.f002.nc\"\n ds = xr.open_dataset(file_path)\n\n lat = ds.latitude\n lon = ds.longitude\n\n temp = (ds['temperature'][:].T - 273.15)\n pres = ds['pressure'][:].T\n # prec = ds['precipitation'][:].T\n wind = ds['wind'][:].T\n\n levels1 = np.arange(-60, 65, 1)\n levels2 = np.arange(40000, 120000, 10000)\n # levels3 = np.arange(0, 50, 1)\n levels4 = np.arange(0, 50, 1)\n proj = ccrs.Mercator(central_longitude=125.0)\n # proj = ccrs.WGS84_SEMIMAJOR_AXIS(central_longitude=0)\n\n fig = plt.figure(figsize=[10, 8], facecolor='none')\n ax = fig.add_axes([0, 0, 1, 1], projection=proj)\n ax.contourf(temp, levels=levels1, cmap='Spectral_r')\n plt.axis('off')\n plt.savefig(\"./figure/temp.png\", bbox_inches='tight', pad_inches=0)\n plt.close()\n\n fig = plt.figure(figsize=[10, 8], facecolor='none')\n ax = fig.add_axes([0, 0, 1, 1], projection=proj)\n ax.contourf(pres, levels=levels2, cmap='Spectral_r')\n plt.axis('off')\n plt.savefig(\"./figure/pres.png\", bbox_inches='tight', pad_inches=0)\n plt.close()\n\n # fig = plt.figure(figsize=[10, 8], facecolor='none')\n # ax = fig.add_axes([0, 0, 1, 1], projection=proj)\n # ax.contourf(prec, levels=levels3, cmap='Spectral_r')\n # plt.axis('off')\n # plt.savefig(\"../../statics/qqfy/images/0{}/prec.png\", bbox_inches='tight', pad_inches=0)\n # plt.close()\n\n fig = plt.figure(figsize=[10, 8], facecolor='none')\n ax = fig.add_axes([0, 0, 1, 1], projection=proj)\n ax.contourf(wind, levels=levels4, cmap='Spectral_r')\n plt.axis('off')\n plt.savefig(\"./figure/wind.png\", bbox_inches='tight', pad_inches=0)\n plt.close()\n\n\nif __name__ == '__main__':\n creatimg()\n","repo_name":"ZhouYao0627/deep-learning-for-image-processing-master","sub_path":"Project/creatimg1_ok.py","file_name":"creatimg1_ok.py","file_ext":"py","file_size_in_byte":2036,"program_lang":"python","lang":"en","doc_type":"code","stars":5,"dataset":"github-code","pt":"15"} +{"seq_id":"20621367952","text":"import torch\nimport torch.nn as nn\nimport torch.optim as optim\nimport gensim\nimport pickle\nimport time\nimport numpy\nfrom tqdm import tqdm\nimport os\nimport torch.utils.data as data\nfrom torch.utils.data import TensorDataset\nfrom torch.utils.data import DataLoader\nfrom perf_model import LogRobustModel, BiLSTM, AC_BiLSTM, Time_BiLSTM\nimport numpy as np\nimport argparse\nfrom sklearn.preprocessing import MinMaxScaler\n\nos.environ['CUDA_VISIBLE_DEVICES']='2'\ndevice = torch.device('cuda' if torch.cuda.is_available() else 'cpu')\n#device = torch.device('cpu')\nwindow_size = 10 # sequence window length\n# embed_dim = 300\nnum_classes = 3\n# input_size = embed_dim # input vector length\nhidden_size = 128 # sequence embedding size\nnum_layers = 1\nnum_epochs = 30\nbatch_size = 32\nattention_size = 16\nmodel_dir = 'model'\ntime_dim = 1\n#bidirectional = True\nlog = 'Adam_batch_size=' + str(batch_size) + ';epoch=' + str(num_epochs) + 'blk'\n\n\nclass SeqDataset(data.Dataset):\n def __init__(self, normalFN, abnormalFN, perfFN, s2vFN):\n self.num_sessions = 0\n self.inputs = []\n self.outputs = []\n self.lengths = []\n self.timedelta = []\n # normalFN = 'my_hdfs_train_normal'\n # abnormalFN = 'my_hdfs_train_abnormal'\n #if not perf:\n self.cnt = 0\n self.time_sum = 0\n self.s2v = pickle.load(open(s2vFN, 'rb'))\n #self.s2va = pickle.load(open('data/my_dataset/LogInsight_merged_hdfs_bert_cased_ori.pkl', 'rb'))\n # seq_dataset = get_dataset('my_hdfs_train_normal', 'my_hdfs_train_abnormal', s2v)\n self.dataLabeled(normalFN, 0)\n self.dataLabeled(abnormalFN, 1)\n self.dataLabeled(perfFN, 2)\n #import pdb; pdb.set_trace()\n # record by list, following time labeled should follow the same order \n self.time_dataLabeled(normalFN + '_time')\n self.time_dataLabeled(abnormalFN + '_time')\n self.time_dataLabeled(perfFN + '_time')\n #print('max inputs length: ', max(len(self.inputs[i]) for i in range(len(self.inputs))))\n self.standardscaler()\n # return inputs, outputs\n # mms = MinMaxScaler()\n # self.timedelta = mms.fit_transform(self.timedelta)\n def standardscaler(self):\n mean = self.time_sum / self.cnt\n se = 0\n for i in self.timedelta:\n for j in i:\n se += (j - mean) ** 2\n se = np.sqrt(se / (self.cnt - 1))\n \n for i in range(len(self.timedelta)):\n for j in range(len(self.timedelta[i])):\n scale = (self.timedelta[i][j] - mean) / se\n self.timedelta[i][j] = scale\n \n def __getitem__(self, index):\n return torch.tensor(self.inputs[index]), torch.tensor(self.timedelta[index]), torch.tensor(self.outputs[index]), torch.tensor(self.lengths[index])\n\n\n def __len__(self):\n # You should change 0 to the total size of your dataset.\n return len(self.outputs)\n\n def dataLabeled(self, FN, label):\n with open(FN, 'r') as f:\n for line in tqdm(f.readlines()):\n self.num_sessions += 1\n line = tuple(map(lambda n: n - 1, map(int, line.strip().split())))\n vecs = []\n# import pdb; pdb.set_trace()\n for i in range(len(line)):\n #if self.perf:\n # vecs.append(line[i])\n #else:\n eid = int(line[i]) + 1\n vecs.append(self.s2v[eid])\n # for i in range(len(line) - window_size):\n self.inputs.append(vecs)# [len, emd]\n self.outputs.append(label)\n self.lengths.append(len(line))\n\n def dataLabeleda(self, FN, label):\n with open(FN, 'r') as f:\n for line in tqdm(f.readlines()):\n self.num_sessions += 1\n line = tuple(map(lambda n: n - 1, map(int, line.strip().split())))\n vecs = []\n# import pdb; pdb.set_trace()\n for i in range(len(line)):\n #if self.perf:\n # vecs.append(line[i])\n #else:\n eid = int(line[i]) + 1\n vecs.append(self.s2va[eid])\n # for i in range(len(line) - window_size):\n self.inputs.append(vecs)# [len, emd]\n self.outputs.append(label)\n self.lengths.append(len(line))\n def time_dataLabeled(self, FN):\n with open(FN, 'r') as f:\n for line in tqdm(f.readlines()):\n #import pdb; pdb.set_trace()\n self.num_sessions += 1\n line = tuple(map(lambda n: n, map(int, line.strip().split())))\n #line = line.strip().split()\n td = [-1]\n for i in range(len(line)):\n td.append(line[i])\n # if line[i] == 0:\n # td.append(1.5)\n # else:\n # td.append(1 / line[i])\n self.cnt += len(line)\n self.time_sum += sum(td)\n #td = [-1] + [ line[i] for i in range(len(line))]\n self.timedelta.append(td) # [len]\n\n\n\ndef pad_tensor(vec, pad, dim, typ):\n \"\"\"\n args:\n vec - tensor to pad\n pad - the size to pad to\n dim - dimension to pad\n\n return:\n a new tensor padded to 'pad' in dimension 'dim'\n \"\"\"\n pad_size = list(vec.shape)\n pad_size[dim] = pad - vec.size(dim)\n if (vec.dtype==torch.int64):\n vec = torch.tensor(vec, dtype=torch.float32)\n\n return torch.cat([vec, torch.zeros(*pad_size, dtype=typ)], dim=dim)\n\n\nclass PadCollate:\n \"\"\"\n a variant of callate_fn that pads according to the longest sequence in\n a batch of sequences\n \"\"\"\n\n def __init__(self, dim=0, typ=torch.float32):\n \"\"\"\n args:\n dim - the dimension to be padded (dimension of time in sequences)\n \"\"\"\n self.dim = dim\n self.type = typ\n\n def pad_collate(self, batch):\n \"\"\"\n args:\n batch - list of (tensor, label, length)\n\n reutrn:\n xs - a tensor of all examples in 'batch' after padding\n ys - a LongTensor of all labels in batch\n ls - a tensor of all lengths in batch\n \"\"\"\n # find longest sequence\n max_len = max(map(lambda x: x[0].shape[self.dim], batch))\n # print('max len', max_len)\n # pad according to max_len\n# pad_batch = map(lambda x: pad_tensor(x[0], pad=max_len, dim=self.dim), batch)\n pad_batch = []\n for i in range(len(batch)):\n pad_batch.append(pad_tensor(batch[i][0], pad=max_len, dim=self.dim, typ=self.type))\n xs = torch.stack(pad_batch, dim=0) # [b, ml, e]\n pad_batch_2 = [] \n # import pdb; pdb.set_trace()\n for i in range(len(batch)):\n pad_batch_2.append(pad_tensor(batch[i][1], pad=max_len, dim=self.dim, typ=torch.float32))\n txs = torch.stack(pad_batch_2, dim=0) # [b, ml]\n ys = torch.tensor(list(map(lambda x: x[2], batch))) # [b, 1]\n ls = torch.tensor(list(map(lambda x: x[3], batch))) # [b, 1]\n return xs, txs, ys, ls\n\n def __call__(self, batch):\n return self.pad_collate(batch)\n\nif __name__ == '__main__':\n parser = argparse.ArgumentParser()\n parser.add_argument('-encoding', default='hdfs_sentence2vec.pkl', type=str)\n parser.add_argument('-embeddim', default=300, type=int)\n parser.add_argument('-timedim', default=300, type=int)\n parser.add_argument('-dataset', default='hdfs', type=str)\n parser.add_argument('-type', default=10, type=str)\n parser.add_argument('-output', default='model/default.pt', type=str)\n parser.add_argument('-bi', default='True', type=bool)\n parser.add_argument('-attn', default='True', type=bool)\n parser.add_argument('-indir', default='data/LogInsight/hdfs', type=str)\n args = parser.parse_args()\n encodingFN = args.encoding\n time_dim = args.timedim\n embed_dim = args.embeddim\n tensortype = args.type\n outputPath = args.output\n bidirectional = args.bi\n indir = args.indir\n attnFlag = args.attn\n# import pdb; pdb.set_trace()\n datasetName = args.dataset\n if tensortype == 'float32':\n tensortype = torch.float32\n elif tensortype == 'double':\n tensortype = torch.double\n #elif tensortype == 'long':\n # tensortype = torch.long\n model = BiLSTM(batch_size, embed_dim, hidden_size, num_layers, num_classes, bidirectional, True, attnFlag, time_dim, device).to(device)\n #model = AC_BiLSTM(embed_dim, hidden_size, num_layers, num_classes, bidirectional, device).to(device)\n dataloader = DataLoader(SeqDataset(indir + '/my_'+ datasetName + '_train_normal', indir + '/my_'+ datasetName + '_train_abnormal', indir + '/my_' + datasetName + '_train_perf', encodingFN), batch_size=batch_size, shuffle=True, pin_memory=False, collate_fn=PadCollate(dim=0, typ=tensortype))\n criterion = nn.CrossEntropyLoss()\n optimizer = optim.Adam(model.parameters())\n# optimizer = optim.SGD(model.parameters(), lr=0.01, weight_decay=0.0001, momentum=0.9)\n #import pdb; pdb.set_trace()\n #for step, fk in enumerate(dataloader):\n # import pdb; pdb.set_trace()\n for epoch in range(num_epochs):\n train_loss = 0\n for step, (seq, timedelta, label, leng) in enumerate(dataloader):\n #import pdb; pdb.set_trace()\n y, output, seq_len = model(seq.to(device), timedelta.to(device), label.to(device), leng.to(device))\n\n loss = criterion(output, y)\n optimizer.zero_grad()\n loss.backward()\n train_loss += loss.item()\n optimizer.step()\n print('Epoch [{}/{}], Train_loss: {:.4f}'.format(epoch+1, num_epochs, train_loss))\n #import pdb; pdb.set_trace()\n # if not os.path.isdir(model_dir):\n # os.makedirs(model_dir)\n torch.save(model.state_dict(), outputPath)\n #torch.save(model.timeembedding, 'model/time_embedding.pt')\n print('Finished Training')\n","repo_name":"IntelligentDDS/SwissLog","sub_path":"anomaly_detection/perf_train.py","file_name":"perf_train.py","file_ext":"py","file_size_in_byte":10112,"program_lang":"python","lang":"en","doc_type":"code","stars":42,"dataset":"github-code","pt":"15"} +{"seq_id":"29368422121","text":"# dataset settings\ndataset_type = 'CocoDataset'\ndata_root = '../../../dataset/'\nimg_norm_cfg = dict(\n mean=[123.675, 116.28, 103.53], std=[58.395, 57.12, 57.375], to_rgb=True)\n\nalbu_train_transforms = [\n dict(\n type='OneOf',\n transforms=[\n dict(type='Flip',p=1.0),\n dict(type='RandomRotate90',p=1.0)\n ],\n p=0.5),\n dict(type='RandomResizedCrop',height=512, width=512, scale=(0.5, 1.0), p=0.5),\n dict(type='RandomBrightnessContrast',brightness_limit=0.1, contrast_limit=0.15, p=0.5),\n dict(type='HueSaturationValue', hue_shift_limit=15, sat_shift_limit=25, val_shift_limit=10, p=0.5),\n dict(type='GaussNoise', p=0.3),\n dict(\n type='OneOf',\n transforms=[\n dict(type='Blur', p=1.0),\n dict(type='GaussianBlur', p=1.0),\n dict(type='MedianBlur', blur_limit=5, p=1.0),\n dict(type='MotionBlur', p=1.0)\n ],\n p=0.1)\n]\n\ntrain_pipeline = [\n dict(type='LoadImageFromFile'),\n dict(type='LoadAnnotations', with_bbox=True),\n dict(type='Resize', img_scale=(1024, 1024), keep_ratio=True),\n dict(type='RandomFlip', flip_ratio=0.5),\n dict(type='Normalize', **img_norm_cfg),\n dict(type='Pad', size_divisor=32),\n dict(type='DefaultFormatBundle'),\n dict(type='Collect', keys=['img', 'gt_bboxes', 'gt_labels']),\n]\ntest_pipeline = [\n dict(type='LoadImageFromFile'),\n dict(\n type='MultiScaleFlipAug',\n img_scale=(1024, 1024),\n flip=False,\n transforms=[\n dict(type='Resize', keep_ratio=True),\n dict(type='RandomFlip'),\n dict(type='Normalize', **img_norm_cfg),\n dict(type='Pad', size_divisor=32),\n dict(type='ImageToTensor', keys=['img']),\n dict(type='Collect', keys=['img']),\n ])\n]\ndata = dict(\n samples_per_gpu=4,\n workers_per_gpu=4,\n train=dict(\n type=dataset_type,\n ann_file=data_root + 'train.json',\n img_prefix=data_root,\n pipeline=train_pipeline),\n val=dict(\n type=dataset_type,\n ann_file=data_root + 'val.json',\n img_prefix=data_root,\n pipeline=test_pipeline),\n test=dict(\n type=dataset_type,\n ann_file=data_root + 'test.json',\n img_prefix=data_root,\n pipeline=test_pipeline))\nevaluation = dict(interval=1, metric='bbox')\n","repo_name":"boostcampaitech4lv23cv3/level2_objectdetection_cv-level2-cv-16","sub_path":"mmdetection/configs/_trashDet_/_base_/datasets/coco_detection.py","file_name":"coco_detection.py","file_ext":"py","file_size_in_byte":2318,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"15"} +{"seq_id":"6440688624","text":"\"\"\"\nValidate if a given string is numeric.\n\nSome examples:\n\"0\" => true\n\" 0.1 \" => true\n\"abc\" => false\n\"1 a\" => false\n\"2e10\" => true\nNote: It is intended for the problem statement to be ambiguous. You should gather all requirements up front before\n implementing one.\n\nUpdate (2015-02-10):\nThe signature of the C++ function had been updated. If you still see your function signature accepts a const\n char * argument, please click the reload button to reset your code definition.\n\"\"\"\nimport re\n\n# def isNumber(s):\n# \"\"\"\n# :type s: str\n# :rtype: bool\n# \"\"\"\n# s = s.strip(' ')\n# # s = s.rstrip(' ')\n# if not s:\n# return False\n# if 'e' in s:\n# s = s.split('e')\n# elif '.' in s:\n# s = s.split('.')\n# if s[0] == '':\n# s[0] = '0'\n# elif s[-1] == '':\n# s[-1] = '0'\n# cnt = 0\n# for i in s:\n# if not i:\n# continue\n# if ' ' in i:\n# return False\n# j = \"\".join((lambda x: (x.sort(), x)[1])(list(i)))\n# i = ''.join(j)\n# if '0' <= i[-1] <= '9':\n# cnt += 1\n# return cnt == len(s)\n\n\ndef isNumber(s):\n \"\"\"\n :type s: str\n :rtype: bool\n \"\"\"\n s = s.strip(' ')\n pattern = re.compile(r'(([\\+-]?\\d*\\.\\d+e[\\+-]?\\d+)|([\\+-]?\\d+[\\.\\d+]e[\\+-]?\\d+)|([\\+-]?\\d+\\.e[\\+-]?\\d+)|([\\+-]?\\d*\\.\\d+e\\d+)|([\\+-]?\\d*\\.\\d+)|([\\+-]?\\d+\\.\\d*)|([\\+-]?\\d+e\\+\\d+)|([\\+-]?\\d+[e]??\\d+)|([\\+-]?\\d*))')\n ret = pattern.match(s)\n if ret:\n print(ret.group())\n if ret.group():\n return len(ret.group()) == len(s)\n else:\n return False\n else:\n return False\n\n# 1481 / 1481 test cases passed Runtime: 135 ms 35.11 % -- 70 %\n\n\"\"\"\n一点点感悟: 1、多个正则条件时不能加上空格\n\"\"\"\n\n\nif __name__ == \"__main__\":\n # \"46.e3\" true\n # \".2e81\" true\n # \".e1\" false\n # \"6+1\" false\n # \"32.e-80123\" true\n # \"1.38354e+8\" true\n # \".703e+4144\" true\n # \"166e-02767\" true\n print(isNumber(\"46.e3\"))\n","repo_name":"Lyechen/leetcode-python","sub_path":"leetcode_065.py","file_name":"leetcode_065.py","file_ext":"py","file_size_in_byte":2049,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"15"} +{"seq_id":"24148240490","text":"import pandas as pd\n\n# Math Test\nmath_ans = pd.read_csv(\"https://raw.githubusercontent.com/youmin817/Data_Analysis/master/dashboard_app/ACT_Math_Answer_Key\").T\n\nheader = math_ans.iloc[0]\nmath_ans = math_ans[1:]\nmath_ans = math_ans.rename(columns=header)\nmath_ans.index = range(50)\n\n\nsd_ans=pd.read_csv(\"https://raw.githubusercontent.com/youmin817/Data_Analysis/master/dashboard_app/P01_Answers.csv\").T\nheader=sd_ans.iloc[0]\nsd_ans = sd_ans[1:51]\nsd_ans = sd_ans.rename(columns=header)\nsd_ans.index = range(0, 50)\n\n\ndef math_grader(math_ans,sd_ans,sd_id):\n index = []\n for num in range(len(math_ans[\"Key\"])):\n record = []\n # checking answers\n ans = math_ans.iloc[num,0]\n if sd_ans.loc[num,sd_id] == ans:\n record.append(True)\n index.append(record)\n else:\n record.append(False)\n index.append(record)\n result = pd.DataFrame(index, columns = [\"Grade\"])\n math_ans['Grade'] = result['Grade']\n grade = pd.DataFrame(math_ans['Grade'].value_counts())\n grade[\"Ans\"] = [\"Right\", 'Wrong']\n math_ans.loc[math_ans['Grade'] == True, \"Grade\"] = \"Right\"\n math_ans.loc[math_ans['Grade'] == False, \"Grade\"] = \"Wrong\"\n return math_ans, grade\n\n\ndef math_table(math_ans,sd_ans ,sd_id):\n math_result, grade_table = math_grader(math_ans,sd_ans,sd_id)\n math = pd.DataFrame(sd_ans[sd_id])\n math['Ans_Key'] = math_result['Key']\n math[\"Grade\"] = math_result[\"Grade\"]\n return math, grade_table\n","repo_name":"youmin817/Dash_app","sub_path":"subject.py","file_name":"subject.py","file_ext":"py","file_size_in_byte":1485,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"15"} +{"seq_id":"41983524032","text":"import tensorflow as tf\nimport tensorflow.contrib.graph_editor as ge\n\n# add new tensors/ops and connect them with existing ones\n\n# sgv = SubGraphView\ndef inject_nodes(graph, location, injection_fn, args={}):\n '''\n Applies injection function after defined node location in graph\n :param graph: current graph\n :param location: name of node after which to inject new nodes as str, e.g. 'add:0'\n :param injection_fn: function defining nodes to inject\n :param args: any additional arguments for injection_fn, e.g. new external tensors\n :return: graph with injected nodes\n '''\n # find injection location in graph\n tensors = tf.contrib.graph_editor.get_tensors(graph)\n injection_point = [t.name for t in tensors].index(location)\n # tensors[injection_point] is where we want to inject new nodes\n\n # find outgoing connections of tensors[injection_point]\n connection_nodes = [] # nodes for which tensors[injection_point] is currently an input\n for o in tensors:\n # print(o)\n for input in o.op.inputs:\n if input.name == tensors[injection_point].name:\n print('found connection: {}'.format(o.name))\n connection_nodes.append(o)\n\n # apply injection function to add nodes after tensors[injection_point] within the same name_scope\n new_node = injection_fn(tensors[injection_point],**args) # tensors[injection_point] becomes input for new nodes\n\n if len(connection_nodes)<1:\n Warning(\"Didn't find any outgoing connections for node {}\".format(tensors[injection_point].name))\n\n else:\n # make last injected node input for connection nodes of tensors[injection_point]\n connection_inputs = ge.sgv([c.op for c in connection_nodes]) # get all current inputs of connection nodes (could have additional ones we don't want to remap)\n for j in range(len(connection_inputs.inputs)):\n # print(ge.sgv(connections[0].op).remap_inputs([j]))\n if connection_inputs.remap_inputs([j]).inputs[0].name == tensors[injection_point].name: # select which input to remap\n # reroute network so that new_node becomes (selected) input for outgoing connections\n ge.connect(ge.sgv(new_node.op), ge.sgv([c.op for c in connection_nodes]).remap_inputs([0]))\n print('connected')\n\n # ensure that new_node now is in the input of connection nodes\n for c in connection_nodes:\n assert new_node in [i for i in c.op.inputs],'{} is not an input of {}'.format(new_node.name,c.name)\n\n return graph\n\n\nif __name__ == '__main__':\n\n # toy injection function\n v = tf.constant(2, name='v')\n w = tf.constant(4, name='w')\n args = {'v':v,'w':w}\n def constant_injection(input_tensor,v,w):\n output_tensor = (input_tensor ** v) + w\n return output_tensor\n\n # build toy graph\n with tf.name_scope('model'):\n # with tf.name_scope('bert'):\n a = tf.constant(1,name='a')\n b = tf.constant(2,name='b')\n c = a+b\n d = tf.constant(3,name='d')\n e = c*d\n f = tf.constant(1,name='f')\n g = c*f\n z = g + e\n\n graph = tf.get_default_graph()\n graph = inject_nodes(graph, 'model/add:0', constant_injection, args)\n\n init_op = tf.global_variables_initializer()\n model_dir = \"/Users/nicole/code/CQA/data/tmp/\"\n\n # copy_graph(tf.global_variables())\n\n with tf.Session() as sess:\n\n sess.run(init_op)\n print(z.eval()) # -> 3\n # print(outputs[-1].eval()) # -> 3\n\n # print(new_d.eval()) # -> 42\n\n writer = tf.summary.FileWriter(model_dir + '/external_injection', sess.graph)\n # save_path = saver.save(sess, \"/Users/nicole/code/CQA/data/tmp/model.ckpt\")\n writer.add_graph(sess.graph)\n writer.close()\n\n\n\n\n\n\n\n\n","repo_name":"wuningxi/GiBERT","sub_path":"src/graph_modification/inject.py","file_name":"inject.py","file_ext":"py","file_size_in_byte":3808,"program_lang":"python","lang":"en","doc_type":"code","stars":3,"dataset":"github-code","pt":"15"} +{"seq_id":"42299768599","text":"class Solution:\r\n def merge(self, intervals: list) -> list:\r\n\r\n # Strategy:\r\n # Since we are not sure if intervals will be sorted in any way, we should\r\n # sort intervals in increasing order by their lower bound (or 0th index).\r\n # Then we will go through the sorted intervals and see if the current interval\r\n # overlaps with the next interval. Note that, there are few ways 2 intervals\r\n # can overlap:\r\n # 1) ( { ) }\r\n # 2) ( { } )\r\n # 3) { ( } )\r\n # 4) { ( ) }\r\n # Since intervals are sorted in increasing order by their lower bound, overlaps\r\n # can only happen in 2 cases (case 1 and case 2). Notice that in both cases, the\r\n # lower bound of the next interval is smaller than OR EQUAL TO the upper bound of\r\n # the current interval. When we merge the 2 intervals, we keep the larger upper\r\n # bound between the 2 intervals.\r\n # Also, as a consequence of the previous observation, if the next interval DOES NOT\r\n # overlap with the current interval, any future interval will also not overlap with\r\n # the current interval. This is because a non-overlap condition happens when the\r\n # lower bound of the next interval is bigger than the upper bound of the current\r\n # interval. Any future intervals will have an even higher lower bound. Therefore,\r\n # when there is no overlap, we update the current interval to the next interval.\r\n\r\n # Sort intervals by their first element.\r\n intervals = sorted(intervals, key=lambda x: x[0])\r\n\r\n # Initialize solution to an empty list. It may be better to append to solution list\r\n # rather than popping an interval from the intervals list repeatedly. This is\r\n # because, POPPING AN ARBITRARY ELEMENT from a list takes O(n) NOT O(1).\r\n solution = []\r\n\r\n # Initialize current interval index to 0 and the next interval index to 1.\r\n curr_idx = 0\r\n next_idx = 1\r\n\r\n # While the next interval index is still within bound, we keep trying to see if\r\n # the next interval can merge with the current interval.\r\n while next_idx < len(intervals):\r\n\r\n # Get the current interval and the next interval.\r\n curr_interval = intervals[curr_idx]\r\n next_interval = intervals[next_idx]\r\n\r\n # Check to see if the lower bound of the next interval is small than or equal\r\n # to the upper bound of the current interval. If it is, then we have an overlap.\r\n if curr_interval[1] >= next_interval[0]:\r\n\r\n # Merge the 2 intervals by keeping the large upper bound between these 2\r\n # intervals. We already know the lower bound of the current interval is\r\n # less or equal to the lower bound of the next interval.\r\n curr_interval[1] = max(curr_interval[1], next_interval[1])\r\n\r\n # If there is no overlap, we append the curr_interval to solutions. Then we move\r\n # on by setting the current interval to the next interval (or curr_idx to next_idx).\r\n else:\r\n solution.append(curr_interval)\r\n curr_idx = next_idx\r\n\r\n # Continue on with the next interval by incrementing next_idx by 1.\r\n next_idx += 1\r\n\r\n # Since we do not have a chance to append the last current interval to our solution,\r\n # we do it one last time outside of our main loop.\r\n solution.append(intervals[curr_idx])\r\n\r\n return solution\r\n\r\n\r\nl = []\r\nsol = Solution().merge(l)\r\nprint(sol)\r\n","repo_name":"iiimj4everiii/LeetCode","sub_path":"Merge_Intervals/source.py","file_name":"source.py","file_ext":"py","file_size_in_byte":3661,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"15"} +{"seq_id":"11974147839","text":"# -*- coding:utf-8 -*-\r\nimport urllib.request\r\nimport os\r\nimport shutil\r\nimport re\r\nimport codecs\r\nimport json\r\nfrom bs4 import BeautifulSoup\r\nimport _thread\r\n\r\nimport sys \r\nsys.setrecursionlimit(1000000) \r\n\r\ndef get_url(pno,psize,channelid):\r\n url = \"http://apiv2.sohu.com/apiV2/re/news?channelId=\"+str(channelid)+\"&pno=\"+str(pno)+\"&psize=\"+str(psize)\r\n return url\r\n\r\ndef get_fileinfo(url,code):#获取解编码后的HTML\r\n html = None\r\n try:\r\n headers = {'User-Agent':'Mozilla/5.0 (Windows; U; Windows NT 6.1; en-US; rv:1.9.1.6) Gecko/20091201 Firefox/3.5.6'}\r\n req = urllib.request.Request(url=url, headers=headers)\r\n html = urllib.request.urlopen(req).read().decode(encoding = code, errors='ignore')\r\n except Exception as e:\r\n print(e, \"please check your network situation\")\r\n return None\r\n info = json.loads(html)\r\n n=len(info[\"list\"])\r\n path=[]\r\n title=[]\r\n for i in range(n):\r\n path.append(info[\"list\"][i][\"path\"])\r\n title.append(info[\"list\"][i][\"title\"])\r\n return path,title\r\n\r\ndef get_html_soup(url,code):#获取解编码后的HTML\r\n html = None\r\n try:\r\n headers = {'User-Agent':'Mozilla/5.0 (Windows; U; Windows NT 6.1; en-US; rv:1.9.1.6) Gecko/20091201 Firefox/3.5.6'}\r\n req = urllib.request.Request(url=url, headers=headers)\r\n html = urllib.request.urlopen(req).read().decode(encoding = code, errors='ignore')\r\n except Exception as e:\r\n print(e, \"please check your network situation\")\r\n return None\r\n soup = BeautifulSoup(str(html), \"lxml\") \r\n return soup\r\n \r\ndef get_news_body(url):#抓取新闻主体内容\r\n content_text = []\r\n article_div = \"\"\r\n\r\n soup = get_html_soup(url, 'utf-8')\r\n if soup == None:\r\n return None\r\n article_div = str(soup.find(\"div\", attrs = {\"class\": \"text\"}))\r\n soup = BeautifulSoup(str(article_div), \"lxml\")\r\n para_arr = soup.find_all(\"p\")\r\n lenth = len(para_arr)\r\n for i in range(0,lenth - 1):\r\n if len(para_arr[i].get_text().strip()) > 0:\r\n content_text.append(\" \" + para_arr[i].get_text().strip())\r\n for x in content_text:\r\n if x == \" None\":\r\n return None\r\n return content_text\r\n\r\ndef create_txt(rootdir, type, title, content): \r\n filepath=rootdir+'/'+type\r\n if not os.path.exists(filepath):\r\n os.mkdir(filepath)\r\n filepath+= '/'+clean_chinese_character(title) + \".txt\"\r\n if os.path.exists(filepath):\r\n return\r\n f=None\r\n try:\r\n f=codecs.open(filepath,'w','utf-8')\r\n for x in content:\r\n f.write(x)\r\n f.write('\\n')\r\n except Exception as e:\r\n return None \r\n finally:\r\n if not f==None:\r\n f.close()\r\n print(\"create \"+type+\" succeed\")\r\n\r\ndef clean_chinese_character(text):\r\n '''处理特殊的中文符号,将其全部替换为'-' 否则在保存时Windows无法将有的中文符号作为路径'''\r\n chars = chars = ['\\t',\" \",\"\\n\",\"/\", \"\\\"\", \"'\", \"·\", \"。\",\"?\", \"!\", \",\", \"、\", \";\", \":\", \"‘\", \"’\", \"“\", \"”\", \"(\", \")\", \"…\", \"–\", \".\", \"《\", \"》\",\"|\",\"?\",\",\",\"<\",\">\"];\r\n new_text = \"\"\r\n for i in range(len(text)):\r\n if text[i] not in chars:\r\n new_text += text[i]\r\n else:\r\n if not text[i]==\" \":\r\n new_text += \"_\"\r\n return new_text;\r\n\r\n \r\ntopic=[\"caijing\",\"yule\", \"tiyu\",\"qiche\",\"shishang\",\"keji\",\"youxi\",\"chongwu\",\"dongman\",\"wenhua\",\"lishi\",\"jiaoyu\",\"xingzuo\"]\r\nchannelid=[15,19,17,18,23,30,42,44,41,12,13,25,27]\r\n\r\ndef scrape(num):\r\n totalpsize=100\r\n totalpno=100\r\n rootdir=\"F:/souhu\"\r\n i=num\r\n for j in range(totalpsize):\r\n for k in range(totalpno):\r\n url = get_url(k+1,j+1,channelid[i])\r\n (path,title)=get_fileinfo(url,'utf-8')\r\n pathnum=len(path)\r\n for l in range(pathnum):\r\n if path[l].find(\"http\")==-1:\r\n newpath=\"http:\"+path[l]\r\n path[l] = newpath\r\n content=get_news_body(path[l])\r\n if content==None:\r\n continue\r\n create_txt(rootdir, topic[i], title[l], content)\r\n \r\n \r\nimport threading,time\r\nfrom time import sleep, ctime\r\n\r\nthreadpool=[]\r\nfor i in range(13):\r\n th = _thread.start_new_thread(scrape,(i,))\r\n # threadpool.append(th)\r\nwhile(True):\r\n time.sleep(10)\r\n print(10)\r\n# for th in threadpool:\r\n # th.start()\r\n\r\n# for th in threadpool :\r\n # threading.Thread.join( th )\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 ","repo_name":"summersunshine1/textclassification","sub_path":"textclassification/scrapesouhu.py","file_name":"scrapesouhu.py","file_ext":"py","file_size_in_byte":4655,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"15"} +{"seq_id":"21560317916","text":"from sqlite3 import connect\n\n\nclass User:\n def __init__(self, db_name: str, db) -> None:\n self.db_name = db_name\n self.db = db\n\n def disconn(self):\n return self.conn()\\\n .close()\n\n def conn(self):\n return connect(self.db)\n\n def create_table(self):\n script = f'''CREATE TABLE IF NOT EXISTS {self.db_name} (\n name varchar(255),\n surname varchar(255)\n );\n '''\n\n self.conn()\\\n .cursor()\\\n .execute(script)\n\n self.conn()\\\n .commit()\n\n def insert_sercords(self, name: str, surname: str):\n sql = f'INSERT INTO {self.db_name} (name, surname) VALUES (\"{name}, \"{surname}\"'\n\n self.conn()\\\n .cursor()\\\n .execute(sql)\n\n self.conn()\\\n .commit()\n","repo_name":"Ja-Pan-Krzysztof/PythonJsonScrip","sub_path":"database.py","file_name":"database.py","file_ext":"py","file_size_in_byte":830,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"15"} +{"seq_id":"22768932227","text":"import pytest\n\nfrom openpyxl.styles.colors import BLACK, WHITE, Color\n\n\n@pytest.fixture\ndef GradientFill():\n from openpyxl.styles.fills import GradientFill\n return GradientFill\n\n\nclass TestGradientFill:\n\n def test_empty_ctor(self, GradientFill):\n gf = GradientFill()\n assert gf.fill_type == 'linear'\n assert gf.degree == 0\n assert gf.left == 0\n assert gf.right == 0\n assert gf.top == 0\n assert gf.bottom == 0\n assert gf.stop == ()\n\n\n def test_ctor(self, GradientFill):\n gf = GradientFill(degree=90, left=1, right=2, top=3, bottom=4)\n assert gf.degree == 90\n assert gf.left == 1\n assert gf.right == 2\n assert gf.top == 3\n assert gf.bottom == 4\n\n\n def test_sequence(self, GradientFill):\n colors = [Color(BLACK), Color(WHITE)]\n gf = GradientFill(stop=colors)\n assert gf.stop == tuple(colors)\n\n\n def test_invalid_sequence(self, GradientFill):\n colors = [BLACK, WHITE]\n with pytest.raises(TypeError):\n GradientFill(stop=colors)\n\n\n def test_dict_interface(self, GradientFill):\n gf = GradientFill(degree=90, left=1, right=2, top=3, bottom=4)\n assert dict(gf) == {'bottom': \"4\", 'degree': \"90\", 'left':\"1\",\n 'right': \"2\", 'top': \"3\", 'type': 'linear'}\n","repo_name":"petres/eurostat","sub_path":"app/lib/openpyxl/styles/tests/test_fills.py","file_name":"test_fills.py","file_ext":"py","file_size_in_byte":1350,"program_lang":"python","lang":"en","doc_type":"code","stars":10,"dataset":"github-code","pt":"15"} +{"seq_id":"10574898611","text":"# Definition for a binary tree node.\n# class TreeNode(object):\n# def __init__(self, x):\n# self.val = x\n# self.left = None\n# self.right = None\n\nclass Solution(object):\n def diameterOfBinaryTree(self, root):\n \"\"\"\n :type root: TreeNode\n :rtype: int\n \"\"\"\n longgestPaths = [0, ]\n self.longgestPath(root, longgestPaths)\n return longgestPaths[0]\n\n def longgestPath(self, root, longgestPaths):\n if root is None:\n return 0\n else:\n leftPath = self.longgestPath(root.left, longgestPaths)\n rightPath = self.longgestPath(root.right, longgestPaths)\n crossRootPath = (leftPath + rightPath + 1)\n longgestPaths[0] = max(longgestPaths[0], crossRootPath)\n return max(leftPath, rightPath) + 1\n","repo_name":"SS4G/JP2020","sub_path":"algo/543.py","file_name":"543.py","file_ext":"py","file_size_in_byte":836,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"15"} +{"seq_id":"7459337824","text":"#-------------------------------------------------------------------------------\r\n# Name: card.py\r\n# Purpose: Object representing a card in a card game.\r\n#\r\n# Author: Kejdi Domi\r\n#\r\n# Created: 27-07-2020\r\n# Copyright: (c) ASUS 2020\r\n# Licence: \r\n#-------------------------------------------------------------------------------\r\nclass CardValueError(Exception):\r\n def __init__(self,message):\r\n self.message = message\r\n\r\nclass CardSuitError(Exception):\r\n def __init__(self,message):\r\n self.message = message\r\n\r\nclass Card:\r\n\r\n def __init__(self, value, suit):\r\n try:\r\n self.value = value\r\n self.suit = suit\r\n\r\n if self.value not in ['A',2,3,4,5,6,7,8,9,10,'J','Q','K']:\r\n raise CardValueError(\"Invalid Value, a value can be 'A',2,3,4,5,6,7,8,9,10,'J','Q''K'\")\r\n if self.suit not in [\"hearts\",\"spades\", 'diamonds', 'clubs']:\r\n raise CardSuitError('Invalid Suit, suits can be \"hearts\",\"spades\", \"diamonds\", \"clubs\"')\r\n\r\n except (CardValueError, CardSuitError) as e:\r\n print(e.message)\r\n\r\n\r\n\r\n","repo_name":"kejdidomi/xing","sub_path":"card.py","file_name":"card.py","file_ext":"py","file_size_in_byte":1150,"program_lang":"python","lang":"en","doc_type":"code","stars":2,"dataset":"github-code","pt":"15"} +{"seq_id":"7198386364","text":"from collections import Counter\nN,M = input().split()\nmax = -1\narr=[]\nfor a in range(int(M)):\n arr += list(map(int, input().split()))\n \ncounter = Counter(arr).most_common()\n\nfor x, y in counter: \n if int(y)> max:\n max = y\n \n\nfor x, y in counter: \n if max == int(y):\n print(x,end=\" \")\n\n","repo_name":"tiemo0708/PythonPratice-Algo","sub_path":"python_pratice/test.py","file_name":"test.py","file_ext":"py","file_size_in_byte":321,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"17"} +{"seq_id":"8090027118","text":"# Copyright (c) 2023 Arista Networks, Inc. All rights reserved.\r\n# Arista Networks, Inc. Confidential and Proprietary.\r\n\r\n\"\"\"\r\nTestcase for verification of login banner\r\n\"\"\"\r\n\r\nimport pytest\r\nfrom pyeapi.eapilib import EapiError\r\nfrom vane import tests_tools, test_case_logger\r\nfrom vane.config import dut_objs, test_defs\r\n\r\nTEST_SUITE = \"nrfu_tests\"\r\nlogging = test_case_logger.setup_logger(__file__)\r\n\r\n\r\n@pytest.mark.nrfu_test\r\n@pytest.mark.security\r\nclass LoginBannerTests:\r\n \"\"\"\r\n Testcase for verification of login banner\r\n \"\"\"\r\n\r\n dut_parameters = tests_tools.parametrize_duts(TEST_SUITE, test_defs, dut_objs)\r\n test_duts = dut_parameters[\"test_security_rp_login_banner\"][\"duts\"]\r\n test_ids = dut_parameters[\"test_security_rp_login_banner\"][\"ids\"]\r\n\r\n @pytest.mark.parametrize(\"dut\", test_duts, ids=test_ids)\r\n def test_security_rp_login_banner(self, dut, tests_definitions):\r\n \"\"\"\r\n TD: Testcase for verification of login banner.\r\n Args:\r\n dut(dict): details related to a particular DUT\r\n tests_definitions(dict): test suite and test case parameters\r\n \"\"\"\r\n tops = tests_tools.TestOps(tests_definitions, TEST_SUITE, dut)\r\n self.output = \"\"\r\n tops.actual_output = {\"login_banner_found\": False}\r\n\r\n # Forming output message if test result is passed\r\n tops.output_msg = \"Login banner is found on the device.\"\r\n\r\n try:\r\n \"\"\"\r\n TS: Running `show banner login` command on device and verifying that the\r\n login banner is found on the device.\r\n \"\"\"\r\n output = dut[\"output\"][tops.show_cmd][\"json\"]\r\n logging.info(\r\n f\"On device {tops.dut_name}, output of {tops.show_cmd} command is: \\n{output}\\n\",\r\n )\r\n self.output += f\"\\nOutput of {tops.show_cmd} command is: \\n{output}\"\r\n login_banner = output.get(\"loginBanner\")\r\n tops.actual_output = {\"login_banner_found\": bool(login_banner)}\r\n\r\n # forming output message if test result is fail\r\n if tops.expected_output != tops.actual_output:\r\n if not tops.actual_output[\"login_banner_found\"]:\r\n tops.output_msg = \"Login banner is not found on the device.\"\r\n\r\n except (AttributeError, LookupError, EapiError) as excep:\r\n tops.output_msg = tops.actual_output = str(excep).split(\"\\n\", maxsplit=1)[0]\r\n logging.error(\r\n (\r\n f\"On device {tops.dut_name}, Error while running the testcase\"\r\n f\" is:\\n{tops.actual_output}\"\r\n ),\r\n )\r\n\r\n tops.test_result = tops.expected_output == tops.actual_output\r\n tops.parse_test_steps(self.test_security_rp_login_banner)\r\n tops.generate_report(tops.dut_name, self.output)\r\n assert tops.expected_output == tops.actual_output\r\n","repo_name":"aristanetworks/vane","sub_path":"nrfu_tests/test_security_rp_login_banner.py","file_name":"test_security_rp_login_banner.py","file_ext":"py","file_size_in_byte":2928,"program_lang":"python","lang":"en","doc_type":"code","stars":12,"dataset":"github-code","pt":"17"} +{"seq_id":"9448216188","text":"# -*- coding: utf-8 -*-\n# Part of Softhealer Technologies.\n\nfrom odoo import api, fields, models\nfrom odoo.osv import expression\n\n\nclass ShAccountJournalRestrict(models.Model):\n _inherit = 'account.journal'\n\n @api.model\n def default_get(self, fields):\n rec = super(ShAccountJournalRestrict, self).default_get(fields)\n\n users = self.env.company.sh_user_ids.ids\n rec.update({\n 'user_ids': [(6, 0, users)]\n })\n return rec\n\n user_ids = fields.Many2many(\n 'res.users', string=\"Users\", copy=False)\n\n # To apply domain to action_________ 2\n @api.model\n def _name_search(self, name, args=None, operator='ilike', limit=100, name_get_uid=None):\n super(ShAccountJournalRestrict, self)._name_search(\n name, args=None, operator='ilike', limit=100, name_get_uid=None)\n\n if(\n self.env.user.has_group(\"sh_journal_restrict.group_journal_restrict_feature\") and not\n (self.env.user.has_group(\"base.group_erp_manager\"))\n ):\n domain = [\n (\"user_ids\", \"in\", self.env.user.id), ('name', 'ilike', name)\n ]\n else:\n domain = [('name', 'ilike', name)]\n return self._search(expression.AND([domain, args]), limit=limit, access_rights_uid=name_get_uid)\n\n # To apply domain to load menu_________ 1\n @api.model\n def search(self, args, offset=0, limit=None, order=None, count=False):\n _ = self._context or {}\n if(\n self.env.user.has_group(\"sh_journal_restrict.group_journal_restrict_feature\") and not\n (self.env.user.has_group(\"base.group_erp_manager\"))\n ):\n args += [\n (\"user_ids\", \"in\", self.env.user.id),\n ]\n return super(ShAccountJournalRestrict, self).search(\n args,\n offset=offset,\n limit=limit,\n order=order,\n count=count,\n )\n","repo_name":"BERGAWI/ALMAYAR","sub_path":"sh_journal_restrict/models/account.py","file_name":"account.py","file_ext":"py","file_size_in_byte":1948,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"17"} +{"seq_id":"23794537643","text":"import numpy as np\nfrom hmmlearn.hmm import MultinomialHMM,GMMHMM\nimport scipy.io as scipy_io\nfrom sklearn.metrics.cluster import adjusted_mutual_info_score\nimport matplotlib.pyplot as plt\nimport copy\nimport generate_exercise as gen_ex\n\ndef random_observation(Diff_level,level):\n \"\"\" randomly generate observation by using beta distribution modeling student correctness\n Diff_level : beta distribution parameter for different level 4 by 2 matrix\n level: current level\n return : observation\n\n \"\"\"\n if np.random.beta(Diff_level[level,0],Diff_level[level,1]) >= 0.5 :\n return level\n else:\n return level + 4\n\n\ndef level_change(state_estimate,current_state,T1,T2,Tpass):\n \"\"\" probability based to decide when to increase/decrease student level\n state_estimate : hmm state estimation for current time\n current_state : t-1 state (deterministic)\n T1 : increase level threshold\n T2 : decrease level threshold\n Tpass: pass threshold\n \"\"\"\n if current_state !=0 :\n if current_state !=3:\n if np.sum(state_estimate[0:current_state+1])/(current_state+1) >=T1:\n return current_state -1\n elif np.sum(state_estimate[current_state:4])/(4-current_state) >=T2 :\n return current_state +1\n else:\n return current_state\n elif state_estimate[3]<=T1:\n return 2\n else:\n return 3\n elif state_estimate[0] >=Tpass:\n return -1\n elif np.sum(state_estimate[1:4])/3 >=T2 :\n return 1\n else:\n return 0\n\ndef rule_based_level_change(seq,past_num =3):\n \"\"\" rule based to decide when to increase/ decrease student level\n return_num = -1: increase\n return_num = 0: hold\n return_num = 1: decrease\n \"\"\"\n new_seq = copy.copy(seq)\n # get past values\n A = new_seq.pop()\n return_num = 0\n for i in range(past_num-1):\n try :\n if A ==new_seq.pop():\n if A >=4 and A!=7:\n return_num = 1\n elif A >=4 and A==7:\n return_num = 0\n else:\n return_num = -1\n else:\n return 0\n except IndexError:\n return_num = 0\n break\n return return_num\n\n\ndef plot_seq(seq,post_level,know_cover):\n \"\"\"Plotting posterior probability and sequence \"\"\"\n array_seq = np.array(seq)\n array_post_level = np.array(post_level)\n know_seq = np.array(know_cover)\n plt.subplot(3,1,1)\n # plotting exercise sequence\n for i in range(len(seq)):\n if array_seq[i] >=4:\n plt.plot(i,array_seq[i]-4,'rs')\n else:\n plt.plot(i,array_seq[i],'gd')\n plt.ylim(0,3)\n\n plt.subplot(3,1,2)\n lg1= plt.plot(array_post_level[:,0],'r-',label ='A')\n lg2=plt.plot(array_post_level[:,1],'g-',label ='B')\n lg3=plt.plot(array_post_level[:,2],'b-',label ='C')\n lg4=plt.plot(array_post_level[:,3],'k-',label ='D')\n\n plt.legend()\n plt.ylim(0,1)\n plt.subplot(3,1,3)\n plt.plot(know_seq)\n plt.show()\n\n\n\n\nif __name__ == '__main__':\n # subjective Transition matrix: stationary distribution: 0.167,0.333,0.333,0.167, eigenvalue\n # 1,0.9,0.7,0.6\n Trans = np.array([[0.8,0.2,0,0],[0.1,0.8,0.1,0],[0 ,0.1,0.8,0.1],[0,0,0.2,0.8]])\n # subjective Emission distribution P(difficulty level | student level)\n Emiss_sub = 0.25*np.ones([4,4])\n# Emiss_sub = np.array([[0.5,0.3,0.1,0.1],[0.3,0.5,0.1,0.1],[0.1 ,0.3,0.4,0.2],[0.05,0.15,0.2,0.6]])\n # objective Emission distribution P(answer | difficulty level student level)\n # should have learnt from data, for now by our assumption\n\n Emiss_obj_1 = np.array([[0.5,0.7,0.8,0.9],[0.3,0.65,0.7,0.85],[0.2,0.5,0.6,0.8],[0.1,0.3,0.5,0.6]])\n Emiss_obj_2 = 1- Emiss_obj_1\n\n # Emission Probability\n Emiss = np.zeros([2,4,4])\n Emiss[0,:,:] = Emiss_obj_1.T*Emiss_sub\n Emiss[1,:,:] = Emiss_obj_2.T*Emiss_sub\n Emiss = Emiss.reshape((8,4))\n\n # Initial Probability: First set as stationary distribution of Transition matrix, Eventually should be learnt through data\n Startprob = np.array([0.167,0.333,0.333,0.167])\n\n # setting HMM model parameters\n HMM_model = MultinomialHMM(n_components = 4,startprob= Startprob,transmat = Trans,algorithm = \"map\")\n HMM_model._set_emissionprob(Emiss.T)\n\n\n\n # generate exercise database\n data_base = gen_ex.question_search(N_seq = np.array([1000,1000,1000,1000]),K = 30,beta_seq= [4,3,2.5,2])\n\n # exercise difficulty simulation\n# Diff_level = np.array([[0.5,0.5],[0.7,0.3],[0.8,0.2],[0.9,0.1]])\n# Diff_level = np.array([[0.3,0.7],[0.65,0.35],[0.7,0.3],[0.85,0.15]])\n Diff_level = np.array([[0.2,0.8],[0.5,0.5],[0.6,0.4],[0.8,0.2]])\n# Diff_level = np.array([[0.1,0.9],[0.3,0.7],[0.5,0.5],[0.6,0.4]])\n\n\n # observation sequence : i.e. answer = 0/1 & level = 0/1/2/3\n seq = []\n post_level = []\n know_cover = []\n\n # selecting first question\n post_level.append(Startprob)\n current_state = np.argmax(Startprob)\n # last problem id\n last_problem_id = [current_state,0]\n # appending observation sequence\n new_observe = random_observation(Diff_level,np.argmax(Startprob))\n seq.append(new_observe)\n\n # appending knowledge coverage\n last_problem_id = data_base.search_problem(current_state,last_problem_id,answer = 1-int(new_observe/4))\n knowledge = np.double(data_base.get_know_mask())\n know_cover.append(np.sum(knowledge)/knowledge.size)\n\n\n # threshold for hidden state based level change\n T1 = 0.3\n T2 = 0.3\n Tpass = 0.6\n # threshold for rule based level change\n past_num = 3\n\n\n\n # generating sequence\n for i in range(60):\n logprob, posterior = HMM_model.score_samples(seq)\n # estimating current state\n last_post = posterior[posterior.shape[0]-1]\n # appending current posterior estimation\n post_level.append(last_post)\n\n# # hidden state based level change\n current_state = level_change(last_post,current_state,T1,T2,Tpass)\n\n# # rule based level change\n# current_state = current_state + rule_based_level_change(seq,past_num)\n\n if current_state != -1 and last_problem_id[1]!=-1:\n new_observe = random_observation(Diff_level,current_state)\n # randomly generate answer for next question\n seq.append(new_observe)\n last_problem_id = data_base.search_problem(current_state,last_problem_id,answer = 1-int(new_observe/4))\n knowledge = np.double(data_base.get_know_mask())\n know_cover.append(np.sum(knowledge)/knowledge.size)\n else:\n\n break\n plot_seq(seq,post_level,know_cover)\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n","repo_name":"xning01/WL_DOE","sub_path":"student_recommend.py","file_name":"student_recommend.py","file_ext":"py","file_size_in_byte":6776,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"17"} +{"seq_id":"73260178583","text":"import numpy as np\nfrom neural_network import NeuralNetwork\n\nclass OptSgd():\n \n def __init__(self, step_size):\n self.step_size = step_size\n\n def step(self, gradient):\n return self.step_size * gradient\n\nclass OptAdam():\n\n def __init__(self, step_size, wind_mom_rate, wind_grad_rate):\n self.step_size = step_size\n self.wind_mom_rate = wind_mom_rate\n self.wind_grad_rate = wind_grad_rate\n self.wind_mom = None\n self.wind_grad = None\n\n def step(self, gradient):\n\n if self.wind_mom is None:\n self.wind_mom = np.zeros_like(gradient)\n if self.wind_grad is None:\n self.wind_grad = np.zeros_like(gradient)\n\n self.wind_mom = self.wind_mom_rate*self.wind_mom + (1.0 - self.wind_mom_rate)*gradient\n self.wind_grad = self.wind_grad_rate*self.wind_grad + (1.0 - self.wind_grad_rate)*(gradient**2)\n return self.step_size*(self.wind_mom/(np.sqrt(self.wind_grad)+1e-8))\n\ndef individual_to_neural_network(individual, layer_sizes, layer_activations,\n biases=True, use_vbn=True, virtual_batch=None):\n '''\n Converts a 'chromosome'/individual to a PyTorch neural network module.\n '''\n\n # if biases is true, we first take off all the biases from the end\n bias_section = np.sum(layer_sizes[1:]) # sum up all nodes except the last\n vbn_section = len(layer_sizes[1:-1])*2\n total_section = bias_section+vbn_section\n if biases:\n if use_vbn:\n weights = individual[:, :-total_section]\n biases = individual[0, -total_section:(-total_section+bias_section)]\n vbn = individual[:, (-total_section+bias_section):]\n assert len(vbn[0,:]) + len(weights[0,:]) + len(biases) == len(individual[0, :]), \"length mismatch\"\n else:\n weights = individual[:, :-total_nodes]\n biases = individual[0, -total_nodes:]\n vbn = None\n assert len(weights) + len(biases) == len(individual[0, :]), \"length mismatch\"\n else:\n if use_vbn:\n weights = individual[:, :-vbn_section]\n vbn = individual[:, -vbn_section:]\n assert len(weights) + len(vbn) == len(individual[0, :]), \"length mismatch\"\n else:\n weights = individual[:]\n vbn = None\n biases = np.zeros(total_nodes) + 0.01 # we fill the biases with 0.01 because maybe that's more interesting\n\n culm_w = 0\n culm_b = 0\n layer_weights = []\n layer_biases = []\n for l1,l2 in zip(layer_sizes[:-1], layer_sizes[1:]):\n\n weight_count = l1*l2\n w = np.array(weights[0, culm_w:(culm_w+weight_count)])\n w = np.reshape(w, (l1,l2))\n culm_w += weight_count\n layer_weights.append(w)\n \n b = biases[culm_b:(culm_b+l2)]\n culm_b += l2\n layer_biases.append(b)\n\n if use_vbn:\n vbn = np.reshape(vbn, (-1, 2))\n\n torch_nn = NeuralNetwork(layer_sizes, layer_activations, layer_weights, layer_biases,\n virtual_batch=virtual_batch, vbn_params=vbn)\n return torch_nn\n","repo_name":"levifussell/EvoStratClean","sub_path":"utils.py","file_name":"utils.py","file_ext":"py","file_size_in_byte":3100,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"17"} +{"seq_id":"8842697187","text":"import logging\nfrom django.conf import settings\n\n\nlogger = logging.getLogger(__name__)\n\n\nclass StateDatasetRouter(object):\n \"\"\"Read/write from speciic State databases\"\"\"\n\n def _db_name(self, model):\n return 'traffic_stops_{}'.format(model._meta.app_label)\n\n def _db_name_from_label(self, app_label):\n return 'traffic_stops_{}'.format(app_label)\n\n def db_for_read(self, model, **hints):\n \"\"\"Return state DB if model's app name is a database\"\"\"\n state_db = self._db_name(model)\n if state_db in settings.DATABASES:\n name = state_db\n else:\n name = 'default'\n logger.debug('db_for_read({}): {}'.format(state_db, name))\n return name\n\n def db_for_write(self, model, **hints):\n \"\"\"Return state DB if model's app name is a database\"\"\"\n state_db = self._db_name(model)\n if state_db in settings.DATABASES:\n name = state_db\n else:\n name = 'default'\n logger.debug('db_for_write({}): {}'.format(state_db, name))\n return name\n\n def allow_migrate(self, db, app_label, model_name=None, **hints):\n # scenarios:\n #\n # default traffic_stops_nc False\n # default traffic_stops_admin True\n # traffic_stops_nc traffic_stops_admin False\n # traffic_stops_nc traffic_stops_nc True\n #\n state_db = self._db_name_from_label(app_label)\n app_is_state = state_db in settings.DATABASES\n if app_is_state:\n ret = db == state_db\n elif db == 'default':\n ret = True\n else:\n ret = False\n logger.debug(\n 'allow_syncdb({}, {} {}): {}'.format(db, app_label, model_name, ret))\n return ret\n","repo_name":"OpenDataPolicingNC/Traffic-Stops","sub_path":"traffic_stops/routers.py","file_name":"routers.py","file_ext":"py","file_size_in_byte":1775,"program_lang":"python","lang":"en","doc_type":"code","stars":25,"dataset":"github-code","pt":"17"} +{"seq_id":"33453171030","text":"import re\nfrom typing import Optional\n\n\ndef neg_literal(lit: str):\n return \"^\" + lit if lit[0] != \"^\" else lit[1:]\n\n\ndef get_sub_formulas(formula: str, P=\"P\", add_prefix = \"\") -> list:\n sub_formulas = []\n # split the formula to the different subformulas\n while re.search(\"(\\^\" + P + \"\\d+|[(][^()]*[)])\", formula) is not None:\n a = re.search(\"(\\^\" + P + \"\\d+)\", formula)\n if a is None:\n a = re.search(\"(\\^\" + P + \"\\d+|[(][^()]*[)])\", formula)\n start = a.start(0)\n end = a.end(0)\n sub_formulas.append(formula[start:end])\n formula = formula.replace(sub_formulas[-1], P + str(len(sub_formulas)) + add_prefix, 1)\n if not re.fullmatch(P + \"\\d+\", formula):\n sub_formulas.append(\"(\" + formula + \")\")\n return sub_formulas\n\n#\n# print(get_sub_formulas(\"2((3+5)+3.2f+(-53.2(-5s+4))-3d)+(3)\", P=\"!\",add_prefix=\"%\"))\n# print(get_sub_formulas(\"\", P=\"!\"))\n\n\ndef tseitin_to_cnf(formula: str, index: int) -> list:\n if re.fullmatch(\"\\^P\\d+\", formula):\n return [\"^P{0}|{1}\".format(index, formula), \"P{0}|{1}\".format(index, formula[1:])]\n formula = formula[1:-1] # move the brackets at the start and the end\n if \"<->\" in formula:\n literals = formula.split(\"<->\")\n cnf = [\n \"^P{0}|^{1}|{2}\".format(index, literals[0], literals[1]),\n \"^P{0}|{1}|^{2}\".format(index, literals[0], literals[1]),\n \"P{0}|{1}|{2}\".format(index, literals[0], literals[1]),\n \"P{0}|^{1}|^{2}\".format(index, literals[0], literals[1])\n ]\n return cnf\n if \"&\" in formula:\n sep = \"&\"\n literals = formula.split(sep)\n\n frml = formula.replace(\"&\", \"|^\")\n frml = \"P{0}|^{1}\".format(index, frml)\n cnf = [frml]\n for literal in literals:\n cnf.append(\"^P{0}|{1}\".format(index, literal))\n return cnf\n if \"->\" in formula:\n formula = \"^\" + formula.replace(\"->\", \"|\")\n if \"|\" in formula:\n sep = \"|\"\n literals = formula.split(sep)\n\n frml = \"^P{0}|{1}\".format(index, formula)\n cnf = [frml]\n for literal in literals:\n cnf.append(\"P{0}|^{1}\".format(index, literal))\n return cnf\n\n return [formula]\n\n\ndef tseitin_transformation(formula: str) -> list:\n \"\"\"\n\n :param formula:\n :return: the formula after performing tseitin's transformation.\n \"\"\"\n formula = formula.replace(\" \", \"\")\n sub_formulas = get_sub_formulas(formula)\n # change to CNF\n cnf_formulas = []\n for i in range(len(sub_formulas)):\n cnf_formulas += tseitin_to_cnf(sub_formulas[i], i + 1)\n cnf_formulas.append(\"P\" + str(len(sub_formulas)))\n\n return cnf_formulas\n\n\ndef preprocessing(cnf_formula: list) -> list:\n new_cnf_formula = []\n for frml in cnf_formula:\n frml = frml.replace(\"^^\", \"\")\n literals = frml.split(\"|\")\n normal = set([x for x in literals if x[0] != \"^\"])\n neg = set([x[1:] for x in literals if x[0] == \"^\"])\n if not normal.isdisjoint(neg):\n continue\n new_frml = \"|\".join(set(literals))\n if new_frml not in new_cnf_formula:\n new_cnf_formula.append(new_frml)\n return new_cnf_formula\n\n\ndef assign_literal(lit: str, t_assigned_order: list, t_assigned_dec: list, t_assigned_frml: list, frml=\"split\",\n offset=0):\n t_assigned_order.append(lit)\n t_assigned_frml.append(frml)\n if len(t_assigned_dec) == 0:\n t_assigned_dec.append(offset)\n else:\n t_assigned_dec.append(t_assigned_dec[-1] + offset)\n\n\n# def unit_propagation(cnf_formula: list, t_order: list, t_dec: list, t_frml: list) -> Optional[str]:\n# for frml in cnf_formula:\n# literals = frml.split(\"|\")\n# if not set(literals).isdisjoint(set(t_order)):\n# continue\n# new_literals = []\n# for lit in literals:\n# neg_lit = neg_literal(lit)\n# if neg_lit not in t_order:\n# new_literals.append(lit)\n# if len(new_literals) == 0:\n# return frml\n# if len(new_literals) == 1:\n# assign_literal(new_literals[-1], t_order, t_dec, t_frml, frml=frml)\n# return None\n\n\ndef reset_watch_literals(cnf_formula: list, watch_literals: list, t_order: list):\n for i in range(len(cnf_formula)):\n literals = cnf_formula[i].split(\"|\")\n if not set(literals).isdisjoint(set(t_order)):\n continue\n new_literals = []\n for lit in literals:\n neg_lit = neg_literal(lit)\n if neg_lit not in t_order:\n new_literals.append(lit)\n if len(new_literals) >= 2:\n break\n watch_literals[i] = new_literals\n\n\ndef update_watch_literals(cnf_formula: list, update_wtach: str, watch_literals: list, t_order: list):\n for i in range(len(cnf_formula)):\n literals = cnf_formula[i].split(\"|\")\n if not set(literals).isdisjoint(set(t_order)):\n continue\n neg = neg_literal(update_wtach)\n if neg in watch_literals[i]:\n new_literals = []\n for lit in literals:\n neg_lit = neg_literal(lit)\n if neg_lit not in t_order:\n new_literals.append(lit)\n if len(new_literals) >= 2:\n break\n watch_literals[i] = new_literals\n\n\ndef watch_propagation(cnf_formula: list, watch_literals: list, t_assigned_order: list, t_assigned_dec: list,\n t_assigned_frml: list):\n for i in range(len(cnf_formula)):\n literals = cnf_formula[i].split(\"|\")\n if not set(literals).isdisjoint(set(t_assigned_order)):\n continue\n if len(watch_literals[i]) == 0:\n return cnf_formula[i]\n if len(watch_literals[i]) == 1:\n assign_literal(watch_literals[i][0], t_assigned_order, t_assigned_dec, t_assigned_frml, frml=cnf_formula[i])\n update_watch_literals(cnf_formula, watch_literals[i][0], watch_literals, t_assigned_order)\n return None\n\n\ndef case_splitting(t_assigned_order: list, t_assigned_dec: list, t_assigned_frml: list, all_literals: list):\n for lit in all_literals:\n if lit not in t_assigned_order and neg_literal(lit) not in t_assigned_order:\n assign_literal(lit, t_assigned_order, t_assigned_dec, t_assigned_frml, offset=1)\n break\n\n\ndef DLIS(cnf: list, watch_literals: list, t_assigned_order: list, t_assigned_dec: list, t_assigned_frml: list):\n num_of_satisf_clauses = {}\n for frml in cnf:\n literals = frml.split(\"|\")\n if not set(literals).isdisjoint(set(t_assigned_order)):\n continue\n for lit in literals:\n if lit in t_assigned_order or neg_literal(lit) in t_assigned_order:\n continue\n if lit in num_of_satisf_clauses:\n num_of_satisf_clauses[lit] = num_of_satisf_clauses[lit] + 1\n else:\n num_of_satisf_clauses[lit] = 0\n lit_to_add = max(num_of_satisf_clauses, key=num_of_satisf_clauses.get)\n assign_literal(lit_to_add, t_assigned_order, t_assigned_dec,\n t_assigned_frml, offset=1)\n update_watch_literals(cnf, lit_to_add, watch_literals, t_assigned_order)\n\n\ndef check_assign_sat_cnf(cnf_formula: list, t_assigned: list) -> bool:\n for frml in cnf_formula:\n literals = frml.split(\"|\")\n if set(literals).isdisjoint(set(t_assigned)):\n return False\n return True\n\n\ndef check_one_lit_in_last_dec_lvl(lits: list, t_order: list, t_dec: list) -> bool:\n flag = False\n for lit in lits:\n indx = t_order.index(neg_literal(lit))\n if t_dec[indx] == t_dec[-1]:\n if flag:\n return False\n flag = True\n if flag:\n return True\n print(\"0 literals in the last dec lvl\")\n return False\n\n\ndef process_after_conflict(conflict_literals, lit_to_remove):\n frml = \"|\".join(conflict_literals)\n frml.replace(\"^^\", \"\")\n conflict_literals = frml.split(\"|\")\n conflict_literals = list(set(conflict_literals))\n conflict_literals.remove(lit_to_remove)\n conflict_literals.remove(neg_literal(lit_to_remove))\n return conflict_literals\n\n\ndef handle_conflict(conflict, t_order, t_dec, t_frml) -> str:\n conflict_literals = conflict.split(\"|\")\n for i in range(1, len(t_order) + 1):\n if check_one_lit_in_last_dec_lvl(conflict_literals, t_order, t_dec):\n break\n lit = t_order[-i]\n if neg_literal(lit) in conflict_literals:\n conflict_literals += t_frml[-i].split(\"|\")\n conflict_literals = process_after_conflict(conflict_literals, lit)\n return \"|\".join(conflict_literals)\n\n\ndef find_level_to_backjump(conflict, t_order, t_dec):\n dec_lvls = []\n for lit in conflict.split(\"|\"):\n indx = t_order.index(neg_literal(lit))\n dec_lvls.append(t_dec[indx])\n if len(dec_lvls) < 2:\n return 0\n dec_lvls.sort()\n return dec_lvls[-2]\n\n\ndef main():\n org_formula = \"(x1 <-> x2) & (x1 <-> ^x2)\"\n cnf = tseitin_transformation(org_formula)\n print(cnf)\n cnf = preprocessing(cnf)\n print(cnf)\n watch_literals = [cla.split(\"|\")[:2] for cla in cnf]\n all_literals = []\n for frml in cnf:\n all_literals += frml.split(\"|\")\n all_literals = list(set(all_literals))\n\n t_assigned_order = [] # the literal that get a True assignment\n t_assigned_dec = [] # the decision level\n t_assigned_frml = [] # the fornula we used (or \"split\" for case splitting\n\n print(org_formula)\n\n while True:\n old = len(t_assigned_order)\n # conflict = unit_propagation(cnf, t_assigned_order, t_assigned_dec, t_assigned_frml)\n conflict = watch_propagation(cnf, watch_literals, t_assigned_order, t_assigned_dec, t_assigned_frml)\n if conflict is not None:\n if t_assigned_dec[-1] == 0:\n print(\"UNSAT\")\n exit()\n conflict = handle_conflict(conflict, t_assigned_order, t_assigned_dec, t_assigned_frml)\n lvl_to_backjump = find_level_to_backjump(conflict, t_assigned_order, t_assigned_dec)\n indx_to_backjump = t_assigned_dec.index(lvl_to_backjump + 1)\n cnf.append(conflict)\n watch_literals.append([])\n t_assigned_order = t_assigned_order[:indx_to_backjump]\n t_assigned_dec = t_assigned_dec[:indx_to_backjump]\n t_assigned_frml = t_assigned_frml[:indx_to_backjump]\n reset_watch_literals(cnf, watch_literals, t_assigned_order)\n continue\n\n new = len(t_assigned_order)\n # cant propagate any more\n if old == new:\n if check_assign_sat_cnf(cnf, t_assigned_order):\n break\n DLIS(cnf, watch_literals, t_assigned_order, t_assigned_dec, t_assigned_frml)\n\n # complete the assignment to all the literals:\n old = 0\n new = 1\n while old != new:\n old = len(t_assigned_order)\n case_splitting(t_assigned_order, t_assigned_dec, t_assigned_frml, all_literals)\n new = len(t_assigned_order)\n\n # print the final assignment\n t_assigned_order.sort()\n print(\"SAT\")\n print([i for i in t_assigned_order if i[0] != \"P\" and i[:2] != \"^P\"])\n#\nif __name__ == \"__main__\":\n #print(get_sub_formulas(\"2((3+5)+3.2f+(-53.2(-5s+4))-3d)+(3)\", P=\"!\",add_prefix=\"%\"))\n #print(get_sub_formulas(\"\", P=\"!\"))\n #main()\n print(get_sub_formulas(\"3&(^3|2&(9&4)|1)\"))\n\n# cnf = [\n# \"x2|x3|^x4\",\n# \"^x2|^x1\",\n# \"^x3|^x4\",\n# \"x4|x5|x6\",\n# \"^x5|x7\",\n# \"^x6|x7|^x8\"\n# ]\n\n# t_assigned_order = [\"x1\", \"^x2\", \"x8\", \"^x7\", \"^x5\", \"^x6\", \"x4\", \"^x3\"]\n# t_assigned_dec = [0, 0, 1, 2, 2, 2, 2, 2]\n# t_assigned_frml = [\"split\", \"^x2|^x1\", \"split\", \"split\", \"^x5|x7\", \"^x6|x7|^x8\", \"x4|x5|x6\", \"^x3|^x4\"]\n","repo_name":"noamfluss42/AutomatedReasoningAboutSoftware","sub_path":"part_one.py","file_name":"part_one.py","file_ext":"py","file_size_in_byte":11819,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"17"} +{"seq_id":"37209968448","text":"# This is a sample Python script.\n\n# Press Shift+F10 to execute it or replace it with your code.\n# Press Double Shift to search everywhere for classes, files, tool windows, actions, and settings.\n\nimport math\n\nnu = 38E9\nc = 5.7E9\nk = 360E6\na = 1\nb = 10\n\nr = a\n\npq1 = k * r*r / (b*b) - c * k * r * r / ((2 * nu + c) * a * a) - 4 * nu * k * math.log(r / a) / (2 * nu + c) - k - c * k / (2 * nu + c)\n\nr = b\n\npq2 = k * r*r / (b*b) - c * k * r * r / ((2 * nu + c) * a * a) - 4 * nu * k * math.log(r / a) / (2 * nu + c) - k - c * k / (2 * nu + c)\n\nprint(pq1)\nprint(pq2)\n\np = 0.5E9\nq = 2.0E9\n\nr1 = a\nr2 = b\n\ndef Err(rs) :\n return ((-p + k * (rs * rs / (b * b) - 1)) - (-q + c * k / (2 * nu + c) * (rs * rs / (a * a) - 1) + 4 * k * nu / (2 * nu + c) * math.log(rs / a)))**2\n\nfor i in range(0, 200):\n\n err1 = Err(r1 + (r2 - r1) * 0.25)\n err2 = Err(r1 + (r2 - r1) * 0.75)\n print(str(i) + \" : \" + str(r1) + \" \" + str(r2) + \" : \" + str(err1) + \" \" + str(err2))\n if err1 < err2 :\n r2 = (r1 + r2) * 0.5\n else :\n r1 = (r1 + r2) * 0.5\n\n\n\n if(err1 == 0 and err2 == 0):\n break\n\nprint((r1 + r2) * 0.5)","repo_name":"WWWalenok/Kovalev","sub_path":"SFML/SFML/main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":1124,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"17"} +{"seq_id":"1264687526","text":"from typing import (\n Any,\n Optional,\n Union,\n List,\n Dict,\n)\n\nimport pandas as pd\nimport numpy as np\nfrom datetime import datetime\n\nfrom petrovisor.api.utils.helper import ApiHelper\n\nfrom petrovisor.api.protocols.protocols import SupportsRequests\nfrom petrovisor.api.protocols.protocols import SupportsItemRequests\nfrom petrovisor.api.protocols.protocols import SupportsSignalsRequests\nfrom petrovisor.api.protocols.protocols import SupportsDataFrames\n\n\n# Reference Table API calls\nclass RefTableMixin(SupportsDataFrames, SupportsSignalsRequests, SupportsItemRequests, SupportsRequests):\n \"\"\"\n Reference Table API calls\n \"\"\"\n\n # load reference table info\n def get_ref_table_data_info(self, name: str, **kwargs) -> Any:\n \"\"\"\n Get reference table data info\n\n Parameters\n ----------\n name : str\n Reference table name\n \"\"\"\n route = 'ReferenceTables'\n return self.get(f'{route}/{name}/ExistingData', **kwargs)\n\n # load reference table data\n def load_ref_table_data(self,\n name: str,\n entity: Union[str, Dict],\n date: Optional[Union[datetime, str]],\n **kwargs) -> Any:\n \"\"\"\n Load reference table data\n\n Parameters\n ----------\n name : str\n Reference table name\n entity : str, dict\n Entity object or Entity name\n date : str, datetime, None\n Date or None\n \"\"\"\n route = 'ReferenceTables'\n entity_name = ApiHelper.get_object_name(entity)\n date_str = self.get_json_valid_value(date, 'time', **kwargs)\n if date_str is None:\n date_str = ''\n return self.get(f'{route}/{name}/Data/{entity_name}/{date_str}', **kwargs)\n\n # save reference table data\n def save_ref_table_data(self,\n name: str,\n entity: Union[str, Dict],\n date: Optional[Union[datetime, float]],\n data: Union[Dict[float, float], List, pd.DataFrame],\n **kwargs) -> Any:\n \"\"\"\n Save reference table data\n\n Parameters\n ----------\n name : str\n Reference table name\n entity : str, dict\n Entity object or Entity name\n date : str, datetime, None\n Date or None\n data : dict, list, DataFrame\n Reference Table Data\n \"\"\"\n route = 'ReferenceTables'\n entity_name = ApiHelper.get_object_name(entity)\n date_str = self.get_json_valid_value(date, 'time', **kwargs)\n if date_str is None:\n date_str = ''\n # prepare data\n if isinstance(data, dict):\n return self.put(f'{route}/{name}/Data/{entity_name}/{date_str}', data=data, **kwargs)\n else:\n # convert list to dictionary\n def __list_to_dict(x, num_cols, **kwargs):\n if num_cols == 0:\n return {\n self.get_json_valid_value(idx, 'numeric', **kwargs):\n self.get_json_valid_value(row, 'numeric', **kwargs) for idx, row in enumerate(x)}\n elif num_cols == 1:\n return {\n self.get_json_valid_value(idx, 'numeric', **kwargs):\n self.get_json_valid_value(row[0], 'numeric', **kwargs) for idx, row in enumerate(x)}\n elif num_cols > 1:\n return {\n self.get_json_valid_value(row[0], 'numeric', **kwargs):\n self.get_json_valid_value(row[1], 'numeric', **kwargs) for row in x}\n return {}\n if isinstance(data, (list, np.ndarray, pd.DataFrame, pd.Series)):\n num_cols = ApiHelper.get_num_cols(data)\n if num_cols is None:\n raise ValueError(f\"PetroVisor::save_ref_table_data(): \"\n f\"number of columns in the list should be either 2 or 1.\")\n ref_table = __list_to_dict(ApiHelper.to_list(data, **kwargs), num_cols, **kwargs)\n else:\n raise ValueError(f\"PetroVisor::save_ref_table_data(): \"\n f\"invalid data format '{type(data)}'. \"\n f\"Should be either dict[float,float], list of iterables, DataFrame, Series or array.\")\n return self.put(f'{route}/{name}/Data/{entity_name}/{date_str}', data=ref_table, **kwargs)\n\n # delete reference table data\n def delete_ref_table_data(self,\n name: str,\n entity: Union[str, Dict],\n date: Optional[Union[datetime, float]],\n **kwargs) -> Any:\n \"\"\"\n Delete reference table data\n\n Parameters\n ----------\n name : str\n Reference table name\n entity : str, dict\n Entity object or Entity name\n date : str, datetime, None\n Date or None\n \"\"\"\n route = 'ReferenceTables'\n entity_name = ApiHelper.get_object_name(entity)\n date_str = self.get_json_valid_value(date, 'time', **kwargs)\n if date_str is None:\n date_str = ''\n return self.delete(f'{route}/{name}/Data/{entity_name}/{date_str}', **kwargs)\n ","repo_name":"Datagration/petrovisor-python-api","sub_path":"src/petrovisor/api/methods/reference_tables.py","file_name":"reference_tables.py","file_ext":"py","file_size_in_byte":5499,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"17"} +{"seq_id":"15081409924","text":"# -*- coding: utf-8 -*-\r\n# Time: 2020-04-01 15:28\r\n# Author: Landers1037\r\n# Mail: liaorenj@gmail.com\r\n# File: exit.py\r\nfrom . import api\r\nfrom app import db\r\nfrom app.model import Pig\r\nfrom flask import request,jsonify\r\nimport time\r\nimport os\r\n\r\n@api.route(\"/api/data\")\r\ndef getdata():\r\n \"\"\"\r\n 获取全部数据库数据 暂时未做分片处理\r\n :return:\r\n \"\"\"\r\n if request.args.get(\"id\"):\r\n id = request.args.get(\"id\")\r\n try:\r\n i = Pig.query.get(int(id))\r\n\r\n d = {\r\n \"id\":i.id,\r\n \"date\": i.date,\r\n \"name\":i.name,\r\n \"sex\":i.sex,\r\n \"age\":i.age,\r\n \"illtime\":i.illtime,\r\n \"phone\":i.phone,\r\n \"parent\":i.parent,\r\n \"work\":i.work,\r\n \"address\":i.address,\r\n \"detail\":i.detail,\r\n \"solution\":i.solution,\r\n \"addon\":i.addon,\r\n \"money\":i.money,\r\n \"doc\": i.doc\r\n }\r\n return jsonify(d)\r\n except:\r\n return jsonify(\"bad\")\r\n else:\r\n try:\r\n #默认的首页只显示20条数据\r\n #计算任务交给前端\r\n\r\n # list = Pig.query.order_by(Pig.id.desc()).limit(20).all()\r\n list = Pig.query.order_by(Pig.id.desc()).all()\r\n data = []\r\n for i in list:\r\n d = {\r\n \"id\": i.id,\r\n \"date\": i.date,\r\n \"name\": i.name,\r\n \"phone\": i.phone,\r\n \"address\": i.address,\r\n \"detail\": i.detail\r\n }\r\n data.append(d)\r\n\r\n return jsonify(data)\r\n\r\n except:\r\n return jsonify(\"bad\")\r\n\r\n\r\n@api.route(\"/api/add\",methods=[\"POST\"])\r\ndef adddata():\r\n \"\"\"\r\n 添加一条数据\r\n :return:\r\n \"\"\"\r\n if request.json:\r\n data = request.json\r\n now = time.strftime(\"%H:%M:%S\",time.localtime())\r\n\r\n try:\r\n date = data[\"date\"]\r\n name = data[\"name\"]\r\n sex = data[\"sex\"]\r\n age = data[\"age\"]\r\n illtime = data[\"illtime\"]\r\n phone = data[\"phone\"]\r\n parent = data[\"parent\"]\r\n work = data[\"work\"]\r\n address = data[\"address\"]\r\n detail = data[\"detail\"]\r\n solution = data[\"solution\"]\r\n addon = data[\"addon\"]\r\n money = data[\"money\"]\r\n doc = data[\"doc\"]\r\n newitem = Pig(date=date,time=now,name=name,sex=sex,age=age,\r\n illtime=illtime,phone=phone,parent=parent,\r\n work=work,address=address,detail=detail,\r\n solution=solution,addon=addon,money=money,doc=doc\r\n )\r\n db.session.add(newitem)\r\n db.session.commit()\r\n\r\n return \"ok\"\r\n except Exception as e:\r\n print(e.args)\r\n\r\n return \"bad\"\r\n return \"bad\"\r\n\r\n@api.route(\"/api/edit\",methods=[\"POST\"])\r\ndef edit():\r\n \"\"\"\r\n 修改更新数据\r\n :return:\r\n \"\"\"\r\n if request.json:\r\n data = request.json\r\n try:\r\n id = data[\"id\"]\r\n date = data[\"date\"]\r\n name = data[\"name\"]\r\n sex = data[\"sex\"]\r\n age = data[\"age\"]\r\n illtime = data[\"illtime\"]\r\n phone = data[\"phone\"]\r\n parent = data[\"parent\"]\r\n work = data[\"work\"]\r\n address = data[\"address\"]\r\n detail = data[\"detail\"]\r\n solution = data[\"solution\"]\r\n addon = data[\"addon\"]\r\n money = data[\"money\"]\r\n doc = data[\"doc\"]\r\n\r\n edititem = Pig.query.get(int(id))\r\n edititem.date = date\r\n edititem.name = name\r\n edititem.sex = sex\r\n edititem.age = age\r\n edititem.illtime = illtime\r\n edititem.phone= phone\r\n edititem.parent = parent\r\n edititem.work = work\r\n edititem.address = address\r\n edititem.detail = detail\r\n edititem.solution = solution\r\n edititem.addon = addon\r\n edititem.money = money\r\n edititem.doc = doc\r\n\r\n db.session.commit()\r\n\r\n return \"ok\"\r\n except Exception as e:\r\n print(e.args)\r\n\r\n return \"bad\"\r\n return \"bad\"\r\n\r\n@api.route(\"/api/se\",methods=[\"GET\"])\r\n#按名称等信息搜索\r\ndef search():\r\n try:\r\n r = request.args\r\n if r.get(\"name\"):\r\n name = r.get(\"name\")\r\n list = Pig.query.filter(Pig.name.contains(name)).all()\r\n data = []\r\n for i in list:\r\n d = {\r\n \"id\":i.id,\r\n \"date\":i.date,\r\n \"name\":i.name,\r\n \"phone\":i.phone,\r\n \"address\":i.address\r\n }\r\n data.append(d)\r\n\r\n return jsonify(data)\r\n\r\n elif r.get(\"date\"):\r\n date = r.get(\"date\")\r\n list = Pig.query.filter(Pig.date.contains(date)).all()\r\n data = []\r\n for i in list:\r\n d = {\r\n \"id\": i.id,\r\n \"date\": i.date,\r\n \"name\": i.name,\r\n \"phone\": i.phone,\r\n \"address\": i.address\r\n }\r\n data.append(d)\r\n\r\n return jsonify(data)\r\n\r\n elif r.get(\"sex\"):\r\n sex = r.get(\"sex\")\r\n list = Pig.query.filter(Pig.sex==sex).all()\r\n data = []\r\n for i in list:\r\n d = {\r\n \"id\": i.id,\r\n \"date\": i.date,\r\n \"name\": i.name,\r\n \"phone\": i.phone,\r\n \"address\": i.address\r\n }\r\n data.append(d)\r\n\r\n return jsonify(data)\r\n\r\n elif r.get(\"phone\"):\r\n phone = r.get(\"phone\")\r\n list = Pig.query.filter(Pig.name.contains(phone)).all()\r\n data = []\r\n for i in list:\r\n d = {\r\n \"id\": i.id,\r\n \"date\": i.date,\r\n \"name\": i.name,\r\n \"phone\": i.phone,\r\n \"address\": i.address\r\n }\r\n data.append(d)\r\n\r\n return jsonify(data)\r\n else:\r\n return jsonify(\"bad\")\r\n except:\r\n return jsonify(\"bad\")\r\n\r\n@api.route(\"/api/del\",methods=[\"POST\"])\r\ndef delitem():\r\n \"\"\"\r\n 删除数据\r\n :return:\r\n \"\"\"\r\n if request.json:\r\n id = request.json[\"id\"]\r\n try:\r\n p = Pig.query.get(int(id))\r\n db.session.delete(p)\r\n db.session.commit()\r\n\r\n return jsonify(\"ok\")\r\n except:\r\n return jsonify(\"bad\")\r\n else:\r\n return jsonify(\"bad\")\r\n\r\n\r\n@api.route(\"/api/info\")\r\ndef getinfo():\r\n \"\"\"\r\n 获取数据库全局信息\r\n :return:\r\n \"\"\"\r\n try:\r\n db_size = os.path.getsize(os.path.join(os.getcwd(), 'pig.db'))\r\n db_count = Pig.query.count()\r\n db_backups = os.listdir(os.path.join(os.getcwd(),\"backup\"))\r\n return jsonify({\r\n \"size\": db_size//1000,\r\n \"count\": db_count,\r\n \"new_bk\": db_backups[-1].replace(\"pig-\",\"\").replace(\".db\",\"\")\r\n })\r\n except BaseException as e:\r\n print(e.args)\r\n return jsonify(\"bad\")","repo_name":"Landers1037/pigform","sub_path":"flask-backend/pigform/app/views/data.py","file_name":"data.py","file_ext":"py","file_size_in_byte":7832,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"17"} +{"seq_id":"14290262017","text":"import sys\nn,m = map(int,sys.stdin.readline().split())\nl = list(map(int,sys.stdin.readline().split()))\nsl = []\nco = 0\nco_num = []\nmax = 0\nfor i in l:\n if i not in sl:\n sl.append(i)\nprint(sl)\nco = len(sl)\nfor i in sl:\n co_num.append(l.count(i))\nprint(co_num)\nfor i in co_num:\n if max < i:\n max = i\nprint(max)\nfor k in range(max,0,-1):\n for i in range(co):\n if co_num[i] == k:\n for j in range(k,0,-1):\n print(sl[i],end=' ')\n ","repo_name":"skatlqja3/Baekjoon_Online_Judge_Test","sub_path":"2910.py","file_name":"2910.py","file_ext":"py","file_size_in_byte":489,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"17"} +{"seq_id":"9903466584","text":"import boto3\n\nfrom config import s3_bucket, s3_key, s3_secret\n\n\ndef upload_s3(file, key_name, content_type):\n # create connection\n conn = boto3.client(\"s3\", s3_key, s3_secret, )\n\n # upload the file after getting the right bucket\n bucket = conn.get_bucket(s3_bucket)\n\n obj = S3Key(bucket)\n obj.name = key_name\n obj.content_type = content_type\n obj.set_contents_from_string(file.getvalue())\n obj.set_acl('public-read')\n\n # fermer le fichier\n file.close()\n\n return obj.generate_url(expires_in=0, query_auth=False)\n","repo_name":"Yassine-BADJI/onzbar-api","sub_path":"external_ressource/bucket_s3.py","file_name":"bucket_s3.py","file_ext":"py","file_size_in_byte":547,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"17"} +{"seq_id":"33630439423","text":"# -*- coding: utf-8 -*-\n\nimport sys\nimport click\nfrom jira import JIRAError\nfrom jinja2 import Environment, PackageLoader\n\n\n# Jinja2 templates\nenv = Environment(loader=PackageLoader('jirainfo'),\n trim_blocks=True,\n lstrip_blocks=True)\n\n\ndef printErrorMsg(msg):\n click.echo(click.style(msg, fg='red'))\n\ndef printJiraErrorAndExit(e):\n #errmsg = 'ERROR - Jira error({0}): {1}'.format(e.status_code, e.text)\n errmsg = 'Jira error: {0}'.format(e.status_code)\n printErrorMsg(errmsg)\n sys.exit(1)\n\ndef readIssuesFromInput(input):\n result = []\n for line in input:\n result.append(line.strip(' ').rstrip('\\n'))\n\n return result\n\ndef getIssuesOrExit(jira, issueKeys):\n try:\n issues = jira.getIssues(issueKeys)\n except JIRAError as e:\n printJiraErrorAndExit(e)\n\n return issues\n\ndef getSummaryOrExit(jira, issueKey):\n try:\n summary = jira.getSummary(issueKey)\n except JIRAError as e:\n printJiraErrorAndExit(e)\n\n return summary\n\ndef compileEmailTemplate(issues):\n template = env.get_template('email.html')\n return template.render(issues=issues)\n\ndef compileChangelogTemplate(features, bugs, others, meta):\n template = env.get_template('changelog.md')\n return template.render(features=features, bugs=bugs, others=others, meta=meta)\n\ndef exitIfNoHost(ctx):\n errorMsg = \"\"\"Error: Jira host is not specified! Please, use the --host option or specify the Jira host as an environment variable (JIRAINFO_HOST).\n \"\"\"\n if not 'host' in ctx.obj or not ctx.obj['host']:\n printErrorMsg(errorMsg)\n #click.echo(ctx.get_help())\n ctx.exit(1)\n","repo_name":"hypebeast/jira-info","sub_path":"jirainfo/helpers.py","file_name":"helpers.py","file_ext":"py","file_size_in_byte":1668,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"17"} +{"seq_id":"37627564224","text":"load(\"@bazel_tools//tools/build_defs/repo:utils.bzl\", \"maybe\")\nload(\"//build/kernel/kleaf:key_value_repo.bzl\", \"key_value_repo\")\nload(\n \"//build/kernel/kleaf/impl:kernel_prebuilt_repo.bzl\",\n \"kernel_prebuilt_repo\",\n)\nload(\n \"//build/kernel/kleaf/impl:kernel_prebuilt_utils.bzl\",\n \"CI_TARGET_MAPPING\",\n)\nload(\"//build/kernel/kleaf/impl:kleaf_host_tools_repo.bzl\", \"kleaf_host_tools_repo\")\nload(\n \"//build/kernel/kleaf/impl:local_repository.bzl\",\n \"kleaf_local_repository\",\n \"new_kleaf_local_repository\",\n)\nload(\"//prebuilts/clang/host/linux-x86/kleaf:register.bzl\", \"register_clang_toolchains\")\n\n# buildifier: disable=unnamed-macro\ndef define_kleaf_workspace(\n common_kernel_package = None,\n include_remote_java_tools_repo = False,\n artifact_url_fmt = None):\n \"\"\"Common macro for defining repositories in a Kleaf workspace.\n\n **This macro must only be called from `WORKSPACE` or `WORKSPACE.bazel`\n files, not `BUILD` or `BUILD.bazel` files!**\n\n If [`define_kleaf_workspace_epilog`](#define_kleaf_workspace_epilog) is\n called, it must be called after `define_kleaf_workspace` is called.\n\n Args:\n common_kernel_package: Default is `\"@//common\"`. The package to the common\n kernel source tree.\n\n As a legacy behavior, if the provided string does not start with\n `@` or `//`, it is prepended with `@//`.\n\n Do not provide the trailing `/`.\n include_remote_java_tools_repo: Default is `False`. Whether to vendor two extra\n repositories: remote_java_tools and remote_java_tools_linux.\n\n These respositories should exist under `//prebuilts/bazel/`\n artifact_url_fmt: API endpoint for Android CI artifacts.\n The format may include anchors for the following properties:\n * {build_number}\n * {target}\n * {filename}\n \"\"\"\n\n if common_kernel_package == None:\n common_kernel_package = str(Label(\"//common:x\")).removesuffix(\":x\")\n if not common_kernel_package.startswith(\"@\") and not common_kernel_package.startswith(\"//\"):\n common_kernel_package = str(Label(\"//{}:x\".format(common_kernel_package))).removesuffix(\":x\")\n\n # buildifier: disable=print\n print(\"\"\"\nWARNING: define_kleaf_workspace() should be called with common_kernel_package={}.\n This will become an error in the future.\"\"\".format(\n repr(common_kernel_package),\n ))\n\n maybe(\n repo_rule = kleaf_local_repository,\n name = \"bazel_skylib\",\n path = \"external/bazel-skylib\",\n )\n\n maybe(\n repo_rule = kleaf_local_repository,\n name = \"io_abseil_py\",\n path = \"external/python/absl-py\",\n )\n\n maybe(\n repo_rule = kleaf_local_repository,\n name = \"io_bazel_stardoc\",\n path = \"external/stardoc\",\n )\n\n # Superset of all tools we need from host.\n # For the subset of host tools we typically use for a kernel build,\n # see //build/kernel:hermetic-tools.\n kleaf_host_tools_repo(\n name = \"kleaf_host_tools\",\n host_tools = [\n \"bash\",\n \"perl\",\n \"rsync\",\n \"sh\",\n # For BTRFS (b/292212788)\n \"find\",\n ],\n )\n\n # External repos without Bazel support.\n # https://docs.bazel.build/versions/main/external.html#non-bazel-projects\n new_kleaf_local_repository(\n name = \"prebuilt_ndk\",\n path = \"prebuilts/ndk-r26\",\n build_file = \"build/kernel/kleaf/ndk.BUILD\",\n )\n\n kleaf_workspace_name = Label(\"//build/kernel/kleaf\").workspace_name\n new_kleaf_local_repository(\n name = \"libcap\",\n path = \"external/libcap\",\n build_file = \"build/kernel/kleaf/libcap.BUILD\",\n repo_mapping = {\"@kleaf\": \"@\" + kleaf_workspace_name},\n )\n\n new_kleaf_local_repository(\n name = \"libcap_ng\",\n path = \"external/libcap-ng\",\n build_file = \"build/kernel/kleaf/libcap_ng.BUILD\",\n )\n\n key_value_repo(\n name = \"kernel_toolchain_info\",\n srcs = [\"{}:build.config.constants\".format(common_kernel_package)],\n additional_values = {\n \"common_kernel_package\": common_kernel_package,\n },\n )\n\n for repo_name in CI_TARGET_MAPPING:\n kernel_prebuilt_repo(\n name = repo_name,\n artifact_url_fmt = artifact_url_fmt,\n )\n\n # TODO(b/200202912): Re-route this when rules_python is pulled into AOSP.\n kleaf_local_repository(\n name = \"rules_python\",\n path = \"build/bazel_common_rules/rules/python/stubs\",\n )\n\n # The following 2 repositories contain prebuilts that are necessary to the Java Rules.\n # They are vendored locally to avoid the need for CI bots to download them.\n if include_remote_java_tools_repo:\n kleaf_local_repository(\n name = \"remote_java_tools\",\n path = \"prebuilts/bazel/common/remote_java_tools\",\n )\n\n kleaf_local_repository(\n name = \"remote_java_tools_linux\",\n path = \"prebuilts/bazel/linux-x86_64/remote_java_tools_linux\",\n )\n\n # Use checked-in JDK from prebuilts as local_jdk\n # Needed for stardoc\n # Note: This was not added directly to avoid conflicts with roboleaf,\n # see https://android-review.googlesource.com/c/platform/build/bazel/+/2457390\n # for more details.\n new_kleaf_local_repository(\n name = \"local_jdk\",\n path = \"prebuilts/jdk/jdk11/linux-x86\",\n build_file = \"build/kernel/kleaf/jdk11.BUILD\",\n )\n\n # Fake rules_cc to avoid fetching it for any py_binary targets.\n kleaf_local_repository(\n name = \"rules_cc\",\n path = \"build/kernel/kleaf/impl/fake_rules_cc\",\n )\n\n # Stub out @remote_coverage_tools required for testing.\n kleaf_local_repository(\n name = \"remote_coverage_tools\",\n path = \"build/bazel_common_rules/rules/coverage/remote_coverage_tools\",\n )\n\n # Use checked-in JDK from prebuilts as local_jdk\n # Needed for stardoc\n native.register_toolchains(\n \"@local_jdk//:all\",\n )\n\n # Label(): Resolve the label against this extension (register.bzl) so the\n # workspace name is injected properly when //prebuilts is in a subworkspace.\n # str(): register_toolchains() only accepts strings, not Labels.\n native.register_toolchains(\n str(Label(\"//prebuilts/build-tools:py_toolchain\")),\n str(Label(\"//build/kernel:hermetic_tools_toolchain\")),\n )\n\n register_clang_toolchains()\n","repo_name":"msft-mirror-aosp/kernel.build","sub_path":"kleaf/workspace.bzl","file_name":"workspace.bzl","file_ext":"bzl","file_size_in_byte":6490,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"17"} +{"seq_id":"8212610518","text":"# 첫 번째 수를 뺀 결과 키 조회 (1. Two Sum)\nimport sys\nsys.stdin = open('input.txt')\n\nnums = list(map(int, input().split()))\ntarget = int(input())\n\nnums_map = {}\n# 키와 값을 바꿔서 딕셔너리로 저장\nfor i, num in enumerate(nums):\n nums_map[num] = i\n\nprint(nums_map)\n\n# 타켓에서 첫 번째 수를 뺀 결과를 키로 조회\nfor i, num in enumerate(nums):\n if target - num in nums_map and i != nums_map[target - num]:\n print([nums.index(num), nums_map[target - num]])\n break\n\n## 조회 구조 개선\nnums_map = {}\n# 하나의 for 문으로 통합\nfor i, num in enumerate(nums):\n if target - num in nums_map:\n print([nums_map[target - num], i])\n break\n nums_map[num] = i","repo_name":"glass93/algorithm-problem-solving","sub_path":"파이썬 알고리즘 인터뷰/07_배열/07_두 수의 합/첫 번째 수를 뺀 결과 키 조회.py","file_name":"첫 번째 수를 뺀 결과 키 조회.py","file_ext":"py","file_size_in_byte":735,"program_lang":"python","lang":"ko","doc_type":"code","stars":2,"dataset":"github-code","pt":"17"} +{"seq_id":"72256771864","text":"import numpy as np\nimport pandas as pd\nimport random\n\nwith open('/home/xueho/coding_challenges/sudoku.txt', 'r') as f:\n lines = f.readlines()\n\nb=[]\nfor line in lines:\n line = list(line.strip(\"'\"))\n line = [c for c in line if c not in (' ', '\\n')]\n line = [int(c) if c != '_' else c for c in line ]\n b.append(line) \n\nboard = pd.DataFrame(b,index = ['r1','r2','r3','r4','r5','r6','r7','r8','r9'],\n columns = ['c1','c2','c3','c4','c5','c6','c7','c8','c9'])\n\n# generate dictionary of missing values for each small square\n\nfull_set = {1,2,3,4,5,6,7,8,9}\n \ndef sq_missing(df):\n \"\"\"get missing values in each 3x3 square \"\"\"\n \n all_nums = []\n for i in range(0,3):\n nums = [n for n in df.iloc[i] if n != '_' ]\n all_nums.extend(nums)\n missing = full_set - set(all_nums)\n return list(missing)\n\ndef sq_dic(df):\n m_dic = {}\n for i in range(0,3):\n for j in range(0,3):\n tmp = df.iloc[i*3:(i*3+3), j*3:(j*3+3)]\n m_dic[i*3+j] = sq_missing(tmp)\n return m_dic \n\ndef mis_pos_in_square(df_sq,k):\n m_pos = []\n for i in range(0,3):\n for j in range(0,3):\n if df_sq.iloc[i,j] == '_':\n r = i+3*(k//3)\n c = j+3*(k%3)\n m_pos.append((r,c))\n\n return list(set(m_pos))\n\ndef mis_pos_in_squares(df):\n \"\"\"Record positions for '_' on the whole board. \"\"\"\n \n # loop through squares\n all_pos = []\n for i in range(3):\n for j in range(3):\n df1 = df.iloc[i*3:(i*3+3), j*3:(j*3+3)]\n k = 3*i+j\n m_pos = mis_pos_in_square(df1,k)\n all_pos.extend(m_pos) \n\n return all_pos\n\ndef fill_board(df, sq_miss):\n w = df.shape[0]\n filled_pos = []\n for row in range(w):\n exist_num_row = [x for x in df.iloc[row] if x !='_']\n for col in range(w):\n exist_num_col = [y for y in df.iloc[:, col] if y !='_'] \n \n if df.iloc[row, col] == '_':\n k = 3*(row//3) + col//3\n df1 = df.iloc[3*(row//3):3*(row//3)+3, 3*(col//3):3*(col//3)+3]\n for v in sq_miss[k]:\n if v not in df1.values and v not in exist_num_row and v not in exist_num_col:\n df.iloc[row, col] = v\n filled_pos.append((row, col, v))\n exist_num_row = [x for x in df.iloc[row] if x !='_']\n exist_num_col = [y for y in df.iloc[:, col] if y !='_'] \n \n return df, filled_pos \n\nif __name__ == '__main__':\n full_set = {1,2,3,4,5,6,7,8,9}\n sq_mis = sq_dic(board)\n finished, filled_pos = fill_board(board, sq_mis)\n print(finished)\n print()\n print(finished[finished=='_'].count().sum())\n ","repo_name":"Xuehong-pdx/python-code-challenge","sub_path":"sudoku.py","file_name":"sudoku.py","file_ext":"py","file_size_in_byte":2779,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"17"} +{"seq_id":"41115660245","text":"import unittest\nfrom src.pub import Pub\nfrom src.customer import Customer\nfrom src.drink import Drink\n\nclass TestPub(unittest.TestCase):\n def setUp(self):\n self.drink1 = Drink(\"shots\", 10, 7)\n self.drink2 = Drink(\"spirits\", 20, 5)\n self.drinks_collection = [self.drink1, self.drink2]\n self.pub = Pub(\"The Goose\", 190, self.drinks_collection)\n self.customer = Customer(\"Johnny Bravo\", 50, 23)\n\n def test_sell_drink_increases_till_amount(self):\n self.pub.sell_drink(self.customer, self.drink2)\n self.assertEqual(210, self.pub.till)\n\n\n\n \n # def setUp(self):\n # self.pub = Pub(\"The Prancing Pony\", 100.00)\n\n # def test_pub_has_name(self):\n # self.assertEqual(\"The Prancing Pony\", self.pub.name)","repo_name":"mz-biddy01/Pub-Lab","sub_path":"tests/pub_test.py","file_name":"pub_test.py","file_ext":"py","file_size_in_byte":768,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"17"} +{"seq_id":"86500558276","text":"import copy\nfrom .table_att_loss import TableAttentionLoss\n\n\ndef build_loss(config):\n support_dict = ['TableAttentionLoss']\n\n config = copy.deepcopy(config)\n module_name = config.pop('name')\n assert module_name in support_dict, Exception('loss only support {}'.format(\n support_dict))\n module_class = eval(module_name)(**config)\n return module_class\n","repo_name":"June-Li/TableRecognition","sub_path":"utils/losses/__init__.py","file_name":"__init__.py","file_ext":"py","file_size_in_byte":375,"program_lang":"python","lang":"en","doc_type":"code","stars":9,"dataset":"github-code","pt":"17"} +{"seq_id":"25665591351","text":"from django.shortcuts import render, redirect\nfrom .models import Notes, Homework\nfrom .forms import *\nfrom django.contrib import messages\nfrom django.views import generic\nfrom youtubesearchpython import VideosSearch\nimport requests\nimport wikipedia\nfrom django.contrib.auth.decorators import login_required\n\n# Create your views here.\n\ndef home(request):\n return render(request, 'dashboard/home.html')\n@login_required(login_url = 'login')\ndef notes(request):\n if request.method == 'POST':\n form = NotesForm(request.POST)\n if form.is_valid():\n notes = Notes(user = request.user, title = request.POST['title'], description = request.POST['description'])\n notes.save()\n messages.success(request, f\"Notes Added Successfully By {request.user.username}\")\n return redirect('notes')\n \n else:\n form = NotesForm()\n notes = Notes.objects.filter(user = request.user)\n context = {'notes' : notes, 'form':form}\n return render(request, 'dashboard/notes.html', context)\n\n\ndef notes_delete(request, pk = None):\n Notes.objects.get(id = pk).delete()\n return redirect('notes')\n\nclass NotesDetailView(generic.DetailView):\n model = Notes\n \n@login_required(login_url = 'login') \ndef homework(request):\n if request.method == 'POST':\n form = HomeworkForm(request.POST) \n if form.is_valid():\n try:\n finished = request.POST['is_finished']\n if finished == 'on':\n finished = True\n else:\n finished = False\n except:\n finished = False\n \n homework = Homework(\n user = request.user,\n subject = request.POST['subject'],\n title = request.POST['title'],\n description = request.POST['description'],\n due = request.POST['due'],\n is_finished = finished\n )\n homework.save()\n messages.success(request, f'Homework added form {request.user.username}!!')\n return redirect('homework')\n \n else:\n form = HomeworkForm()\n homeworks = Homework.objects.filter()\n if len(homeworks) == 0:\n homework_done = True\n else:\n homework_done = False\n context = {'homework' : homeworks, 'homework_done' : homework_done, \"form\": form}\n return render(request, 'dashboard/homework.html', context)\n \n \ndef update_homework(request, pk):\n homework = Homework.objects.get(id = pk)\n if homework.is_finished == True:\n homework.is_finished = False\n else:\n homework.is_finished = True\n homework.save()\n return redirect('homework')\n\ndef delete_homework(request, id):\n homework = Homework.objects.get(id = id).delete()\n return redirect('homework')\n\n\ndef youtube(request):\n if request.method == 'POST':\n form = DashboardForm(request.POST)\n text = request.POST['text']\n video = VideosSearch(text, limit = 10)\n result_list = []\n \n for i in video.result()['result']:\n \n result_dict = {\n 'input' : text,\n 'title' : i['title'],\n 'duration' : i['duration'],\n 'thumbnail' : i['thumbnails'][0]['url'],\n 'channel' : i['channel']['name'],\n 'link' : i['link'],\n 'views' : i['viewCount']['short'],\n 'published' : i['publishedTime'],\n }\n desc = ''\n if i['descriptionSnippet']:\n for j in i['descriptionSnippet']:\n desc += j['text']\n result_dict['description'] = desc\n result_list.append(result_dict)\n context = {\n 'form': form,\n 'results' : result_list\n }\n return render(request, 'dashboard/youtube.html', context)\n \n else:\n form = DashboardForm()\n context = {'form' : form}\n return render(request, 'dashboard/youtube.html', context)\n\n@login_required\ndef todo(request):\n todo = Todo.objects.filter(user = request.user)\n if request.method == \"POST\":\n form = TodoForm(request.POST)\n if form.is_valid():\n try:\n finished = request.POST['is_finished']\n if finished == 'on':\n finished = True\n else:\n finished = False\n except:\n finished = False\n \n todo = Todo(\n user = request.user,\n title = request.POST['title'],\n is_finished = finished\n )\n todo.save()\n messages.success(request, f'To do added successfully from {request.user}')\n return redirect('todo')\n else:\n form = TodoForm()\n context = {'todos' : todo, 'form' : form}\n return render(request, 'dashboard/todo.html', context)\n\ndef update_todo(request, id):\n todo = Todo.objects.get(id = id)\n if todo.is_finished:\n todo.is_finished = False\n else:\n todo.is_finished = True\n todo.save()\n return redirect('todo')\n\ndef delete_todo(request, id):\n Todo.objects.get(id = id).delete()\n return redirect('todo')\n\ndef books(request):\n if request.method == 'POST':\n form = DashboardForm(request.POST)\n text = request.POST['text']\n url = \"https://www.googleapis.com/books/v1/volumes?q=\" + text\n r = requests.get(url)\n r.raise_for_status()\n answer = r.json()\n \n result_list = []\n\n \n \n for i in range(10): \n result_dict = {\n 'title' : answer['items'][i]['volumeInfo']['title'],\n #'subtitle' : answer['items'][i]['volumeInfo']['subtitle'],\n 'description' : answer['items'][i]['volumeInfo']['description'],\n 'count' : answer['items'][i]['volumeInfo']['pageCount'],\n 'categories' : answer['items'][i]['volumeInfo']['categories'],\n #'rating' : answer['items'][i]['volumeInfo']['averageRating'],\n 'thumbnail' : answer['items'][i]['volumeInfo']['imageLinks']['thumbnail'],\n 'preview' : answer['items'][i]['volumeInfo']['previewLink'],\n \n \n }\n result_list.append(result_dict)\n \n context = {\n 'form': form,\n 'results' : result_list\n }\n return render(request, 'dashboard/books.html', context)\n \n else:\n form = DashboardForm()\n context = {'form' : form}\n return render(request, 'dashboard/books.html', context)\n\n\ndef dictionary(request):\n if request.method == 'POST':\n form = DashboardForm(request.POST)\n text = request.POST['text']\n url = \"https://api.dictionaryapi.dev/api/v2/entries/en_US/\" + text\n r = requests.get(url)\n r.raise_for_status()\n answer = r.json()\n print('first line------------------->\\n',answer[0]['phonetics'])\n print()\n print('second line------------------->\\n', answer[0]['meanings'][1])\n try:\n phonetics = answer[0]['phonetics'][0]['text']\n audio = answer[0]['phonetics'][0]['audio']\n difinition = answer[0]['meanings'][0]['definitions'][0]['definition']\n example = answer[0]['meanings'][1]['definitions'][1]['example']\n synonyms = answer[0]['meanings'][0]['definitions'][0]['synonyms']\n \n context = {\n 'form': form,\n 'phonetics' : phonetics,\n 'audio' : audio,\n 'definition' : difinition,\n 'example' : example,\n 'synosyms' : synonyms,\n 'input' : text,\n }\n except:\n context = {\n 'form' : form,\n 'input' : text,\n }\n return render(request, 'dashboard/dictionary.html', context)\n else:\n form = DashboardForm()\n context = {'form' : form}\n return render(request, 'dashboard/dictionary.html', context)\n\n\ndef wiki(request):\n if request.method == 'POST':\n text = request.POST['text']\n form = DashboardForm(request.POST)\n search = wikipedia.page(text)\n print('------------------------------------------------------------------>')\n print(search.summary)\n print('--------------------------------------------------------------->')\n context = {\n 'form' : form,\n 'title' : search.title,\n 'link' : search.link,\n 'details' : search.summary,\n }\n return render(request, 'dashboard/wiki.html', context)\n form = DashboardForm()\n context = {\n 'form' : form,\n }\n return render(request, 'dashboard/wiki.html', context)\n\n\ndef conversion(request):\n if request.method == 'POST':\n form = ConversionForm(request.POST)\n if request.POST.get('measurement') == 'length':\n measurment_form = LenghtConversionForm()\n context ={\n 'form' : form,\n 'm_form': measurment_form,\n 'input' : True,\n }\n \n if 'input' in request.POST:\n first = request.POST['measure1']\n second = request.POST['measure2']\n input_value = request.POST['input']\n answer = ''\n \n if input_value and int(input_value) >= 0:\n if first == 'yard' and second == 'foot':\n answer = f'{input_value} yard = {int(input_value)*3} foot'\n if first == 'foot' and second == 'yard':\n answer = f'{input_value} foot = {int(input_value)/3} yard'\n context = {\n 'form': form,\n 'm_form': measurment_form,\n 'input': True,\n 'answer': answer\n }\n return render(request, 'dashboard/conversion.html', context)\n if request.POST.get('measurement') == 'mass':\n measurment_form = MassConversionForm(request.POST)\n if 'input' in request.POST:\n first = request.POST['measure1']\n second = request.POST['measure2']\n input_value = request.POST['input']\n answer = ''\n if input_value and int(input_value) >= 0:\n if first == 'pound' and second == 'kilogram':\n answer = f'{input_value} pound = {int(input_value) * 0.453592} kilogram'\n if first == 'kilogram' and second == 'pound':\n answer = f'{input_value} kilogram = {int(input_value) * 2.20462} pound'\n context = {\n 'form': form,\n 'm_form': measurment_form,\n 'input': True,\n 'answer': answer\n }\n \n return render(request, 'dashboard/conversion.html', context)\n\n else:\n form = ConversionForm()\n\n context = {\n 'form': form,\n 'input': False,\n }\n return render(request, 'dashboard/conversion.html', context)\n\n\ndef register(request):\n if request.method == 'POST':\n form = UserRegistrationForm(request.POST)\n if form.is_valid():\n form.save()\n username = form.cleaned_data.get('username')\n messages.success(request, f'Account is created for {username} !!')\n return redirect('login')\n\n else: \n form = UserRegistrationForm()\n contex = {\n 'form' : form\n }\n return render(request, 'dashboard/register.html', contex)\n\n@login_required(login_url = 'login')\ndef profile(request):\n homework = Homework.objects.filter(is_finished = False, user = request.user)\n todo = Todo.objects.filter(is_finished = False, user = request.user)\n print(len(homework), len(todo))\n if len(homework) == 0:\n homework_done = True\n else:\n homework_done = False\n if len(todo) == 0 :\n todo_done = True\n else:\n todo_done = False\n \n context = {\n 'homeworks' : homework,\n 'todos' : todo,\n 'homework_done' : homework_done,\n 'todo_done' : todo_done,\n }\n for i in list(homework):\n print(i.id)\n print(homework_done, todo_done)\n return render(request, 'dashboard/profile.html', context)","repo_name":"ravan2763/StudentStudyPortal","sub_path":"StudyPortal/dashboard/views.py","file_name":"views.py","file_ext":"py","file_size_in_byte":12523,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"17"} +{"seq_id":"22688148804","text":"import pandas as pd\nimport numpy as np\nfrom keras.models import Sequential\nfrom keras.layers.core import Dense, Dropout, Activation\nfrom keras.optimizers import SGD, adam\nfrom keras.layers.normalization import BatchNormalization\nfrom keras.utils import to_categorical\n# read in data\ndata_train = pd.read_csv('train.csv')\ndata_val = pd.read_csv('test.csv')\n\nnames_train = data_train['Name']\nnames_val = data_val['Name']\n# drop columns that do not correlate with survival / have significant gaps\ndata_train = data_train.drop(['Cabin', 'Name', 'PassengerId', 'Fare', 'Embarked'], axis=1)\ndata_val = data_val.drop(['Cabin', 'Name', 'PassengerId', 'Fare', 'Embarked'], axis=1)\ndata = [data_train, data_val]\n\nclasses = ['Deceased', 'Survived']\n\ndef vec_to_description(person):\n\tdescription = \"\"\n\talone = None\n\tticket = None\n\tif person[0] == 1:\n\t\tsex = \"Male\"\n\telse:\n\t\tsex = \"Female\"\n\tif person[1] == 1:\n\t\talone = \"with large family\"\n\tif person[2] == 1:\n\t\talone = \"alone\"\n\tif person[3] == 1:\n\t\tage = \"Child\"\n\tif person[4] == 1:\n\t\tage = \"Young adult\"\n\tif person[5] == 1:\n\t\tage = \"Adult\"\n\tif person[6] == 1:\n\t\tage = \"Elderly\"\n\tif person[7] == 1:\n\t\tticket = \"travelling in first class\"\n\tif person[8] == 1:\n\t\tticket = \"travelling in second class\"\n\tif person[9] == 1:\n\t\tticket = \"travelling in third class\"\n\n\tif(ticket is None):\n\t\tticket = \"travelling in UNKNOWN\"\n\tif(alone is None):\n\t\talone = \"with companion / or family with 4 members or less\"\n\tdescription = (\"{0}, {1}, {2} {3}\").format(age, sex, ticket, alone)\n\n\treturn description\n\nfor d in data:\n\t'''\n\tPreprocessing\n\t1. Map columns containing strings to binary numerical values\n\t 1 = male, 0 = female\n\t2. Identify and flag large families, families with 5 or more\n\t members had significantly lower survival rates\n\t3. Identify and flag solo travellers, they had lower survival rates\n\t4. If age is not known for a person then populate with median\n\t5. Create age groups for child, young adult, adult and old\n\t6. Group by ticket class\n\t'''\n\t# Create new columns for relevant groups\n\td['largeFam'] = 0\n\td['Alone'] = 0\n\td['Child'] = 0\n\td['YoungA'] = 0\n\td['Adult'] = 0\n\td['Old'] = 0\n\td['First_class'] = 0\n\td['Second_class'] = 0\n\td['Third_class'] =0\n\n\t# 1. Convert sex to binary numerical values\n\td['Sex'] = d['Sex'].map({ 'male': 1, 'female': 0}).astype(int)\n\n\t# 2. Identify + flag large groups/families\n\td.loc[d['SibSp'] + d['Parch'] + 1 > 4, 'largeFam'] = 1\n\t\n\t# 3. Identify + flag solo travellers\n\td.loc[d['SibSp'] + d['Parch'] + 1 == 1, 'Alone'] =1\n\n\t# 4. Set blank ages to median age\n\td.loc[d.Age.isnull(), 'Age'] = d.Age.median()\n\t\n\t# 5. Group passengers by age\n\td.loc[d['Age'] <= 16, 'Child'] = 1\n\td.loc[(d['Age'] > 16) & (d['Age'] <= 30), 'YoungA'] = 1\n\td.loc[(d['Age'] > 30) & (d['Age'] <= 60), 'Adult'] = 1\n\td.loc[d['Age'] > 60, 'Old'] = 1\n\n\t#6. Group passengers by ticket class\n\td.loc[d['Pclass'] == 1, 'First_class'] = 1\n\td.loc[d['Pclass'] == 2, 'Second_class'] = 1\n\td.loc[d['Pclass'] == 3, 'Third_class'] = 1\n\n\n# Drop columns we don't need any more from training/validation set\n# We've moved these into groups above\ndata_train = data_train.drop(['Ticket', 'Parch', 'SibSp', 'Age', 'Pclass'], axis=1)\ndata_val = data_val.drop(['Ticket', 'Parch', 'SibSp', 'Age', 'Pclass'], axis=1)\n\n# Set target column to predict (Survived)\ntargets = np.array(to_categorical(data_train['Survived'], 2))\n\n# Set features we are trying to correlate to target\nfeatures = np.array(data_train.drop('Survived', axis=1))\nfeatures_val = np.array(data_val)\n\n# Set neural net architecture\n# 2 simple fully connected layers with relu activation\n# output layer will have 2 nodes (len classes) with softmax activation\n# to provide probability score\nmodel = Sequential()\nmodel.add(Dense(512))\nmodel.add(BatchNormalization())\nmodel.add(Activation('relu'))\nmodel.add(Dropout(.2))\nmodel.add(Dense(256))\nmodel.add(BatchNormalization())\nmodel.add(Activation('relu'))\nmodel.add(Dropout(.2))\nmodel.add(Dense(len(classes), activation='softmax'))\n\nmodel.compile(loss = 'categorical_crossentropy', optimizer='SGD', metrics=['accuracy'])\n\n\nmodel.fit(features, targets, epochs=100, batch_size=32, verbose=1)\n\np = model.predict(features_val)\nfor i, x in enumerate(p):\n\tn = names_val[i]\n\td = features_val[i]\n\td = vec_to_description(d)\n\tmortality = classes[np.argmax(x)]\n\tif (mortality == 'Deceased'):\n\t\tprob = x[0]\n\telse:\n\t\tprob = x[1]\n\t\n\tprint(\"\\n\\n\\n\\n{0}\\n________________________________________\\nDescription: {1}\".format(n, d)) \n\tprint(\"Prediction: {0} ({1:.1%} probability)\".format(mortality, prob))\n\nscore = model.evaluate(features, targets)\nprint (\"\\nEstimated accuracy: {:.0%}\".format(score[1]))\n\t\n","repo_name":"blairharper/dl-titanic","sub_path":"titanic.py","file_name":"titanic.py","file_ext":"py","file_size_in_byte":4615,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"17"} +{"seq_id":"74022879385","text":"# 문자열 word가 주어질 때, 해당 문자열에서 a 개수를 구하세요.\n# count() 메서드 사용 금지\n# input : apple\n# output : 1\n\n\nword = input()\ncount = 0\n\nfor i in word:\n if i == 'a':\n count += 1\n\nprint(count)","repo_name":"BuildEnough/TIL2","sub_path":"알고리즘/노션파이썬문제/잡다한 문제/문제14_문자의_갯수_구하기.py","file_name":"문제14_문자의_갯수_구하기.py","file_ext":"py","file_size_in_byte":239,"program_lang":"python","lang":"ko","doc_type":"code","stars":2,"dataset":"github-code","pt":"17"} +{"seq_id":"28365802770","text":"'''\r\nBlue Bird\r\n'''\r\nimport pygame\r\nimport time\r\nimport random\r\nimport sys\r\nimport os\r\nfrom pygame.locals import *\r\n\r\nos.environ['SDL_VIDEO_WINDOW_POS'] = \"%d,%d\" % (450, 200)\r\n\r\npygame.init()\r\n\r\n\r\nclass Window():\r\n \r\n def __init__(self):\r\n self.size = (700, 500)\r\n self.GUI = pygame.display.set_mode(self.size, 1, 32)\r\n pygame.display.set_caption('Blue Bird')\r\n self.bg_image = pygame.image.load('forest_landscape_klein.png')\r\n self.icon = pygame.image.load('flat-flying-bird-icon.jpg')\r\n pygame.display.set_icon(self.icon)\r\n \r\n def background(self):\r\n self.GUI.fill((0, 0, 0))\r\n self.GUI.blit(self.bg_image, (0, 0))\r\n \r\n\r\nclass Bird():\r\n \r\n def __init__(self, GUI):\r\n self.pos_x = 80\r\n self.pos_y = 360\r\n self.ascend = 25\r\n self.fall = 5\r\n self.GUI = GUI\r\n self.bird_flying = pygame.image.load('Figur_Flügel_unten_klein.png')\r\n self.bird_sinking = pygame.image.load('Figur_Flügel_oben_klein.png')\r\n \r\n def update(self):\r\n if pygame.event.peek(MOUSEBUTTONDOWN):\r\n self.pos_y -= self.ascend\r\n self.GUI.GUI.blit(self.bird_flying, (self.pos_x - 25, self.pos_y - 25))\r\n else:\r\n self.pos_y += self.fall\r\n self.GUI.GUI.blit(self.bird_sinking, (self.pos_x - 25, self.pos_y - 25))\r\n pygame.event.clear()\r\n \r\n\r\nclass Obstacle():\r\n \r\n def __init__(self, GUI, x_pos):\r\n self.GUI = GUI\r\n self.pos_x = x_pos\r\n self.narrow_top = random.randrange(200, 350)\r\n self.narrow_bottom = self.narrow_top + 100\r\n self.width = 25\r\n self.color = (139, 69, 19)\r\n \r\n def set(self):\r\n pygame.draw.rect(self.GUI.GUI, self.color,\r\n (self.pos_x, 0, self.width, self.narrow_top))\r\n pygame.draw.rect(self.GUI.GUI, self.color,\r\n (self.pos_x, self.narrow_bottom, self.width, 500))\r\n \r\n def move(self):\r\n self.pos_x -= 5\r\n\r\n\r\ndef check_collision(bird, obstacle ):\r\n if (bird.pos_x + 25 > obstacle.pos_x and\r\n bird.pos_x - 25 < obstacle.pos_x + obstacle.width and\r\n (bird.pos_y - 25 < obstacle.narrow_top or\r\n bird.pos_y + 25 > obstacle.narrow_bottom)):\r\n return True\r\n elif bird.pos_y - 25 < 0 or bird.pos_y + 25 > 500:\r\n return True\r\n else:\r\n return False\r\n\r\n\r\ndef game_over(start, end, Interface):\r\n played_time = int(end - start)\r\n font1 = pygame.font.SysFont('Arial', 35)\r\n font2 = pygame.font.SysFont('Arial', 25)\r\n bg_image = pygame.image.load('laurel-wreath-297040_1280.png')\r\n Interface.GUI.fill((255, 255, 255))\r\n Interface.GUI.blit(bg_image, (0, 0))\r\n text = font1.render('Sie haben {} Sekunden geschaft!'. format(played_time),\r\n 1, (255,215,0))\r\n text2 = font2.render('klicken Sie um erneut zu spielen.', 1, (0, 0, 0))\r\n Interface.GUI.blit(text, (130, 200))\r\n Interface.GUI.blit(text2, (200, 300))\r\n pygame.display.update()\r\n while True:\r\n if pygame.event.peek(QUIT):\r\n pygame.quit()\r\n sys.exit()\r\n elif pygame.event.peek(MOUSEBUTTONDOWN):\r\n game()\r\n time.sleep(0.05)\r\n \r\n\r\ndef game():\r\n global Bird\r\n GUI = Window()\r\n bird = Bird(GUI)\r\n\r\n obstacles = []\r\n positions = {0}\r\n \r\n for number in range(1, 151):\r\n position = set((random.randrange(500, 8000, 200), 0))\r\n positions = positions ^ position\r\n \r\n positions = list(positions)\r\n positions.pop(0)\r\n positions.sort()\r\n \r\n for position in positions:\r\n obstacles.append(Obstacle(GUI, position))\r\n\r\n pygame.mixer.init()\r\n pygame.mixer.music.load('a_brilliant_idea_terrasound.mp3')\r\n pygame.mixer.music.play(loops = -1, start = 0.0)\r\n\r\n Font_time = pygame.font.SysFont('Arial', 30)\r\n\r\n start_time = time.time()\r\n \r\n while True:\r\n if pygame.event.peek(QUIT):\r\n pygame.quit()\r\n sys.exit()\r\n GUI.background()\r\n bird.update()\r\n for obstacle in obstacles:\r\n obstacle.move()\r\n if obstacle.pos_x < 700 and obstacle.pos_x > 0:\r\n obstacle.set()\r\n if check_collision(bird, obstacle):\r\n #print('collision')\r\n end_time = time.time()\r\n game_over(start_time, end_time, GUI)\r\n if obstacles[len(obstacles) - 1].pos_x < 0:\r\n end_time = time.time()\r\n pygame.quit()\r\n game_over(start_time, end_time, GUI)\r\n\r\n runned_time = Font_time.render('%d sek' % (time.time() - start_time),\r\n 1, (0, 0, 0))\r\n GUI.GUI.blit(runned_time, (20, 20))\r\n pygame.display.update()\r\n time.sleep(0.05)\r\n\r\n\r\nif __name__ == '__main__':\r\n game()\r\n","repo_name":"Jonny2019/Jonny2019.github.io","sub_path":"Homepage/Blue Bird.pyw","file_name":"Blue Bird.pyw","file_ext":"pyw","file_size_in_byte":4931,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"17"} +{"seq_id":"21152000001","text":"import os\nimport tempfile\nimport torch\nimport torch.distributed as dist\nimport torch.nn as nn\nimport torch.optim as optim\nimport torch.multiprocessing as mp\nimport torch.multiprocessing as mp\nfrom torch.multiprocessing import Process\nimport random\nimport time\nimport numpy as np\nfrom torch.nn.parallel import DistributedDataParallel as DDP\n\ndef sync_initial_weights(model, rank, world_size):\n for param in model.parameters():\n if rank == 0:\n # Rank 0 is sending it's own weight\n # to all it's siblings (1 to world_size)\n for sibling in range(1, world_size):\n dist.send(param.data, dst=sibling)\n else:\n # Siblings must recieve the parameters\n dist.recv(param.data, src=0)\n\ndef average_model(model, rank, world_size):\n for param in model.parameters():\n dist.all_reduce(param.data, op=dist.ReduceOp.SUM)\n param.data = param.data/world_size\n \ndef sync_gradients(model, rank, world_size):\n for param in model.parameters():\n dist.all_reduce(param.grad.data, op=dist.ReduceOp.SUM)\n param.grad.data = param.grad.data/world_size\n\ndef setup(rank, world_size):\n os.environ['MASTER_ADDR'] = 'localhost'\n os.environ['MASTER_PORT'] = '12355'\n\n # initialize the process group\n dist.init_process_group(\"gloo\", rank=rank, world_size=world_size)\n\n # Explicitly setting seed to make sure that models created in two processes\n # start from same random weights and biases.\n torch.manual_seed(42)\n\ndef cleanup():\n dist.destroy_process_group()\n\nclass Net(nn.Module):\n def __init__(self):\n super(Net, self).__init__()\n self.il = nn.Linear(1,80)\n self.mi = nn.Linear(80,80)\n self.mi2 = nn.Linear(80,40)\n self.ol = nn.Linear(40,1)\n self.relu = nn.ReLU()\n def forward(self,x):\n hidden1 = self.il(x)\n hissen2 = self.mi(self.relu(hidden1))\n hissen3 = self.mi2(self.relu(hissen2))\n act = self.relu(hissen3)\n out = self.ol(act)\n return out\nN=80000\nBS = 10000\nM = 4 #number of gpu threads\nepocs = 20000\n\nx_in = [(20.0/N)*random.randint(0,N) for i in range(N)]\ndef yfun(i):\n return np.sqrt(i)*np.sin(4*3.14*i/20.0)\ny_vals = [yfun(i) for i in x_in]\n\ndef mk_minibatch(i, size): \n s = int(size)\n my_in = x_in[s*i: s*(i+1)]\n my_vals = y_vals[s*i: s*(i+1)]\n return (my_in, my_vals)\n\nbatches = [mk_minibatch(i, BS) for i in range(int(N/BS))]\nk = len(batches)\nbatch = []\ns = 0\nfor i in range(M):\n bat = []\n for j in range(int(k/M)):\n bat.append(batches[s+j])\n batch.append(bat)\n s+= int(k/M)\n\ndef batchtodev(rank, device):\n btch =batch[rank]\n devb = []\n for x in btch:\n xin = torch.tensor([x[0]], device=device).T\n yin = torch.tensor([x[1]], device=device).T\n devb.append((xin, yin))\n return devb\n\ndef run(rank, size):\n setup(rank, size)\n #determine my device IDs. \n n = torch.cuda.device_count() // size\n device_ids = list(range(rank * n, (rank + 1) * n))\n # create model and move it to device_ids[0]\n device = device_ids[0]\n model = Net().to(device)\n \n sync_initial_weights(model, rank, size)\n btch = batchtodev(rank, device)\n print('batch has ', len(btch), ' elements')\n print(\"len of btch[0][0] =\", len(btch[0][0]))\n\n loss_fn = nn.MSELoss()\n optimizer = optim.SGD(model.parameters(), lr=0.005)\n sync_freq =10\n for epoc in range(1, epocs):\n for b in btch:\n optimizer.zero_grad()\n outputs = model(b[0])\n loss = loss_fn(outputs,b[1])\n loss.backward()\n if epoc % sync_freq == 0:\n sync_gradients(model, rank, world_size)\n optimizer.step()\n if epoc % 200 == 0:\n average_model(model,rank, size)\n \n if epoc % 1000 == 0:\n print('epoc %d loss %f'%(epoc, float(loss)))\n if rank == 0:\n torch.save(model.state_dict(), \"/tmp/model\")\n\n cleanup()\n\n\ndef launch(demo_fn, world_size):\n mp.spawn(demo_fn,\n args=(world_size,),\n nprocs=world_size,\n join=True)\n\n\nif __name__ == \"__main__\":\n t0 = time.time()\n launch(run, M)\n print('elapsed = ', time.time()-t0)\n\n x_in = [0.025*random.randint(0,800) for i in range(800)]\n def yfun(i):\n return np.sqrt(i)*np.sin(4*3.14*i/20.0)\n y_vals = [yfun(i) for i in x_in]\n inputs = torch.tensor([x_in]).T\n targets = torch.tensor([y_vals]).T\n m0 = Net()\n m0.load_state_dict(torch.load(\"/tmp/model\"))\n mouts = m0(inputs)\n loss_fn = nn.MSELoss()\n err = loss_fn(mouts, targets)\n print(\"err =\", err)\n","repo_name":"dbgannon/torch","sub_path":"distributed-learn-gpu-final.py","file_name":"distributed-learn-gpu-final.py","file_ext":"py","file_size_in_byte":4665,"program_lang":"python","lang":"en","doc_type":"code","stars":4,"dataset":"github-code","pt":"17"} +{"seq_id":"40500753046","text":"import pickle\nimport EvaluatePhrase\nimport random\ndef main(num_round):\n input_list = pickle.load(open(\"../Datasets/processed/test_input_list.pkl\", \"rb\"))\n label_list = pickle.load(open(\"../Datasets/processed/test_label_list.pkl\", \"rb\"))\n \n total_acc = 0\n total_wrong_rate = 0\n total_improper_rate = 0\n for i in range(num_round):\n acc, wrong_rate, improper_rate = random_fingering(input_list, label_list)\n total_acc = acc + total_acc\n total_wrong_rate = wrong_rate + total_wrong_rate\n total_improper_rate = improper_rate + total_improper_rate\n if (i + 1) % 1000 == 0:\n print(\"Round \", i + 1, (len(str(num_round)) - len(str(i + 1))) * ' ',\"average acc is\", total_acc / (i + 1), \"average wrong rate is\", total_wrong_rate / (i+1), \"average improper rate is\", total_improper_rate / (i+1))\n\ndef random_fingering(input_list, label_list):\n test_set_abs_true = 0\n test_set_abs_false = 0\n test_set_improper = 0\n for i in range(len(input_list)):\n \n random_f = []\n for j in range(len(label_list[i])): \n random_f.append(random.randint(1,5))\n phrase_abs_true, phrase_abs_false, phrase_improper = EvaluatePhrase.main(input_list[i], random_f, label_list[i])\n test_set_abs_true = test_set_abs_true + phrase_abs_true\n test_set_abs_false = test_set_abs_false + phrase_abs_false\n test_set_improper = test_set_improper + phrase_improper\n return test_set_abs_true / sum(len(phrase) for phrase in (label_list)), test_set_abs_false / sum(len(phrase) for phrase in (input_list)), test_set_improper / sum(len(phrase) for phrase in (input_list))\nmain(10000)","repo_name":"guwalgiya/Piano-Fingering-Generators","sub_path":"LSTM Approach/SelfDataSetRelated/RandomFingeringTest.py","file_name":"RandomFingeringTest.py","file_ext":"py","file_size_in_byte":1760,"program_lang":"python","lang":"en","doc_type":"code","stars":12,"dataset":"github-code","pt":"17"} +{"seq_id":"1899723798","text":"from flask import Flask, abort, flash, redirect, render_template, session, url_for, request\nfrom flask.ext.qrcode import QRcode\n\nfrom os import urandom, path, getpid\nfrom binascii import hexlify\nimport inspect\nimport logging\n\nimport requests as req\n\nimport json\n\n\ndef run():\n flask_options = dict(port=PORT, host='0.0.0.0', debug=True)\n app.secret_key = hexlify(urandom(24))\n app.run(**flask_options)\n\n\ndef save_pid():\n \"\"\"Save pid into a file: filename.pid.\"\"\"\n pidfilename = inspect.getfile(inspect.currentframe()) + \".pid\"\n f = open(pidfilename, 'w')\n f.write(str(getpid()))\n f.close()\n\n\ndef generate_url(host, protocol='http', port=80, directory=''):\n\n if isinstance(directory, list):\n directory = '/'.join(directory)\n\n return \"%s://%s:%d/%s\" % (protocol, host, port, directory)\n\n\napp = Flask(__name__, static_url_path=\"\", static_folder='static')\nQRcode(app)\n\nMY_IP = req.get(generate_url('jsonip.com')).json()['ip']\nPORT = 88\n\n\n@app.route('/')\ndef root():\n return redirect(url_for('index'))\n\n\n@app.route('/index')\ndef index():\n return render_template('index.html', about_url=generate_url(MY_IP, port=PORT, directory=url_for('about')[1:]))\n\n\n@app.route('/about', methods=['GET'])\ndef about():\n return render_template('about.html')\n\n\"\"\"\n@app.route('/api/count-terms', methods=['POST'])\ndef api_count_terms():\n return json.dumps()\n\"\"\"\n\nif __name__ == '__main__':\n\n save_pid()\n\n logfilename = inspect.getfile(inspect.currentframe()) + \".log\"\n logging.basicConfig(filename=logfilename, level=logging.INFO, format='%(asctime)s %(message)s')\n logging.info(\"Started\")\n\n run()\n","repo_name":"danielperezr88/ConceptInsight","sub_path":"ConceptInsight.py","file_name":"ConceptInsight.py","file_ext":"py","file_size_in_byte":1637,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"17"} +{"seq_id":"72469814104","text":"#Question 2\ndef smaller(x, a, b):\n count = 0\n for i in x:\n if (b > i):\n count = count + 1\n return count\n\n\n\nx = []\ns = int(input(\"Input the number of elements: \"))\nprint(\"Enter array elements: \")\nfor j in range(0,s):\n no = int(input())\n x.append(no)\n\nn = int(input(\"Please enter n:\"))\nans = smaller(x, s, n)\nprint(\"answer: \", ans)\n\n\n","repo_name":"anas-zafar/DataScience","sub_path":"Question2.py","file_name":"Question2.py","file_ext":"py","file_size_in_byte":365,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"17"} +{"seq_id":"14725071006","text":"from typing import List\n\n\nclass Solution:\n def combinationSum(self, candidates: List[int], target: int) -> List[List[int]]:\n res = []\n subset = []\n\n def dfs(options, remainder):\n if remainder == 0:\n res.append(subset.copy())\n return\n if remainder < 0:\n return\n if not options:\n return\n\n subset.append(options[0])\n dfs(options, remainder - options[0])\n subset.pop()\n dfs(options[1:], remainder)\n\n dfs(candidates, target)\n return res\n","repo_name":"Wh0DKnee/InterviewPrep","sub_path":"Backtracking/combination_sum.py","file_name":"combination_sum.py","file_ext":"py","file_size_in_byte":607,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"17"} +{"seq_id":"7165517341","text":"from entity import Entity\nfrom vectors import Vector2D\n\nclass Particle(Entity):\n def __init__(self, x, y):\n Entity.__init__(self, x, y)\n \n def update(self, dt):\n self.position += self.velocity*dt\n self.acceleration = self.Fnet*self.invMass\n self.velocity += self.acceleration*dt\n self.Fnet = Vector2D()\n \n \n \n","repo_name":"jclarkrichards/PhysicsEngine","sub_path":"particle.py","file_name":"particle.py","file_ext":"py","file_size_in_byte":360,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"17"} +{"seq_id":"39800239389","text":"__author__ = 'student'\n\nfrom sock1_reader_writer.reader_writer import reader_writer\nfrom socket import socket\n\nsock = socket()\n\nsock.connect(('localhost',12347))\n\nprint(\"Connection made\")\n\nrw = reader_writer(sock)\n\n\n\nrw.write('1 ')\nfor i in range(2,40):\n rw.write(' ' + str(i) + ' * ')\n\nrw.close_write()\n\nprint(\"sending done\")\n\nc = rw.read()\nwhile c:\n print(c,end='')\n c = rw.read()\n\nsock.close()","repo_name":"bangour2/Pyhton-codes-project","sub_path":"class-140911-sockets/class-140911-sockets/sock3-rpn/client2.py","file_name":"client2.py","file_ext":"py","file_size_in_byte":405,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"17"} +{"seq_id":"1658439047","text":"# Recursion Method\n# def binarySearch(fullList, start, end, number):\n# if end > start:\n# mid = start + (end - start) // 2\n# middleElement = fullList[mid]\n# if middleElement == number:\n# return mid\n# elif middleElement < number:\n# start = mid + 1\n# return binarySearch(fullList, start, end, number)\n# else:\n# end = mid - 1\n# return binarySearch(fullList, start, end, number)\n# else:\n# return -1\n\n# Iteration method\ndef binarySearch(fullList, start, end, number):\n while end > start:\n mid = start + (end - start) // 2\n middleElement = fullList[mid]\n if middleElement == number:\n return mid\n elif middleElement < number:\n start = mid + 1\n else:\n end = mid - 1\n else:\n return -1\n\n\nif __name__ == '__main__':\n # aList = [1, 7, 9, 20, 40, 80, 87, 93, 102, 117]\n aList = []\n elementsCount = int(input('Enter number of elements: '))\n print('Enter elements')\n for i in range(elementsCount):\n element = int(input())\n aList.append(element)\n searchElement = int(input('Search for element: '))\n index = binarySearch(aList, 0, len(aList)-1, searchElement)\n if index == -1:\n print('Element not found.')\n else:\n print('index of element', index)","repo_name":"surendragalwa11/data-structures","sub_path":"searches/binary-search.py","file_name":"binary-search.py","file_ext":"py","file_size_in_byte":1380,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"17"} +{"seq_id":"26097610826","text":"import pygame\nimport display\n\nclass unit(object):\n\tdef __init__ (self, x, y):\n\t\tself.x = x\n\t\tself.y = y\n\t\tself.frame = 1.0\n\t\t\nclass player (unit):\n\tdef __init__(self, x, y):\n\t\tsuper (player, self).__init__(x, y)\n\t\tself.spritesheet = display.load(\"human_base.png\")\n\t\tself.mapping = {\n\t\t\t\"up\" : createTupleList(0) ,\n\t\t\t\"right\": createTupleList(18),\n\t\t\t\"down\" : createTupleList(36),\n\t\t\t\"left\" : createTupleList(54)\n\t\t}\n\t\tself.facing = \"down\"\n\t\tself.speed = .5\n\t\tself.moving = False\n\t\tself.mask = pygame.mask.Mask((16,16))\n\t\t\n\tdef update(self):\n\t\tif self.moving:\n\t\t\tself.frame = (self.frame + self.speed) % 4\n\t\t\n\tdef render(self, surface):\n\t\tsurface.blit(self.spritesheet, \n\t\t\t (504, 504, 16, 16),\n\t\t\t\t\t self.mapping[self.facing][int(self.frame)])\n\t\n\tdef handler(self, event):\n\t\tif event.type == pygame.KEYDOWN:\n\t\t\tif event.key == pygame.K_UP:\n\t\t\t\t# self.y -= 1\n\t\t\t\t# if self.y < 0:\n\t\t\t\t\t# self.y = 0\n\t\t\t\tself.facing = \"up\"\n\t\t\telif event.key == pygame.K_DOWN:\n\t\t\t\t# self.y += 1\n\t\t\t\t# if self.y > (999 - 16):\n\t\t\t\t\t# self.y = 999 - 16\n\t\t\t\tself.facing = \"down\"\n\t\t\telif event.key == pygame.K_LEFT:\n\t\t\t\t# self.x -= 1\n\t\t\t\t# if self.x < 0:\n\t\t\t\t\t# self.x = 0\n\t\t\t\tself.facing = \"left\"\n\t\t\telif event.key == pygame.K_RIGHT:\n\t\t\t\t# self.x += 1\n\t\t\t\t# if self.x > (999 - 16):\n\t\t\t\t\t# self.x = 999 - 16\n\t\t\t\tself.facing = \"right\"\n\t\t\tself.moving = True\n\t\t\t\n\t\telif event.type == pygame.KEYUP:\n\t\t\tself.moving = False\n\t\t\tself.frame = 1\n\t\t\t\t\t\ndef createTupleList(num):\n\tlist = []\n\tfor i in range(3):\n\t\tlist.append((16 * i, num , 16, 18))\n\tlist.append((16, num, 16, 18))\n\treturn list","repo_name":"poweleri/Code_Duze","sub_path":"units.py","file_name":"units.py","file_ext":"py","file_size_in_byte":1565,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"17"} +{"seq_id":"26930066297","text":"arr = [4, 3, 6, 2, 1, 1]\n\nlst = [0] * len(arr)\nfor i in arr:\n lst[i-1] += 1\n\nfor i in range(len(lst)):\n if lst[i] == 0:\n print(\"missing : \",str(i+1))\n elif lst[i] ==2:\n print(\"repeating : \",str(i+1))","repo_name":"mrlancelot/CodingPractice","sub_path":"SDE_Sheet/repeating_missing.py","file_name":"repeating_missing.py","file_ext":"py","file_size_in_byte":222,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"17"} +{"seq_id":"71270707226","text":"#!/usr/bin/env python\n# encoding: utf-8\n\"\"\"\n@author: zhangchao\n@file: 077_find-co-occurrence-number\n@time: 2023/8/23 20:25\n@project: huawei-od-python\n@desc: 077 找出两个整数数组中同时出现的整数\n\"\"\"\nfrom collections import Counter, defaultdict\n\n\ndef solve_method(nums1, nums2):\n c1 = Counter(nums1)\n c2 = Counter(nums2)\n\n c = c1 & c2\n if not c:\n return \"NULL\"\n else:\n freq_num = defaultdict(list)\n # 得到每个次数下对应的整数\n for k, v in c.items():\n freq_num[v].append(k)\n\n # 对次数按从小到大排序\n freq_num = dict(sorted(freq_num.items(), key=lambda x: x[0]))\n # 将每个次数下的整数从小到大排序\n freq_num = {k: sorted(v) for k, v in freq_num.items()}\n\n result = [f\"{k}:\" + \",\".join(map(str, v)) for k, v in freq_num.items()]\n return result\n\n\nif __name__ == '__main__':\n nums1 = [5, 3, 6, -8, 0, 11]\n nums2 = [2, 8, 8, 8, -1, 15]\n assert solve_method(nums1, nums2) == \"NULL\"\n\n nums1 = [5, 8, 11, 3, 6, 8, 8, -1, 11, 2, 11, 11]\n nums2 = [11, 2, 11, 8, 6, 8, 8, -1, 8, 15, 3, -9, 11]\n assert solve_method(nums1, nums2) == [\"1:-1,2,3,6\", \"3:8,11\"]\n","repo_name":"datawhalechina/huawei-od-python","sub_path":"codes/others100/077_find-co-occurrence-number.py","file_name":"077_find-co-occurrence-number.py","file_ext":"py","file_size_in_byte":1212,"program_lang":"python","lang":"en","doc_type":"code","stars":38,"dataset":"github-code","pt":"17"} +{"seq_id":"73155730264","text":"import json\nimport pytest\nfrom starlette.testclient import TestClient\nfrom starlette.exceptions import HTTPException\nfrom sovereign.app import generic_error_response\n\n\ndef test_index_redirects_to_interface(testclient: TestClient):\n response = testclient.get('/', allow_redirects=False)\n assert response.status_code == 307\n assert response.headers['Location'] == '/ui'\n\n\ndef test_css_stylesheet_exists(testclient: TestClient):\n response = testclient.get('/static/style.css')\n assert response.status_code == 200\n assert response.headers['Content-Type'] == 'text/css; charset=utf-8'\n\n\ndef test_error_handler_returns_json_response():\n response = generic_error_response(ValueError('Hello'))\n assert response.status_code == 500\n jsondata = json.loads(response.body.decode())\n assert jsondata == {\"error\": \"ValueError\", \"detail\": \"-\", \"request_id\": None, \"traceback\": [\"NoneType: None\", \"\"]}\n\n\ndef test_error_handler_responds_with_json_for_starlette_exceptions():\n response = generic_error_response(HTTPException(429, 'Too Many Requests!'))\n assert response.status_code == 429\n jsondata = json.loads(response.body.decode())\n assert jsondata == {\"error\": \"HTTPException\", \"detail\": \"Too Many Requests!\", \"request_id\": None, \"traceback\": [\"NoneType: None\", \"\"]}\n\n\n# To be moved somewhere more appropriate\ndef test_supplying_a_bad_key_for_encryption_fails(testclient: TestClient):\n with pytest.raises(ValueError):\n testclient.post('/crypto/decrypt', json={'data': 'helloworld', 'key': 'f' * 44})\n\n","repo_name":"bochuxt/envoy-control-plane-python3","sub_path":"test/unit/test_app_factory.py","file_name":"test_app_factory.py","file_ext":"py","file_size_in_byte":1539,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"17"} +{"seq_id":"32057464442","text":"import json\nimport asyncio\nimport websockets\n\nasync def main():\n ws = await websockets.connect('wss://mainnet.infura.io/ws')\n request = dict(jsonrpc='2.0', id=1, method='eth_blockNumber', params=[])\n while True:\n await ws.send(json.dumps(request))\n response = await ws.recv()\n print(json.loads(response)['result'])\n\nif __name__ == '__main__':\n loop = asyncio.get_event_loop()\n loop.run_until_complete(main())","repo_name":"moonsly/eth_blockchain_indexer_rest","sub_path":"helpers/websocket.py","file_name":"websocket.py","file_ext":"py","file_size_in_byte":444,"program_lang":"python","lang":"en","doc_type":"code","stars":2,"dataset":"github-code","pt":"17"} +{"seq_id":"20660682260","text":"\"\"\"Support for beets command aliases, not unlike git.\n\nBy default, also checks $PATH for beet-* and makes those available as well.\n\nExample:\n\n alias:\n from_path: yes # Default\n aliases:\n singletons: ls singleton:true\n external-cmd-test: '!echo'\n sh-c-test: '!sh -c \"echo foo bar arg1:$1, arg2:$2\" sh-c-test'\n with-help-text:\n command: ls -a\n help: do something or other\n\"\"\"\n\nfrom __future__ import division, absolute_import, print_function\n\nimport confuse\nimport glob\nimport optparse\nimport os\nimport shlex\nimport six\nimport subprocess\nimport sys\n\nfrom beets import plugins\nfrom beets import ui\nfrom beets.plugins import BeetsPlugin\nfrom beets.ui import Subcommand, print_\nfrom beets.ui.commands import default_commands\n\nif sys.version_info >= (3, 3):\n from collections import abc\nelse:\n import collections as abc\n\n\nclass NoOpOptionParser(optparse.OptionParser):\n def parse_args(self, args=None, namespace=None):\n if args is None:\n args = sys.argv[1:]\n return [], args\n\n\nclass AliasCommand(Subcommand):\n def __init__(self, alias, command, log=None, help=None):\n super(AliasCommand, self).__init__(alias, help=help or command, parser=NoOpOptionParser(add_help_option=False, description=help or command))\n\n self.alias = alias\n self.log = log\n self.command = command\n\n def func(self, lib, opts, args=None):\n if args is None:\n args = []\n\n split_command = shlex.split(self.command)\n command = split_command[0]\n command_args = split_command[1:]\n\n # loop through beet arguments, starting from behind\n for i in range(len(args) - 1, -1, -1):\n # replace all occurences of token {X} with parameter (if it exists)\n token = \"{i}\".replace(\"i\", str(i))\n token_replaced = False\n for j in range(0, len(command_args), 1):\n if token in command_args[j]:\n command_args[j] = command_args[j].replace(token, args[i])\n token_replaced = True\n # remove parameter if it has been used for a replacement\n if token_replaced:\n del args[i]\n\n # search for token {} and replace it with the rest of the arguments, if it exists or append otherwise\n if '{}' in command_args:\n for i in range(len(command_args) - 1, -1, -1):\n if command_args[i] == '{}':\n command_args[i:i + 1] = args\n else:\n command_args = command_args + args\n\n args = command_args\n\n if command.startswith('!'):\n command = command[1:]\n argv = [command] + args\n\n if self.log:\n self.log.debug('Running {}', subprocess.list2cmdline(argv))\n\n try:\n return subprocess.check_call(argv)\n except subprocess.CalledProcessError as exc:\n if self.log:\n self.log.debug(u'command `{0}` failed with {1}', subprocess.list2cmdline(argv), exc.returncode)\n plugins.send('cli_exit', lib=lib)\n lib._close()\n sys.exit(exc.returncode)\n else:\n argv = [command] + args\n cmdname = argv[0]\n\n subcommands = list(default_commands)\n subcommands.extend(plugins.commands())\n for subcommand in subcommands:\n if cmdname == subcommand.name or cmdname in subcommand.aliases:\n break\n else:\n raise ui.UserError(u\"unknown command '{0}'\".format(cmdname))\n\n if self.log:\n self.log.debug('Running {}', subprocess.list2cmdline(argv))\n\n suboptions, subargs = subcommand.parse_args(argv[1:])\n return subcommand.func(lib, suboptions, subargs)\n\n\nclass AliasPlugin(BeetsPlugin):\n \"\"\"Support for beets command aliases, not unlike git.\"\"\"\n\n def __init__(self):\n super(AliasPlugin, self).__init__()\n\n self.config.add({\n 'from_path': True,\n 'aliases': {},\n })\n\n def get_command(self, alias, command, help=None):\n \"\"\"Create a Subcommand instance for the specified alias.\"\"\"\n return AliasCommand(alias, command, log=self._log, help=help)\n\n def get_path_commands(self):\n \"\"\"Create subcommands for beet-* scripts in $PATH.\"\"\"\n for path in os.getenv('PATH', '').split(':'):\n cmds = glob.glob(os.path.join(path, 'beet-*'))\n for cmd in cmds:\n if os.access(cmd, os.X_OK):\n command = os.path.basename(cmd)\n alias = command[5:]\n yield (alias, self.get_command(alias, '!' + command, u'Run external command `{0}`'.format(command)))\n\n def cmd_alias(self, lib, opts, args, commands):\n \"\"\"Print the available alias commands.\"\"\"\n for alias, command in sorted(commands.items()):\n print_(u'{0}: {1}'.format(alias, command))\n\n def commands(self):\n \"\"\"Add the alias commands.\"\"\"\n if self.config['from_path'].get(bool):\n commands = dict(self.get_path_commands())\n else:\n commands = {}\n\n for alias in self.config['aliases'].keys():\n if alias in commands:\n raise confuse.ConfigError(u'alias.aliases.{0} was specified multiple times'.format(alias))\n\n command = self.config['aliases'][alias].get()\n if isinstance(command, six.text_type):\n commands[alias] = self.get_command(alias, command)\n elif isinstance(command, abc.Mapping):\n command_text = command.get('command')\n if not command_text:\n raise confuse.ConfigError(u'alias.aliases.{0}.command not found'.format(alias))\n help_text = command.get('help', command_text)\n commands[alias] = self.get_command(alias, command_text, help_text)\n else:\n raise confuse.ConfigError(u'alias.aliases.{0} must be a string or single-element mapping'.format(alias))\n\n if 'alias' in commands:\n raise ui.UserError(u'alias `alias` is reserved for the alias plugin')\n\n alias = Subcommand('alias',\n help=u'Print the available alias commands.')\n alias_commands = dict((a, c.command) for a, c in commands.items())\n alias.func = lambda lib, opts, args: self.cmd_alias(lib, opts, args, alias_commands)\n commands['alias'] = alias\n return commands.values()\n","repo_name":"kergoth/beets-kergoth","sub_path":"beetsplug/alias.py","file_name":"alias.py","file_ext":"py","file_size_in_byte":6584,"program_lang":"python","lang":"en","doc_type":"code","stars":5,"dataset":"github-code","pt":"17"} +{"seq_id":"28431430697","text":"import torch\n\nTORCH_VERSION = torch.__version__\nfrom mvt.utils.reg_util import Registry\nfrom torch.nn.parallel import DataParallel, DistributedDataParallel\n\nMODULE_WRAPPERS = Registry(\"module wrapper\")\nMODULE_WRAPPERS.register_module(module=DataParallel)\nMODULE_WRAPPERS.register_module(module=DistributedDataParallel)\n\n\ndef is_module_wrapper(module):\n \"\"\"Check if a module is a module wrapper.\n module wrappers: DataParallel, DistributedDataParallel.\n\n Args:\n module (nn.Module): The module to be checked.\n Returns:\n bool: True if the input module is a module wrapper.\n \"\"\"\n module_wrappers = tuple(MODULE_WRAPPERS.module_dict.values())\n return isinstance(module, module_wrappers)\n","repo_name":"visriv/multi-visual-tasks","sub_path":"mvt/cores/core_module.py","file_name":"core_module.py","file_ext":"py","file_size_in_byte":717,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"17"} +{"seq_id":"4570544192","text":"import argparse\nparser = argparse.ArgumentParser()\nparser.description='please enter two parameters a and b ...'\nparser.add_argument(\"-a\", \"--inputA\", help=\"this is parameter a\", dest=\"argA\", type=int, default=\"0\")\nparser.add_argument(\"-b\", \"--inputB\", help=\"this is parameter b\", type=int, default=\"1\")\nargs = parser.parse_args()\n\nprint(\"parameter a is :\",args.argA)\nprint(\"parameter b is :\",args.inputB)\n# ————————————————\n# 版权声明:本文为CSDN博主“囊萤映雪的萤”的原创文章,遵循CC 4.0 BY-SA版权协议,转载请附上原文出处链接及本声明。\n# 原文链接:https://blog.csdn.net/liuyingying0418/article/details/100126348","repo_name":"newgitofzinian/code","sub_path":"python/script/study.py","file_name":"study.py","file_ext":"py","file_size_in_byte":697,"program_lang":"python","lang":"zh","doc_type":"code","stars":0,"dataset":"github-code","pt":"17"} +{"seq_id":"692599845","text":"import json\nfrom django import forms\nfrom django.forms.widgets import ClearableFileInput\nfrom django.template.loader import render_to_string\n\n\nclass AdminImageWidget(ClearableFileInput):\n template_with_initial = (\n '

'\n '%(initial_text)s: '\n '%(clear_template)s
%(input_text)s: %(input)s'\n '

'\n )\n\n template_with_clear = (\n ''\n '%(clear)s '\n ''\n )\n\n\nclass SirTrevorWidget(forms.Textarea):\n block_types = ('Product', 'Markup', 'Video', 'Heading', 'Text', 'Image')\n\n def __init__(self, attrs=None, block_types=None):\n self.block_types = block_types or self.block_types\n super().__init__(attrs)\n\n class Media:\n css = {'all': (\n 'utils/sir-trevor/sir-trevor.min.css',\n )}\n js = (\n 'utils/sir-trevor/sir-trevor.min.js',\n )\n\n def render(self, name, value, attrs=None):\n res = super().render(name, value, attrs)\n res += render_to_string('utils/sir_trevor.html', {\n 'id': attrs['id'],\n 'block_types': json.dumps(self.block_types),\n })\n return res\n","repo_name":"Sumsum/sumsum","sub_path":"utils/widgets.py","file_name":"widgets.py","file_ext":"py","file_size_in_byte":1305,"program_lang":"python","lang":"en","doc_type":"code","stars":22,"dataset":"github-code","pt":"17"} +{"seq_id":"72712229783","text":"# -*- coding: utf-8 -*-\r\n\r\nimport pandas as pd\r\nimport streamlit as st\r\nimport seaborn as sns\r\n\r\nimport matplotlib.pyplot as plt \r\n\r\nfrom vaderSentiment.vaderSentiment import SentimentIntensityAnalyzer\r\n\r\n\r\n#load clean data\r\ntweets = pd.read_csv('tweets_EDA_clean.csv', encoding='utf-8', index_col=0)\r\n\r\ntweets['date'] = pd.to_datetime(tweets['date'])\r\ntweets['created_at'] = pd.to_datetime(tweets['created_at'])\r\n\r\ndef app():\r\n \r\n sentimentAnalyser = SentimentIntensityAnalyzer()\r\n \r\n \r\n def calculate_sentiment(text):\r\n # Run VADER on the text\r\n scores = sentimentAnalyser.polarity_scores(text)\r\n # Extract the compound score\r\n compound_score = scores['compound']\r\n # Return compound score\r\n return compound_score\r\n \r\n \r\n \r\n # function that will categorize the 'sentiment_score' column by Postive, Negative, or Neutral \r\n def getCategory(score):\r\n if score > 0.05:\r\n return 'Postive'\r\n elif score < -0.05:\r\n return 'Negative'\r\n else:\r\n return 'Neutral'\r\n \r\n tweets['sentiment_score'] = tweets['text'].apply(calculate_sentiment)\r\n tweets['analysis'] = tweets['sentiment_score'].apply(getCategory)\r\n \r\n ########################################################################\r\n \r\n \r\n # with open('style.css') as f:\r\n # st.markdown(f'', unsafe_allow_html=True) \r\n\r\n title1 = '

Covid-19 Sentiment on Twitter

'\r\n st.markdown(title1, unsafe_allow_html=True) \r\n \r\n text1 = '

The figure below is a barplot of the sentiment across variant. The values of the \\\r\n barplot can be normalized such that the sum is 1 for each variant by selecting \\\r\n yes radio button under normalize while count by\\\r\n selecting no radio button.

'\r\n \r\n st.markdown(text1, unsafe_allow_html=True)\r\n \r\n #st.markdown(\"The figure below is a barplot of the sentiment across variant. The values of the \\\r\n # barplot can be normalized such that the sum is 1 for each variant by selecting \\\r\n # `yes` radio button under `normalize` while count by selecting `no` radio button.\")\r\n \r\n \r\n title1 = '

Sentiment:

'\r\n st.markdown(title1, unsafe_allow_html=True)\r\n \r\n #st.header(\"Sentiment:\")\r\n \r\n select_normalize = st.radio(\"normalize:\", ['Yes', 'No'])\r\n dict_norm = {'Yes':(True, 'Frequency'), 'No':(False, 'Count')}\r\n \r\n \r\n \r\n byVariant = tweets.groupby('variant')['analysis'].value_counts(normalize=dict_norm[select_normalize][0])\r\n byVariant = byVariant.rename('number').reset_index()\r\n #plt.figure(figsize=(10,4))\r\n #byVariant.plot.bar(color=['green', 'green', 'green', 'yellow', 'yellow', 'yellow', 'red', 'red', 'red'])\r\n \r\n #byVariant.rename('number').reset_index().pipe((sns.catplot, 'data'), x='variant',y='number',hue='analysis', kind='bar')\r\n sns.catplot(x='variant', y='number', data=byVariant, hue='analysis', kind='bar',\\\r\n height=5, aspect=2)\r\n \r\n plt.xlabel(\"Variant\")\r\n plt.ylabel(dict_norm[select_normalize][1] + \" of each Category\")\r\n st.set_option('deprecation.showPyplotGlobalUse', False)\r\n st.pyplot()\r\n \r\n \r\n text2 = '

The next figure is a time series of sentiment score. The select box \\\r\n select variant picks the selected variant of first 10 days. The default length of time\\\r\n to aggregate is 15 minutes which can be changed by the select box called time interval.

'\r\n \r\n st.markdown(text2, unsafe_allow_html=True)\r\n \r\n # st.markdown(\"The next figure is a time series of `sentiment score`. The select box `select variant` \\\r\n # picks the selected variant of first 10 days. The default time interval\\\r\n # to aggregate is 15 minutes which can be changed by the select box called `time interval`.\\\r\n # \")\r\n \r\n select_var = st.selectbox(\"select variant:\", ['beta', 'delta', 'omicron'])\r\n color_dict = {'beta':'blue', 'delta':'orange', 'omicron':'green'}\r\n \r\n select_timeinterval = st.selectbox(\"time interval:\", ['15 minutes', '30 minutes', '45 minutes', '1 hour', '2 hours'])\r\n time_dict = {'15 minutes':'15min', '30 minutes':'30min', '45 minutes':'45min', '1 hour':'H', '2 hours':'2H'}\r\n \r\n tweets.loc[tweets['variant']==select_var].set_index('created_at')['sentiment_score'].resample(time_dict[select_timeinterval]).mean().plot(figsize = (10,4), color=color_dict[select_var])\r\n plt.title(\"Sentiment Scores on first 10 days \" + select_var + \" Variant (Variant of Concern)\")\r\n plt.ylabel(\"Sentiment Score\")\r\n plt.xlabel(\"Date\")\r\n plt.ylim([-1,1])\r\n plt.tight_layout()\r\n st.set_option('deprecation.showPyplotGlobalUse', False)\r\n st.pyplot()\r\n","repo_name":"ydawit87/DS4A_team-68_project","sub_path":"yoseph2.py","file_name":"yoseph2.py","file_ext":"py","file_size_in_byte":4993,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"17"} +{"seq_id":"17103953679","text":"class Node: \n def __init__ (self,data):\n self.data = data\n self.next = None\n\nclass linkedlist:\n def __init__ (self):\n self.head = None\n\n def insertNodeAtTail (self,newelement):\n newNode = Node(newelement)\n if self.head == None:\n self.head = newNode\n return\n else:\n temp = self.head\n while temp.next != None:\n temp = temp.next\n temp.next = newNode\n return \n def PrintList(self):\n temp = self.head\n if(temp != None):\n print(\"The list contains:\")\n while (temp != None):\n print(temp.data)\n temp = temp.next\n else:\n print(\"The list is empty.\")\n def addatmiddel(self,data,position):\n newnode=Node(data)\n prev = self.head\n curr = newnode\n count = 1\n if position < 0:\n print(\"add valid number\")\n if self.head == None:\n self.head = newnode\n else :\n while count != position :\n prev = prev.next\n count +=1\n curr.next = prev.next\n prev.next = curr\n\nMylist = linkedlist()\nMylist.insertNodeAtTail(141)\nMylist.insertNodeAtTail(142)\nMylist.insertNodeAtTail(143)\nMylist.insertNodeAtTail(144)\nMylist.insertNodeAtTail(145)\nMylist.insertNodeAtTail(146)\nMylist.addatmiddel(66,3)\nMylist.PrintList()\n\n","repo_name":"mussabtafal/Axsos","sub_path":"Algortithms/addrandomlinkedlist.py","file_name":"addrandomlinkedlist.py","file_ext":"py","file_size_in_byte":1461,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"17"} +{"seq_id":"72704477145","text":"import sys\n\nfrom tournamentGenerator import RaceGenerator, Tournament, RandomPlayerGenerator, PlayerGeneratorFromFile\nfrom tournamentGenerator.helper import printRaces\n\nif __name__ == '__main__':\n if len(sys.argv) == 4:\n debug = bool(sys.argv[3])\n elif len(sys.argv) == 3:\n debug = False\n else:\n print(\"tournamentGenerator.py: missing arguments\")\n print(\"Usage: python tournamentGenerator.py NUMBER_PLAYERS_PER_RACE PLAYERS_NAME_FILE/NUMBER_OF_PLAYERS [DEBUG]\")\n sys.exit()\n \n numberOfPlayers = 0\n playersPerRace = int(sys.argv[1])\n try:\n numberOfPlayers = int(sys.argv[2])\n except ValueError:\n filename = sys.argv[2]\n \n if numberOfPlayers == 0:\n playerGenerator = PlayerGeneratorFromFile(filename)\n else:\n playerGenerator = RandomPlayerGenerator(numberOfPlayers)\n \n tournament = Tournament.init_WithPlayerGenerator(playerGenerator)\n \n raceGenerator = RaceGenerator(playersPerRace,debug)\n raceGenerator.generate_lowCostForPlayerWithLeastRaces(tournament)\n \n # debug\n printRaces(tournament.getRaces())\n tournament.printNumberOfRacesOfEachPlayer()\n tournament.printPlayersFacedByEachPlayer()\n","repo_name":"Mortesins/TournamentGenerator","sub_path":"tournamentGenerator_cli.py","file_name":"tournamentGenerator_cli.py","file_ext":"py","file_size_in_byte":1216,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"17"} +{"seq_id":"74822545930","text":"import click\n\nfrom .my_wordclouds import create_wordcloud\n\n\n@click.command()\n@click.version_option()\n@click.option(\n \"-i\",\n \"--inputfile\",\n required=True,\n type=str,\n help=\"The input-file with text.\",\n)\ndef cli(inputfile: str) -> None:\n \"\"\"Extract data from the database [NOT IMPLEMENTED YET].\n\n This command is not implemented yet.\n \"\"\"\n try:\n create_wordcloud(inputfile)\n except click.ClickException as e:\n e.show()\n ctx = click.get_current_context()\n ctx.exit(e.exit_code)\n","repo_name":"stigbd/my-wordclouds","sub_path":"my_wordclouds/cli.py","file_name":"cli.py","file_ext":"py","file_size_in_byte":534,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"15"} +{"seq_id":"37563891792","text":"class Solution:\n def trailingZeroes(self, n: int) -> int:\n count_2 = 0\n count_5 = 0\n if n<0:\n return 0\n for i in range(2,n+1,1):\n if i%2== 0 or i%5==0:\n while i%5==0:\n count_5+=1\n i = i//5\n while i%2==0:\n count_2+=1\n i = i//2\n return min(count_2,count_5)\n\n def trailingZeroes2(self, n: int) -> int:\n # 只需要计算5出现的次数,怎样更快的计算5出现的次数\n count_5 = 0\n index = 1\n while n//(5**index)>0:\n count_5 += n//(5**index)\n index+=1\n return count_5\n\n\nif __name__ == '__main__':\n s = Solution()\n n = 1808548329\n print(s.trailingZeroes2(n))\n","repo_name":"pororodl/LeetCode","sub_path":"172. Factorial Trailing Zeroes.py","file_name":"172. Factorial Trailing Zeroes.py","file_ext":"py","file_size_in_byte":799,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"15"} +{"seq_id":"40456276624","text":"#!/usr/bin/env python3\n\n\"\"\"mapper.py\"\"\" \n\nimport sys\n\n\nfor line in sys.stdin:\n \n line = line.strip()\n \n key, delta = line.split(\"\\t\") #key = (A, month) percentage_var\n \n key = key[1:-1]\n key = key.split(\",\")\n ticker = key[0][1:-1]\n month = key[1][1:-1]\n month = int(month[1:])\n \n delta = float(delta)\n \n\n print(\"%d\\t%s\\t%f\" % (month, ticker, delta)) #month : ticker, delta\n \n \n \n \n","repo_name":"Progetto-bigData/primo_progetto","sub_path":"mapReduce/exercise3/mapper2_ES3.py","file_name":"mapper2_ES3.py","file_ext":"py","file_size_in_byte":457,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"15"} +{"seq_id":"30213577173","text":"import os\nimport sys\nsys.path.append(\"..\")\nimport datetime as dt\n\nimport numpy as np\nimport pandas as pd\nimport torch\nfrom torch.utils.data import Dataset\nfrom torchvision.transforms import Compose\n\nfrom tools.args_tools import args\n\n\nclass TyDataset(Dataset):\n \"\"\"Typhoon dataset\"\"\"\n\n def __init__(self, ty_list_file, root_dir, train=True, train_num=11, test_num=2\n ,input_frames=5, output_frames=18, transform=None):\n \"\"\"\n Args:\n ty_list_file (string): Path of the typhoon list file.\n root_dir (string): Directory with all the files.\n train (boolean): Construct training set or not.\n train_num (int): The event number of training set.\n test_num (int): The event number of testing set.\n input_frames (int, 10-minutes-based): The frames of input data.\n output_frames (int, 10-minutes-based): The frames of output data.\n transform (callable, optional): Optional transform to be applied on a sample.\n \"\"\"\n super().__init__()\n self.ty_list = pd.read_excel(ty_list_file,index_col=\"En name\").drop(\"Ch name\",axis=1)\n self.root_dir = root_dir\n self.input_frames = input_frames\n self.output_frames = output_frames\n self.transform = transform\n\n if train:\n self.events_num = range(0, train_num)\n self.events_list = self.ty_list.index[self.events_num]\n else:\n self.events_num = range(train_num, len(self.ty_list))\n self.events_list = self.ty_list.index[self.events_num]\n\n tmp = 0\n self.idx_list = pd.DataFrame([],columns=[\"frame_start\",\"frame_end\",\"idx_s\",\"idx_e\"])\n for i in self.events_num:\n frame_s = self.ty_list.iloc[i,0]\n frame_e = self.ty_list.iloc[i,1]-dt.timedelta(minutes=(input_frames+output_frames-1)*10)\n\n self.total_frames = tmp + int((frame_e-frame_s).days*24*6 + (frame_e-frame_s).seconds/600)+1\n self.idx_list=self.idx_list.append({\"frame_start\":frame_s,\"frame_end\":frame_e,\n \"idx_s\":tmp,\"idx_e\":self.total_frames-1}\n ,ignore_index=True)\n tmp = self.total_frames\n\n self.idx_list.index = self.events_list\n self.idx_list.index.name = \"Typhoon\"\n\n def __len__(self):\n return self.total_frames\n\n def print_idx_list(self):\n return self.idx_list\n\n def print_ty_list(self):\n return self.ty_list\n\n def __getitem__(self,idx):\n # To identify which event the idx is in.\n assert idx < self.total_frames, 'Index is out of the range of the data!'\n\n for i in self.idx_list.index:\n if idx > self.idx_list.loc[i,\"idx_e\"]:\n continue\n else:\n # determine some indexes\n idx_tmp = idx - self.idx_list.loc[i,\"idx_s\"]\n # print(\"idx_tmp: {:d} |ty: {:s}\".format(idx_tmp,i))\n # print(\"idx: {:d} |ty: {:s}\".format(idx,i))\n year = str(self.idx_list.loc[i,'frame_start'].year)\n\n # RAD data(a tensor with shape (input_frames X H X W))\n rad_data = []\n for j in range(self.input_frames):\n file_time = dt.datetime.strftime(self.idx_list.loc[i,'frame_start']+dt.timedelta(minutes=10*(idx_tmp+j))\n ,format=\"%Y%m%d%H%M\")\n # print(\"rad_data: {:s}\".format(year+'.'+i+\"_\"+rad_file_time+\".npy\"))\n data_path = os.path.join(self.root_dir,'RAD',year+'.'+i+\".\"+file_time+\".npz\")\n data = np.load(data_path)['data'][args.I_y_low:args.I_y_high+1,args.I_x_left:args.I_x_right+1]\n rad_data.append(data)\n rad_data = np.array(rad_data)\n\n # QPE data(a tensor with shape (output_frames X H X W))\n qpe_data = []\n\n for j in range(self.input_frames,self.input_frames+self.output_frames):\n file_time = dt.datetime.strftime(self.idx_list.loc[i,'frame_start']+dt.timedelta(minutes=10*(idx_tmp+j))\n ,format=\"%Y%m%d%H%M\")\n # print(\"qpe_data: {:s}\".format(year+'.'+i+\"_\"+qpe_file_time+\".npy\"))\n data_path = os.path.join(self.root_dir,'QPE',year+'.'+i+\".\"+file_time+\".npz\")\n data = np.load(data_path)['data'][args.I_y_low:args.I_y_high+1,args.I_x_left:args.I_x_right+1]\n qpe_data.append(data)\n qpe_data = np.array(qpe_data)\n # return the idx of sample\n self.sample = {\"RAD\": rad_data, \"QPE\": qpe_data}\n if self.transform:\n self.sample = self.transform(self.sample)\n return self.sample\n\nclass ToTensor(object):\n \"\"\"Convert ndarrays in sample to Tensors.\"\"\"\n def __call__(self, sample):\n rad_data, qpe_data = sample['RAD'], sample['QPE']\n\n # numpy data: x_tsteps X H X W\n # torch data: x_tsteps X H X W\n return {'RAD': torch.from_numpy(rad_data),\n 'QPE': torch.from_numpy(qpe_data)}\n\nclass Normalize(object):\n \"\"\"Convert ndarrays in sample to Tensors.\"\"\"\n def __init__(self, mean, std):\n self.mean = mean\n self.std = std\n def __call__(self, sample):\n rad_data, qpe_data = sample['RAD'], sample['QPE']\n if type(self.mean) == list and type(self.std) == list:\n for i in range(len(self.mean)):\n rad_data[i] = (rad_data[i] - self.mean[i]) / self.std[i]\n\n # numpy data: x_tsteps X H X W\n # torch data: x_tsteps X H X W\n return {'RAD': rad_data,\n 'QPE': qpe_data}\n\nif __name__ == \"__main__\":\n # test dataloader\n input_frames = 5\n output_frames = 18\n mean = [12.834] * input_frames\n # mean += [12.834] * output_frames\n std = [14.14] * input_frames\n # std += [14.14] * output_frames\n train_dataset = TyDataset(ty_list_file=args.ty_list_file,\n root_dir=args.root_dir,\n input_frames=5,\n output_frames=20,\n train=True,\n transform = Compose([ToTensor(),Normalize(mean,std)]))\n print(train_dataset[1][\"RAD\"].sum())\n\n train_dataset = TyDataset(ty_list_file=args.ty_list_file,\n root_dir=args.root_dir,\n input_frames=5,\n output_frames=20,\n train=True,\n transform = Compose([ToTensor()]))\n print(train_dataset[1][\"RAD\"].sum())\n print(train_dataset[1][\"RAD\"].shape)\n","repo_name":"UTMOSTOF9/TY-R-Forecast","sub_path":"models/src/dataseters/CNN2D.py","file_name":"CNN2D.py","file_ext":"py","file_size_in_byte":6841,"program_lang":"python","lang":"en","doc_type":"code","stars":8,"dataset":"github-code","pt":"15"} +{"seq_id":"17568400771","text":"\nimport os\nimport subprocess\nimport time\nfrom colors import *\n\n\n\n\ndef success_msg():\n print(bcolors.OKGREEN + \"\\nSuccess !\" + bcolors.ENDC)\n\n\ndef system_info():\n print(\"System Information ...\")\n os.system('sudo apt-get install screenfetch | screenfetch')\n\ndef clear_cache():\n print(\"Clear apt cache in /var/cache/apt/archives ... \")\n os.system('sudo apt-get clean')\n success_msg()\n\ndef clear_orphaned_packages():\n print(\"removing orphaned packages ... \")\n os.system('sudo apt-get --purge autoremove')\n success_msg()\n\ndef show_ip_addr():\n print(bcolors.WARNING + \"\\nIp Address:\" + bcolors.ENDC)\n os.system('hostname -I')\n\ndef install_dev_packages():\n\n print(\"Updating repository\")\n time.sleep(3)\n os.system(\"sudo apt-get update\")\n\n\n print(\"\\nInstalling Git ...\")\n time.sleep(3)\n os.system(\"sudo apt-get install git -y\")\n\n print(\"\\nInstalling C++ ...\")\n time.sleep(3)\n os.system(\"sudo apt-get install c++ -y\")\n\n print(\"\\nInstalling C ...\")\n time.sleep(3)\n os.system(\"sudo apt-get install gcc -y\")\n\n print(\"\\nInstalling make ...\")\n time.sleep(3)\n os.system(\"sudo apt-get install make -y\")\n\n print(\"\\nInstalling python 3 ...\")\n time.sleep(3)\n os.system(\"sudo apt-get install python3\")\n\n print(\"\\nInstalling pip3 ...\")\n time.sleep(3)\n os.system(\"sudo apt install python3-pip\")\n\n\n\n \n\nwhile (True):\n op = input(\"\"\"\n1 - System Information (screenfetch) and IP Address \n2 - Show IP Address \n3 - Clear apt cache \n4 - Remove orphaned packages\n5 - Install dev packages\n6 - Schedule shutdown \n> \"\"\")\n\n if(op == \"1\"):\n system_info()\n elif (op == \"2\"):\n show_ip_addr()\n elif (op == \"3\"):\n clear_cache()\n elif (op == \"4\"):\n clear_orphaned_packages()\n elif (op == \"5\"):\n install= input(\"Will be installed: git, C++, GCC, make, python3. Continue ? y/n: \")\n if(install == \"y\"):\n install_dev_packages()\n elif (op == \"5\"):\n install= input(\"Will be installed: git, C++, GCC, make, python3, pip3. Continue ? y/n: \")\n if(install == \"y\"):\n install_dev_packages()\n elif (op == \"6\"):\n os.system(\"chmod +x shutdown-auto.sh\")\n os.system(\"./shutdown-auto.sh\")\n #subprocess.call([\"sh\", \"./shutdown-auto.sh\"])\n","repo_name":"rodrigodg1/python-script","sub_path":"maintenance/run.py","file_name":"run.py","file_ext":"py","file_size_in_byte":2302,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"15"} +{"seq_id":"3133269164","text":"from .base import (MySQLDialect, MySQLExecutionContext,\n MySQLCompiler, MySQLIdentifierPreparer)\nfrom .base import TEXT\nfrom ... import sql\nfrom ... import util\nimport re\n\n\nclass MySQLExecutionContext_mysqldb(MySQLExecutionContext):\n\n @property\n def rowcount(self):\n if hasattr(self, '_rowcount'):\n return self._rowcount\n else:\n return self.cursor.rowcount\n\n\nclass MySQLCompiler_mysqldb(MySQLCompiler):\n def visit_mod_binary(self, binary, operator, **kw):\n return self.process(binary.left, **kw) + \" %% \" + \\\n self.process(binary.right, **kw)\n\n def post_process_text(self, text):\n return text.replace('%', '%%')\n\n\nclass MySQLIdentifierPreparer_mysqldb(MySQLIdentifierPreparer):\n\n def _escape_identifier(self, value):\n value = value.replace(self.escape_quote, self.escape_to_quote)\n return value.replace(\"%\", \"%%\")\n\n\nclass MySQLDialect_mysqldb(MySQLDialect):\n driver = 'mysqldb'\n supports_unicode_statements = True\n supports_sane_rowcount = True\n supports_sane_multi_rowcount = True\n\n supports_native_decimal = True\n\n default_paramstyle = 'format'\n execution_ctx_cls = MySQLExecutionContext_mysqldb\n statement_compiler = MySQLCompiler_mysqldb\n preparer = MySQLIdentifierPreparer_mysqldb\n\n def __init__(self, server_side_cursors=False, **kwargs):\n super(MySQLDialect_mysqldb, self).__init__(**kwargs)\n self.server_side_cursors = server_side_cursors\n\n @util.langhelpers.memoized_property\n def supports_server_side_cursors(self):\n try:\n cursors = __import__('MySQLdb.cursors').cursors\n self._sscursor = cursors.SSCursor\n return True\n except (ImportError, AttributeError):\n return False\n\n @classmethod\n def dbapi(cls):\n return __import__('MySQLdb')\n\n def do_executemany(self, cursor, statement, parameters, context=None):\n rowcount = cursor.executemany(statement, parameters)\n if context is not None:\n context._rowcount = rowcount\n\n def _check_unicode_returns(self, connection):\n # work around issue fixed in\n # https://github.com/farcepest/MySQLdb1/commit/cd44524fef63bd3fcb71947392326e9742d520e8\n # specific issue w/ the utf8_bin collation and unicode returns\n\n has_utf8_bin = self.server_version_info > (5, ) and \\\n connection.scalar(\n \"show collation where %s = 'utf8' and %s = 'utf8_bin'\"\n % (\n self.identifier_preparer.quote(\"Charset\"),\n self.identifier_preparer.quote(\"Collation\")\n ))\n if has_utf8_bin:\n additional_tests = [\n sql.collate(sql.cast(\n sql.literal_column(\n \"'test collated returns'\"),\n TEXT(charset='utf8')), \"utf8_bin\")\n ]\n else:\n additional_tests = []\n return super(MySQLDialect_mysqldb, self)._check_unicode_returns(\n connection, additional_tests)\n\n def create_connect_args(self, url):\n opts = url.translate_connect_args(database='db', username='user',\n password='passwd')\n opts.update(url.query)\n\n util.coerce_kw_type(opts, 'compress', bool)\n util.coerce_kw_type(opts, 'connect_timeout', int)\n util.coerce_kw_type(opts, 'read_timeout', int)\n util.coerce_kw_type(opts, 'client_flag', int)\n util.coerce_kw_type(opts, 'local_infile', int)\n # Note: using either of the below will cause all strings to be\n # returned as Unicode, both in raw SQL operations and with column\n # types like String and MSString.\n util.coerce_kw_type(opts, 'use_unicode', bool)\n util.coerce_kw_type(opts, 'charset', str)\n\n # Rich values 'cursorclass' and 'conv' are not supported via\n # query string.\n\n ssl = {}\n keys = ['ssl_ca', 'ssl_key', 'ssl_cert', 'ssl_capath', 'ssl_cipher']\n for key in keys:\n if key in opts:\n ssl[key[4:]] = opts[key]\n util.coerce_kw_type(ssl, key[4:], str)\n del opts[key]\n if ssl:\n opts['ssl'] = ssl\n\n # FOUND_ROWS must be set in CLIENT_FLAGS to enable\n # supports_sane_rowcount.\n client_flag = opts.get('client_flag', 0)\n if self.dbapi is not None:\n try:\n CLIENT_FLAGS = __import__(\n self.dbapi.__name__ + '.constants.CLIENT'\n ).constants.CLIENT\n client_flag |= CLIENT_FLAGS.FOUND_ROWS\n except (AttributeError, ImportError):\n self.supports_sane_rowcount = False\n opts['client_flag'] = client_flag\n return [[], opts]\n\n def _get_server_version_info(self, connection):\n dbapi_con = connection.connection\n version = []\n r = re.compile(r'[.\\-]')\n for n in r.split(dbapi_con.get_server_info()):\n try:\n version.append(int(n))\n except ValueError:\n version.append(n)\n return tuple(version)\n\n def _extract_error_code(self, exception):\n return exception.args[0]\n\n def _detect_charset(self, connection):\n \"\"\"Sniff out the character set in use for connection results.\"\"\"\n\n try:\n # note: the SQL here would be\n # \"SHOW VARIABLES LIKE 'character_set%%'\"\n cset_name = connection.connection.character_set_name\n except AttributeError:\n util.warn(\n \"No 'character_set_name' can be detected with \"\n \"this MySQL-Python version; \"\n \"please upgrade to a recent version of MySQL-Python. \"\n \"Assuming latin1.\")\n return 'latin1'\n else:\n return cset_name()\n\n _isolation_lookup = set(['SERIALIZABLE', 'READ UNCOMMITTED',\n 'READ COMMITTED', 'REPEATABLE READ',\n 'AUTOCOMMIT'])\n\n def _set_isolation_level(self, connection, level):\n if level == 'AUTOCOMMIT':\n connection.autocommit(True)\n else:\n connection.autocommit(False)\n super(MySQLDialect_mysqldb, self)._set_isolation_level(connection,\n level)\n\n\ndialect = MySQLDialect_mysqldb\n","repo_name":"eirannejad/pyRevit","sub_path":"site-packages/sqlalchemy/dialects/mysql/mysqldb.py","file_name":"mysqldb.py","file_ext":"py","file_size_in_byte":6464,"program_lang":"python","lang":"en","doc_type":"code","stars":1092,"dataset":"github-code","pt":"15"} +{"seq_id":"21625273348","text":"# user_name = input(\"What's is your name?\")\n# length_user_name = len(name)\n# print(name, length)\n\n\na = input(\"a: \")\nb = input(\"b: \")\n\nc = a\na = b\nb = c\n\nprint('a: ', a)\nprint('b: ', c)\n","repo_name":"gbmsaraujo/python-bootcamp","sub_path":"aulas/bootcamp/day-01/02-variables/main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":186,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"15"} +{"seq_id":"11269340848","text":"#!/usr/env/bin python3.6\n\nfrom typing import List, Tuple\nfrom operator import add\nfrom functools import reduce\nimport numpy as np\nimport torch\nfrom torch import einsum\nfrom torch import Tensor\nimport pandas as pd\n\nfrom utils import simplex, sset, probs2one_hot\nimport torch.nn.modules.padding\nfrom torch.nn import BCEWithLogitsLoss\n\nclass DiceLoss():\n def __init__(self, **kwargs):\n # Self.idc is used to filter out some classes of the target mask. Use fancy indexing\n self.idc: List[int] = kwargs[\"idc\"]\n print(f\"Initialized {self.__class__.__name__} with {kwargs}\")\n\n def __call__(self, probs: Tensor, target: Tensor, _: Tensor) -> Tensor:\n assert simplex(probs) and simplex(target)\n\n pc = probs[:, self.idc, ...].type(torch.float32)\n tc = target[:, self.idc, ...].type(torch.float32)\n\n intersection: Tensor = einsum(f\"bcwh,bcwh->bc\", pc, tc)\n union: Tensor = (einsum(f\"bkwh->bk\", pc) + einsum(f\"bkwh->bk\", tc))\n\n divided: Tensor = torch.ones_like(intersection) - (2 * intersection + 1e-10) / (union + 1e-10)\n\n loss = divided.mean()\n\n return loss\n\n\n\nclass EntKLProp():\n \"\"\"\n CE between proportions\n \"\"\"\n def __init__(self, **kwargs):\n self.power: int = kwargs[\"power\"]\n self.__fn__ = getattr(__import__('utils'), kwargs['fn'])\n self.curi: bool = kwargs[\"curi\"]\n self.idc: bool = kwargs[\"idc_c\"]\n self.ivd: bool = kwargs[\"ivd\"]\n self.weights: List[float] = kwargs[\"weights_se\"]\n self.lamb_se: float = kwargs[\"lamb_se\"]\n self.lamb_conspred: float = kwargs[\"lamb_conspred\"]\n self.lamb_consprior: float = kwargs[\"lamb_consprior\"]\n\n def __call__(self, probs: Tensor, target: Tensor, bounds) -> Tensor:\n assert simplex(probs) # and simplex(target) # Actually, does not care about second part\n b, _, w, h = probs.shape # type: Tuple[int, int, int, int]\n predicted_mask = probs2one_hot(probs).detach()\n est_prop_mask = self.__fn__(predicted_mask,self.power).squeeze(2)\n est_prop: Tensor = self.__fn__(probs,self.power)\n if self.curi: # this is the case for the main experiments, i.e. we use curriculum learning. Put self.curi=True to reproduce the method\n if self.ivd:\n bounds = bounds[:,:,0] \n bounds= bounds.unsqueeze(2)\n gt_prop = torch.ones_like(est_prop)*bounds/(w*h)\n gt_prop = gt_prop[:,:,0]\n else: # for toy experiments, you can try and use the GT size calculated from the target instead of an estimation of the size. \n #Note that this is \"cheating\", meaning you are adding supplementary info. But interesting to obtain an upper bound\n gt_prop: Tensor = self.__fn__(target,self.power) # the power here is actually useless if we have 0/1 gt labels\n gt_prop = gt_prop.squeeze(2)\n est_prop = est_prop.squeeze(2)\n log_est_prop: Tensor = (est_prop + 1e-10).log()\n\n log_gt_prop: Tensor = (gt_prop + 1e-10).log()\n log_est_prop_mask: Tensor = (est_prop_mask + 1e-10).log()\n\n loss_cons_prior = - torch.einsum(\"bc,bc->\", [est_prop, log_gt_prop]) + torch.einsum(\"bc,bc->\", [est_prop, log_est_prop])\n # Adding division by batch_size to normalise \n loss_cons_prior /= b\n log_p: Tensor = (probs + 1e-10).log()\n mask: Tensor = probs.type((torch.float32))\n mask_weighted = torch.einsum(\"bcwh,c->bcwh\", [mask, Tensor(self.weights).to(mask.device)])\n loss_se = - torch.einsum(\"bcwh,bcwh->\", [mask_weighted, log_p])\n loss_se /= mask.sum() + 1e-10\n\n assert loss_se.requires_grad == probs.requires_grad # Handle the case for validation\n\n return self.lamb_se*loss_se, self.lamb_consprior*loss_cons_prior,est_prop \n\n\nclass SelfEntropy():\n def __init__(self, **kwargs):\n # Self.idc is used to filter out some classes of the target mask. Use fancy indexing\n self.idc: List[int] = kwargs[\"idc\"]\n self.weights: List[float] = kwargs[\"weights\"]\n self.dtype = kwargs[\"dtype\"]\n #print(f\"Initialized {self.__class__.__name__} with {kwargs}\")\n\n def __call__(self, probs: Tensor, target: Tensor, bounds: Tensor) -> Tensor:\n #assert simplex(probs) and simplex(target)\n\n log_p: Tensor = (probs[:, self.idc, ...] + 1e-10).log()\n mask: Tensor = probs[:, self.idc, ...].type((torch.float32))\n mask_weighted = torch.einsum(\"bcwh,c->bcwh\", [mask, Tensor(self.weights).to(mask.device)])\n loss = - torch.einsum(\"bcwh,bcwh->\", [mask_weighted, log_p])\n loss /= mask.sum() + 1e-10\n\n return loss\n\n\nclass CrossEntropy():\n def __init__(self, **kwargs):\n # Self.idc is used to filter out some classes of the target mask. Use fancy indexing\n self.idc: List[int] = kwargs[\"idc\"]\n self.weights: List[float] = kwargs[\"weights\"]\n self.dtype = kwargs[\"dtype\"]\n #print(f\"Initialized {self.__class__.__name__} with {kwargs}\")\n\n def __call__(self, probs: Tensor, target: Tensor, bounds: Tensor) -> Tensor:\n #assert simplex(probs) and simplex(target)\n\n log_p: Tensor = (probs[:, self.idc, ...] + 1e-10).log()\n mask: Tensor = target[:, self.idc, ...].type((torch.float32))\n mask_weighted = torch.einsum(\"bcwh,c->bcwh\", [mask, Tensor(self.weights).to(mask.device)])\n loss = - torch.einsum(\"bcwh,bcwh->\", [mask_weighted, log_p])\n loss /= mask.sum() + 1e-10\n\n #import matplotlib.pyplot as plt\n #plt.imshow(probs[:, self.idc, ...].squeeze(0).squeeze(0).detach().cpu().numpy())\n #plt.imshow(target[:, self.idc, ...].squeeze(0).squeeze(0).detach().cpu().numpy())\n return loss\n\n\nclass NegCrossEntropy(CrossEntropy):\n \"\"\"\n Apply the cross-entropy ONLY if the whole image is the selected class.\n This is useful to supervise the background class when we have weak labels.\n \"\"\"\n def __init__(self, **kwargs):\n super().__init__(**kwargs)\n print(f\"Initialized {self.__class__.__name__} with {kwargs}\")\n\n def __call__(self, probs: Tensor, target: Tensor, bounds: Tensor) -> Tensor:\n _, _, w, h = probs.shape\n trimmed: Tensor = target[:, self.idc, ...]\n full_img: Tensor = torch.einsum(\"bcwh->b\", trimmed) == (w * h) # List of images that are fully covered\n\n if full_img.any():\n where = torch.nonzero(full_img).flatten()\n return super().__call__(probs[where], target[where], bounds[where])\n\n return torch.zeros(1).to(probs.device)\n\nclass NaivePenalty():\n \"\"\"\n Implementation in the same fashion as the log-barrier\n \"\"\"\n def __init__(self, **kwargs):\n self.idc: List[int] = kwargs[\"idc\"]\n self.C = len(self.idc)\n self.__fn__ = getattr(__import__('utils'), kwargs['fn'])\n self.power: int = kwargs[\"power\"]\n self.curi: int = kwargs[\"curi\"]\n #print(f\"Initialized {self.__class__.__name__} with {kwargs}\")\n\n def __call__(self, probs: Tensor, target: Tensor, bounds: Tensor) -> Tensor:\n def penalty(z: Tensor) -> Tensor:\n assert z.shape == ()\n\n return torch.max(torch.zeros_like(z), z)**2\n\n assert simplex(probs) # and simplex(target) # Actually, does not care about second part\n #assert probs.shape == target.shape\n b, _, w, h = probs.shape # type: Tuple[int, int, int, int]\n if len(bounds.shape)==3:\n bounds = torch.unsqueeze(bounds, 2) \n _, _, k, two = bounds.shape # scalar or vector\n assert two == 2\n # assert k == 1 # Keep it simple for now\n value: Tensor = self.__fn__(probs[:, self.idc, ...],self.power)\n #print(value.shape,\"value shape\")\n lower_b = bounds[:, self.idc, :, 0]\n upper_b = bounds[:, self.idc, :, 1]\n\n\n if len(value.shape)==2: #then its norm soft size ... to ameleiorate\n value = value.unsqueeze(2)\n lower_b = lower_b/(w*h)\n upper_b = upper_b/(w*h)\n \n assert value.shape == (b, self.C, k), value.shape\n assert lower_b.shape == upper_b.shape == (b, self.C, k), lower_b.shape\n\n upper_z: Tensor = (value - upper_b).type(torch.float32).flatten()\n lower_z: Tensor = (lower_b - value).type(torch.float32).flatten()\n\n upper_penalty: Tensor = reduce(add, (penalty(e) for e in upper_z))\n lower_penalty: Tensor = reduce(add, (penalty(e) for e in lower_z))\n #count_up: Tensor = reduce(add, (penalty(e)>0 for e in lower_z))\n #count_low: Tensor = reduce(add, (penalty(e)>0 for e in upper_z))\n\n res: Tensor = upper_penalty + lower_penalty\n #count = count_up + count_low\n loss: Tensor = res.sum() / (w * h)**2\n\n assert loss.requires_grad == probs.requires_grad # Handle the case for validation\n\n return loss\n\n\nclass KLPropInv():\n \"\"\"\n CE between proportions\n \"\"\"\n def __init__(self, **kwargs):\n self.power: int = kwargs[\"power\"]\n self.__fn__ = getattr(__import__('utils'), kwargs['fn'])\n self.curi: bool = kwargs[\"curi\"]\n self.idc: bool = kwargs[\"idc_c\"]\n self.ivd: bool = kwargs[\"ivd\"]\n self.weights: List[float] = kwargs[\"weights_se\"]\n self.lamb_ce: float = kwargs[\"lamb_se\"]\n self.lamb_conspred: float = kwargs[\"lamb_conspred\"]\n self.lamb_consprior: float = kwargs[\"lamb_consprior\"]\n self.inv_consloss: float = kwargs[\"inv_consloss\"]\n\n def __call__(self, probs: Tensor, target: Tensor, bounds) -> Tensor:\n assert simplex(probs) # and simplex(target) # Actually, does not care about second part\n\n b, _, w, h = probs.shape # type: Tuple[int, int, int, int]\n # est_prop is the proportion estimated by the network\n est_prop: Tensor = self.__fn__(probs,self.power)\n # gt_prop is the proportion in the ground truth\n if self.curi:\n bounds = bounds[:,0,0] \n gt_prop = torch.ones_like(est_prop)*bounds/(w*h)\n gt_prop = gt_prop[:,:,0]\n else:\n gt_prop: Tensor = self.__fn__(target,self.power) # the power here is actually useless if we have 0/1 gt labels\n est_prop = est_prop.squeeze(2)\n log_gt_prop: Tensor = (gt_prop + 1e-10).log()\n log_est_prop: Tensor = (est_prop + 1e-10).log()\n loss = -torch.einsum(\"bc,bc->\", [est_prop, log_gt_prop]) + torch.einsum(\"bc,bc->\", [est_prop, log_est_prop])\n assert loss.requires_grad == probs.requires_grad # Handle the case for validation\n return loss\n\n\nclass BCELoss():\n def __init__(self, **kwargs):\n # Self.idc is used to filter out some classes of the target mask. Use fancy indexing\n self.idc: List[int] = kwargs[\"idc\"]\n self.dtype = kwargs[\"dtype\"]\n #print(f\"Initialized {self.__class__.__name__} with {kwargs}\")\n\n def __call__(self, d_out: Tensor, label: float):\n bce_loss = torch.nn.BCEWithLogitsLoss()\n loss = bce_loss(d_out,Tensor(d_out.data.size()).fill_(label).to(d_out.device))\n return loss\n\n\nclass BCEGDice():\n def __init__(self, **kwargs):\n self.idc: List[int] = kwargs[\"idc\"]\n self.lamb: List[int] = kwargs[\"lamb\"]\n self.weights: List[float] = kwargs[\"weights\"]\n print(f\"Initialized {self.__class__.__name__} with {kwargs}\")\n def __call__(self, probs: Tensor, target: Tensor, _: Tensor) -> Tensor:\n assert simplex(probs) and simplex(target)\n\n pc = probs[:, self.idc, ...].type(torch.float32)\n tc = target[:, self.idc, ...].type(torch.float32)\n\n w: Tensor = 1 / ((einsum(\"bcwh->bc\", tc).type(torch.float32) + 1e-10) ** 2)\n intersection: Tensor = w * einsum(\"bcwh,bcwh->bc\", pc, tc)\n union: Tensor = w * (einsum(\"bcwh->bc\", pc) + einsum(\"bcwh->bc\", tc))\n\n divided: Tensor = 1 - 2 * (einsum(\"bc->b\", intersection) + 1e-10) / (einsum(\"bc->b\", union) + 1e-10)\n\n loss_gde = divided.mean()\n\n log_p: Tensor = (probs[:, self.idc, ...] + 1e-10).log()\n mask_weighted = torch.einsum(\"bcwh,c->bcwh\", [tc, Tensor(self.weights).to(tc.device)])\n loss_ce = - torch.einsum(\"bcwh,bcwh->\", [mask_weighted, log_p])\n loss_ce /= tc.sum() + 1e-10\n loss = loss_ce + self.lamb*loss_gde\n\n return loss\n\n\n\nclass GeneralizedDice():\n def __init__(self, **kwargs):\n # Self.idc is used to filter out some classes of the target mask. Use fancy indexing\n self.idc: List[int] = kwargs[\"idc\"]\n print(f\"Initialized {self.__class__.__name__} with {kwargs}\")\n\n def __call__(self, probs: Tensor, target: Tensor, _: Tensor) -> Tensor:\n assert simplex(probs) and simplex(target)\n\n pc = probs[:, self.idc, ...].type(torch.float32)\n tc = target[:, self.idc, ...].type(torch.float32)\n\n w: Tensor = 1 / ((einsum(\"bcwh->bc\", tc).type(torch.float32) + 1e-10) ** 2)\n intersection: Tensor = w * einsum(\"bcwh,bcwh->bc\", pc, tc)\n union: Tensor = w * (einsum(\"bcwh->bc\", pc) + einsum(\"bcwh->bc\", tc))\n\n divided: Tensor = 1 - 2 * (einsum(\"bc->b\", intersection) + 1e-10) / (einsum(\"bc->b\", union) + 1e-10)\n\n loss = divided.mean()\n\n return loss\n\n\n\ndef d_loss_calc(pred, label):\n loss_params = {'idc' : [0, 1]}\n criterion = BCELoss(**loss_params, dtype=\"torch.float32\")\n return criterion(pred, label)\n","repo_name":"mathilde-b/SFDA","sub_path":"losses.py","file_name":"losses.py","file_ext":"py","file_size_in_byte":13341,"program_lang":"python","lang":"en","doc_type":"code","stars":29,"dataset":"github-code","pt":"15"} +{"seq_id":"26844185299","text":"from tensorflow import keras\nimport tensorflow as tf\nfrom PIL import Image\nimport pandas as pd\nfrom datetime import datetime\nfrom tqdm.auto import tqdm\nfrom tensorflow.keras.utils import img_to_array\nimport numpy as np\nimport os\nfrom pathlib import Path\nfrom skimage import color as skcolor\nfrom skimage import filters as skfilters\nimport cv2\nimport gc\n\n# Constants\navg_dv = np.array([108.16076384, 61.49104917, 55.44175686])\ncolor_correct = True\ncenter = True\nmax_noise_level = 10000\nstage_idx = {\"Maturation\":0,\n \"Hemostasis\":1,\n \"Inflammatory\":2,\n \"Proliferation\":3}\ncrop_size = 1024\n\nif os.name == 'nt':\n desktop = os.path.join(os.path.join(os.environ['USERPROFILE']), 'Desktop')\n root_images = Path(f\"{desktop}\\Porcine_Exp_Davis\")\n # fixing windows path bug as per \n # https://stackoverflow.com/questions/5629242/getting-every-file-in-a-windows-directory\n image_paths = list(root_images.glob(\"**/*.jpg\"))\nelse:\n desktop = os.path.join(os.path.join(os.path.expanduser('~')), 'Desktop')\n root_images = Path(f\"{desktop}/Porcine_Exp_Davis\")\n # fixing windows path bug as per \n # https://stackoverflow.com/questions/5629242/getting-every-file-in-a-windows-directory\n image_paths = list(root_images.glob(\"**/*.jpg\"))\n\ndir_ = os.path.join(desktop, \"HealNet-Inference\")\nmodel_path = os.path.join(dir_, \"HealNet_cls.h5\")\nprob_table_path = f\"{desktop}/HealNet-Inference/prob_table.csv\"\n\nclass GaussianBlur(tf.keras.__internal__.layers.BaseImageAugmentationLayer):\n \"\"\"Applies a Gaussian Blur with random sigma to an image.\n Args:\n kernel_size: int, 2 element tuple or 2 element list. x and y dimensions for\n the kernel used. If tuple or list, first element is used for the x dimension\n and second element is used for y dimension. If int, kernel will be squared.\n sigma: float, 2 element tuple or 2 element list. Interval in which sigma should\n be sampled from. If float, interval is going to be [0, float), else the\n first element represents the lower bound and the second element the upper\n bound of the sampling interval.\n \"\"\"\n\n def __init__(self, kernel_size, sigma, **kwargs):\n super().__init__(**kwargs)\n self.kernel_size = kernel_size\n self.sigma = sigma\n\n if isinstance(kernel_size, (tuple, list)):\n self.x = kernel_size[0]\n self.y = kernel_size[1]\n else:\n if isinstance(kernel_size, int):\n self.x = self.y = kernel_size\n else:\n raise ValueError(\n \"`kernel_size` must be list, tuple or integer \"\n \", got {} \".format(type(self.kernel_size))\n )\n\n if isinstance(sigma, (tuple, list)):\n self.sigma_min = sigma[0]\n self.sigma_max = sigma[1]\n else:\n self.sigma_min = type(sigma)(0)\n self.sigma_max = sigma\n\n if not isinstance(self.sigma_min, type(self.sigma_max)):\n raise ValueError(\n \"`sigma` must have lower bound and upper bound \"\n \"with same type, got {} and {}\".format(\n type(self.sigma_min), type(self.sigma_max)\n )\n )\n\n if self.sigma_max < self.sigma_min:\n raise ValueError(\n \"`sigma` cannot have upper bound less than \"\n \"lower bound, got {}\".format(sigma)\n )\n\n self._sigma_is_float = isinstance(self.sigma, float)\n if self._sigma_is_float:\n if not self.sigma_min >= 0.0:\n raise ValueError(\n \"`sigma` must be higher than 0\"\n \"when is float, got {}\".format(sigma)\n )\n\n def get_random_transformation(self, image=None, label=None, bounding_box=None):\n sigma = self.get_sigma()\n blur_v = GaussianBlur.get_kernel(sigma, self.y)\n blur_h = GaussianBlur.get_kernel(sigma, self.x)\n blur_v = tf.reshape(blur_v, [self.y, 1, 1, 1])\n blur_h = tf.reshape(blur_h, [1, self.x, 1, 1])\n return (blur_v, blur_h)\n\n def get_sigma(self):\n sigma = self._random_generator.random_uniform(\n shape=(), minval=self.sigma_min, maxval=self.sigma_max\n )\n return sigma\n\n def augment_image(self, image, transformation=None):\n\n image = tf.expand_dims(image, axis=0)\n\n num_channels = tf.shape(image)[-1]\n blur_v, blur_h = transformation\n blur_h = tf.tile(blur_h, [1, 1, num_channels, 1])\n blur_v = tf.tile(blur_v, [1, 1, num_channels, 1])\n blurred = tf.nn.depthwise_conv2d(\n image, blur_h, strides=[1, 1, 1, 1], padding=\"SAME\"\n )\n blurred = tf.nn.depthwise_conv2d(\n blurred, blur_v, strides=[1, 1, 1, 1], padding=\"SAME\"\n )\n\n return tf.squeeze(blurred, axis=0)\n\n @staticmethod\n def get_kernel(sigma, filter_size):\n x = tf.cast(\n tf.range(-filter_size // 2 + 1, filter_size // 2 + 1), dtype=tf.float32\n )\n blur_filter = tf.exp(\n -tf.pow(x, 2.0) / (2.0 * tf.pow(tf.cast(sigma, dtype=tf.float32), 2.0))\n )\n blur_filter /= tf.reduce_sum(blur_filter)\n return blur_filter\n\n def get_config(self):\n config = super().get_config()\n config.update({\"sigma\": self.sigma, \"kernel_size\": self.kernel_size})\n return config\n\ndef get_blur(image_path_obj):\n\n image_path = str(image_path_obj)\n \n # Load the image and convert it to grayscale\n image = cv2.imread(image_path)\n gray = cv2.cvtColor(image, cv2.COLOR_BGR2GRAY)\n\n # Compute the Laplacian of the image and take the absolute value\n lap = cv2.Laplacian(gray, cv2.CV_64F)\n lap = cv2.convertScaleAbs(lap)\n\n # Compute the standard deviation of the Laplacian values\n std_dev = lap.std()\n\n # Return the blur level as a value between 0 and 1\n return std_dev / 255\n\ndef aggregate(probs, stage_idx):\n\n hemo_total = 0\n inf_total = 0\n prolif_total = 0\n matu_total = 0\n\n for prob in probs:\n hemo = prob[stage_idx[\"Hemostasis\"]]\n inf = prob[stage_idx[\"Inflammatory\"]]\n prolif = prob[stage_idx[\"Proliferation\"]]\n matu = prob[stage_idx[\"Maturation\"]]\n\n hemo_total += hemo\n inf_total += inf\n prolif_total += prolif\n matu_total += matu\n\n hemo_avg = hemo_total / len(probs)\n inf_avg = inf_total / len(probs)\n prolif_avg = prolif_total / len(probs)\n matu_avg = matu_total / len(probs)\n\n return hemo_avg, inf_avg, prolif_avg, matu_avg\n\ntry:\n prob_table = pd.read_csv(prob_table_path)\n\nexcept:\n headers = {\"Image\":[], \"Time Processed\":[], \"Blur\":[], \"Patches\": [], \"Hemostasis\":[],\n \"Inflammation\":[], \"Proliferation\":[], \"Maturation\":[]}\n\n table = pd.DataFrame.from_dict(headers)\n table.to_csv(prob_table_path, index=False)\n prob_table = pd.read_csv(prob_table_path)\n\nmodel = keras.models.load_model(model_path, custom_objects={\"GaussianBlur\": GaussianBlur})\nprocessed_ctr = 0\nfor image in tqdm(image_paths):\n if str(image) not in list(prob_table[\"Image\"]):\n try:\n blur = get_blur(image)\n device_image = img_to_array(Image.open(image))\n\n if color_correct:\n img_avg = device_image.mean(axis=(0,1))\n device_image = np.clip(device_image + np.expand_dims(avg_dv - img_avg, axis=0), 0, 255).astype(int)\n\n if center:\n device_image = device_image[1000:4000, 1500:5500]\n\n gray = skcolor.rgb2gray(device_image/255)\n blurred_image = skfilters.gaussian(gray, sigma=1.0)\n thresh = blurred_image > 0.5\n\n max_y, max_x, _ = device_image.shape\n ys = np.random.randint(0, max_y-crop_size, 5)\n xs = np.random.randint(0, max_x-crop_size, 5)\n # Max tries is 5x5 or 25\n tries = np.array(np.meshgrid(ys, xs)).T.reshape(-1, 2)\n\n preds = []\n for y, x in tries:\n # good crop\n if np.count_nonzero(thresh[y:y+crop_size, x:x+crop_size]) < max_noise_level:\n patch = Image.fromarray(device_image[y:y+crop_size, x:x+crop_size].astype(np.uint8))\n patch = patch.resize((128,128))\n image_data = img_to_array(patch)\n\n #image_data = densenet_preprocess(image_data) # densenet hardcoded!\n image_data = np.expand_dims(image_data, axis=0) # adds batch dim\n pred = model.predict(image_data, verbose=0)\n pred = pred.flatten()\n preds.append(pred)\n\n hemo, infl, prol, matu = aggregate(preds, stage_idx)\n\n time = datetime.now().strftime(\"%d/%m/%Y %H:%M:%S\")\n prob_table.loc[len(prob_table)] = [str(image), time, blur, len(preds),\n hemo, infl, prol, matu]\n \n prob_table.to_csv(prob_table_path, index=False)\n prob_table = pd.read_csv(prob_table_path)\n processed_ctr += 1\n gc.collect()\n except Exception as e:\n print(f\"Unable to open {image} (check if corrupted). Skipping...\")\n print(f\"Exception: {e}\")\n\nif processed_ctr:\n print()\n print(f\"Added {processed_ctr} new predictions to {prob_table_path}\")\nelse:\n print()\n print(f\"No new images found in {root_images}\")\n \n","repo_name":"hectorcarrion/HealNet-Inference","sub_path":"healnet_inference.py","file_name":"healnet_inference.py","file_ext":"py","file_size_in_byte":9509,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"15"} +{"seq_id":"42531364241","text":"def transition(chemo, k):\n trans_Hplus = (1 / k) * (chemo[7] / (chemo[7] + chemo[10] + chemo[6] + chemo[3]))\n trans_Hminus = (1 / k) * (chemo[8] / (chemo[8] + chemo[12] + chemo[9] + chemo[5]))\n trans_Vplus = (1 / k) * (chemo[11] / (chemo[11] + chemo[14] + chemo[15] + chemo[13]))\n trans_Vminus = (1 / k) * (chemo[4] / (chemo[4] + chemo[1] + chemo[0] + chemo[2]))\n trans_Hplus_mn = (1 / k) * (chemo[8] / (chemo[8] + chemo[7] + chemo[4] + chemo[11]))\n trans_Hminus_mn = (1 / k) * (chemo[7] / (chemo[8] + chemo[7] + chemo[4] + chemo[11]))\n trans_Vplus_mn = (1 / k) * (chemo[4] / (chemo[8] + chemo[7] + chemo[4] + chemo[11]))\n trans_Vminus_mn = (1 / k) * (chemo[11] / (chemo[8] + chemo[7] + chemo[4] + chemo[11]))\n return [trans_Hplus, trans_Hminus, trans_Vplus, trans_Vminus, trans_Hplus_mn, trans_Hminus_mn,\n trans_Vplus_mn, trans_Vminus_mn]\n","repo_name":"formal-verification-research/retinaModeling","sub_path":"transition.py","file_name":"transition.py","file_ext":"py","file_size_in_byte":878,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"15"} +{"seq_id":"12337572032","text":"from datetime import datetime, timedelta\nfrom peewee import fn\nfrom ..models import Pedido\nfrom .service import Service\n\n\n@Service.register\nclass DashboardService(Service):\n @classmethod\n def sum_last_week(cls):\n date = fn.date(Pedido.dt_pedido)\n rs = Pedido\\\n .select(date.alias('date'), fn.Sum(Pedido.vr_pedido).alias(\"total\"))\\\n .where(Pedido.dt_pedido >= (datetime.now() - timedelta(days=7)))\\\n .group_by(date)\\\n .order_by(date)\\\n .execute()\n return { e.date.strftime(\"%d/%m/%Y\"): e.total for e in rs }\n\n","repo_name":"jaarsi/how4-api","sub_path":"app/services/dashboard.py","file_name":"dashboard.py","file_ext":"py","file_size_in_byte":590,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"15"} +{"seq_id":"15315361869","text":"'''\nDescription: 寻找一个字符串在另一个字符串出现的起始位置\nAuthor: Luminary\nDate: 2021-04-20 10:25:27\nLastEditTime: 2021-04-20 10:26:33\n'''\nclass Solution(object):\n def strStr(self, haystack, needle):\n \"\"\"\n :type haystack: str\n :type needle: str\n :rtype: int\n \"\"\"\n # 双指针滑动窗口判断是否包含子串,包含则返回其起始位置\n if not needle:\n return 0\n left,right = 0, len(needle)\n # 因为在字符串截取时左闭右开,所以right可以取到len(haystack)\n while right <= len(haystack):\n if haystack[left:right] == needle:\n return left\n left += 1\n right +=1\n return -1","repo_name":"Luminary2822/LeetCode_Codings_Python","sub_path":"dailyExec/28-implementstrStr().py","file_name":"28-implementstrStr().py","file_ext":"py","file_size_in_byte":756,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"15"} +{"seq_id":"14805297332","text":"\"\"\"\nPattern Matching (Rabin Karp)\n\nGiven a text txt[0..n-1] and a pattern pat[0..m-1], write a function search(char pat[], char txt[])\nthat prints all occurrences of pat[] in txt[]. You may assume that n > m.\n\"\"\"\nfrom common.problem import Problem\n\n\nclass PatternMatchingRabinKarpAlgorithm(Problem):\n \"\"\"\n Pattern Matching (Rabin Karp)\n \"\"\"\n PROBLEM_NAME = \"PatternMatchingRabinKarpAlgorithm\"\n NOT_FOUND = -1\n\n def __init__(self, input_string, pattern):\n \"\"\"StrStr\n\n Args:\n input_string: haystack\n pattern: to be searched in the haystack\n Returns:\n None\n\n Raises:\n None\n \"\"\"\n super().__init__(self.PROBLEM_NAME)\n self.input_string = input_string\n self.pattern = pattern\n\n def solve(self):\n \"\"\"Solve the problem\n\n Note: The average and best case running time is O(n+m) and the worst case is O(nm).\n\n Args:\n\n Returns:\n integer\n\n Raises:\n None\n \"\"\"\n print(\"Solving {} problem ...\".format(self.PROBLEM_NAME))\n\n pattern_length = len(self.pattern)\n pattern_hash = self.bernstein_hash(self.pattern)\n\n for i in range(len(self.input_string) - pattern_length):\n if self.bernstein_hash(self.input_string[i:i + pattern_length]) == pattern_hash:\n return i + 1\n\n return self.NOT_FOUND\n\n @staticmethod\n def bernstein_hash(value):\n \"\"\"Bernstein hash value of the string\n\n Note:\n\n Args:\n value: string to hash\n\n Returns:\n integer\n\n Raises:\n None\n \"\"\"\n value_bytes = bytearray(value, 'ascii')\n hash_value = 5381\n for c in value_bytes:\n hash_value = hash_value * 33 + c\n\n return hash_value\n","repo_name":"santhosh-kumar/AlgorithmsAndDataStructures","sub_path":"python/problems/string/pattern_matching_rabin_karp.py","file_name":"pattern_matching_rabin_karp.py","file_ext":"py","file_size_in_byte":1837,"program_lang":"python","lang":"en","doc_type":"code","stars":2,"dataset":"github-code","pt":"15"} +{"seq_id":"40720254489","text":"class DFS:\r\n def __init__(self, graph, root):\r\n self.graph = graph\r\n self.visited = dict()\r\n self.stack = list()\r\n self.stack.append(root)\r\n self.counter = 0\r\n\r\n def run(self, target):\r\n while len(self.stack) != 0:\r\n self.counter += 1\r\n init_node = self.stack.pop(len(self.stack) - 1)\r\n if init_node.UID not in self.visited.keys():\r\n self.visited[init_node.UID] = init_node\r\n if init_node.is_equal(target):\r\n return True, self.counter, init_node.step\r\n for nb in self.graph.reveal_neighbors(init_node):\r\n nb.link = init_node\r\n self.stack.append(nb)\r\n return False, 0, 0\r\n","repo_name":"barisozbas/Courses","sub_path":"CS_451/Assignment 1/DFS.py","file_name":"DFS.py","file_ext":"py","file_size_in_byte":761,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"15"} +{"seq_id":"72527648012","text":"from connections import ConnectionPool\nfrom connections import UnclosableConnection\nimport queue\nimport threading\nfrom threads import ClientTaskControl, TaskControl\nfrom typing import Callable\n\nclass ResultHandler(object):\n def __init__(self, success_q, error_q):\n self.__success_q = success_q\n self.__error_q = error_q\n\n def put_error(self, msg):\n self.__error_q.put(msg)\n\n def put_success(self, msg):\n self.__success_q.put(msg)\n\nclass HttpJackHammer(object):\n\n def __init__(self, task: Callable[[UnclosableConnection, ResultHandler], None], on_error: Callable[[object, ClientTaskControl], None], on_success: Callable[[object, ClientTaskControl], None]) -> None:\n self.__task = task\n self.__on_error = on_error\n self.__on_success = on_success\n self.__task_control = TaskControl()\n self.__client_task_control = ClientTaskControl(self.__task_control)\n self.__success_q = queue.Queue()\n self.__error_q = queue.Queue()\n self.__task_result_handler = ResultHandler(self.__success_q, self.__error_q)\n\n def start(self, host: str, num_connections: int) -> threading.Thread:\n self.__connection_pool = ConnectionPool(num_connections)\n self.__connection_pool.connect(host)\n thread = threading.Thread(target=self.__launch_threads())\n thread.start()\n return thread\n\n def __launch_threads(self) -> None:\n try:\n threads = []\n for i in range(self.__connection_pool.capacity()):\n threads.append(threading.Thread(target=self.__task_loop))\n threads.append(threading.Thread(target=self.__success_watcher_loop))\n threads.append(threading.Thread(target=self.__error_watcher_loop))\n\n self.__task_control.start()\n for t in threads:\n t.start()\n \n # block execution till interupt or natural end\n while self.__task_control.running():\n pass\n except KeyboardInterrupt:\n self.__task_control.stop()\n finally:\n for t in threads:\n t.join()\n self.__connection_pool.close_connections()\n\n def __success_watcher_loop(self):\n while self.__task_control.running():\n if self.__success_q.qsize() > 0:\n self.__on_success(self.__success_q.get(), self.__client_task_control)\n\n def __error_watcher_loop(self):\n while self.__task_control.running():\n if self.__error_q.qsize() > 0:\n self.__on_error(self.__error_q.get(), self.__client_task_control)\n\n def __task_loop(self):\n while self.__task_control.running():\n with self.__connection_pool.get_connection() as conn:\n self.__task(conn, self.__task_result_handler)","repo_name":"d4l-w4r/jackhammer","sub_path":"jackhammer.py","file_name":"jackhammer.py","file_ext":"py","file_size_in_byte":2823,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"15"} +{"seq_id":"5310533454","text":"#!/usr/bin/python\n#import the simulator and other stuff\nfrom simulator import lidarSimulator\nimport simulator\nfrom breezyslam.algorithms import RMHC_SLAM\nfrom breezyslam.components import Laser\nfrom collections import namedtuple\nimport time\nimport math\nimport random\n\n#import the library to plot points\nimport matplotlib as mpl\nmpl.use('Agg')\nimport matplotlib.pyplot as plt\n\n#import the libraries to send the data over udp\nfrom struct import *\nimport socket\n\n#where to send UDP data\nUDP_IP = \"127.0.0.1\"\nUDP_PORT = 5005\n\n#define the named tuples\nPoint = namedtuple('Point', 'x y')\nLineseg = namedtuple('Lineseg', 's e')\n\n#define the size of the map to generate in pixels and meters\nMAP_SIZE_PIXELS = 2048\nMAP_SIZE_METERS = 20\n\n#define the points of the room and maike a loop of lineseg namedtuples from them\nroom_pts = [Point(0, 0), Point(10, 0), Point(10, 2), Point(12, 2), Point(15,5),Point(15,10),Point(5,10), Point(5,12), Point(0,12)]\nroom = simulator.loop(room_pts)\n#add an obstacle in the room\nobstacle = simulator.loop([Point(2,3), Point(3,3), Point(2.5,4)])\n#add the obstacle to the room (In python, + concatenates lists)\nroom = room + obstacle\n\n#define the starting point of the lidar simulator\nlidarPoint = Point(4,4)\nlidarAngle = 3\n\n#define data about the lidar simulator\nnum_scans = 50\nlidarRange = 16\nnoise = 0.01\n\n#create a udp socket to send data on\nsock = socket.socket(socket.AF_INET, socket.SOCK_DGRAM) # UDP\n\n#function to send data over UDP\ndef sendUDP(x, y, theta):\n #generate binary data of the angle and position\n packed = pack('>fff', theta, x, y)\n \n #calculate a checksum, total off all data modulo 256\n sum = 0\n for c in packed:\n sum += ord(c)\n sum = sum % 256\n \n #generate binary data including checksum\n packed = pack('>fffB', theta, x, y, sum)\n \n #send data\n sock.sendto(packed, (UDP_IP, UDP_PORT))\n\n#initialize lidar siulator\nlidarSim = lidarSimulator(lidarPoint, lidarAngle, num_scans, lidarRange, noise, room)\n\n#create laser model\nlaser = Laser(num_scans, 10, 360, 1000 * lidarRange, 0,0)\n\n#initialize the slam\nslam = RMHC_SLAM(laser, MAP_SIZE_PIXELS, MAP_SIZE_METERS, random_seed = int(random.uniform(0,10000)))\n\n#create empty lists to fill with points and plot when the program is done\npositions = []\nactual_pos = []\n\n#number of loops, crude way of changing directions\ni = 0\n\n#repeat 500 times\nfor unused in range(500):\n #increment loop counter\n i += 1\n #move diagonally down/right half of the time, and the other way half of the time\n if i < 100:\n lidarSim.translate(Point(0.01, 0.01))\n lidarSim.rotate(0.01)\n else:\n lidarSim.translate(Point(-0.01,-0.01))\n lidarSim.rotate(-0.02)\n if i == 200:\n #reset timer if necesary\n i = 0\n \n #add the actual position to the list\n actual_pos.append((lidarSim.position.x, lidarSim.position.y, lidarSim.angle))\n \n #run the lidar simulator - this can be replaced by the code that reads from a real sensor\n lidarSim.simLidar()\n scan = []\n scan = lidarSim.getScan()\n \n #Run the actual slam algorithm to determine the position from the scan\n slam.update([1000 * s for s in scan])\n \n #get the position\n x,y,theta = slam.getpos()\n #add the position to the list to plot layer\n positions.append((x,y,theta))\n \n #uncomment to plot every 10th scan\n #if i %10 == 0:\n #lidarSim.plotScan('scan' + str(i))\n \n #print data for debugging and send it over UDP\n print(\"X: \" + str(x/1000) + \", Y: \" + str(y/1000) + \", Angle: \" + str(theta))\n sendUDP(x / 1000 - 10,y / 1000 - 10,theta)\n \n #uncomment to scan at a realistic rate\n #time.sleep(0.1)\n\n#plot the lidar scan and actual position\nfig = plt.figure(1)\nplt.plot([(p[0] - positions[0][0])/ 1000 for p in positions],[(p[1] - positions[0][1]) / 1000 for p in positions], 'b-')\nplt.plot([p[0] - actual_pos[0][0] for p in actual_pos],[p[1] - actual_pos[0][1] for p in actual_pos], 'r-')\n\n#find files with the same name and add a number on the end to avoid duplicate files\nimport os\ni = 0\nwhile os.path.exists('{}{:d}.png'.format('path', i)):\n i += 1\n#save the figure with the two paths\nfig.savefig('{}{:d}.png'.format('path', i))\n","repo_name":"JackToaster/lidar-slam","sub_path":"BSLAM-test/test.py","file_name":"test.py","file_ext":"py","file_size_in_byte":4241,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"15"} +{"seq_id":"817622828","text":"'''\nPlatform: HackerRank\n\nYou are given three integers and representing the dimensions of a cuboid along with an integer.\nPrint a list of all possible coordinates given by on a 3D grid where the sum of x,y,z is not equal to n \n'''\ndef permutation(x,y,z,n):\n res = [[v,b,n] for v in range(x+1)\n for b in range(y+1)\n for n in range(z+1)]\n \n return [x for x in res if sum(x) != n]","repo_name":"wojtekw0703/CodeSignal-HackerRank","sub_path":"assignments/permutation_list_comprehension.py","file_name":"permutation_list_comprehension.py","file_ext":"py","file_size_in_byte":416,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"15"} +{"seq_id":"4678744102","text":"import os\nimport util\nimport argparse\n\ndef parserCommad():\n '''\n Get the command line parameter and return them.\n '''\n parser = argparse.ArgumentParser()\n\n parser.add_argument('--RQ1_mutant_path', action='store',\n default=\"./_RQ1_mutant_set/\",\n dest='RQ1_mutant_path',\n help='RQ1 mutant root dictionary.')\n\n parser.add_argument('--num_mutants_set', action='store',\n dest='num_mutants_set',\n type=int,\n default=5,\n help='number of mutants sets.')\n\n parser.add_argument('--version', action='version',\n version='%(prog)s 1.0')\n\n results = parser.parse_args()\n\n return results\n\nif __name__ == \"__main__\":\n\n num_mutants_set = parserCommad().num_mutants_set\n\n for mutant_set_index in range(1, num_mutants_set+1):\n compile_dir = parserCommad().RQ1_mutant_path + \"mutant_set_\" + str(mutant_set_index) + \"/compile/\"\n file_name_list = os.listdir(compile_dir)\n file_name = file_name_list[0]\n replace_index = util.findIndex(file_name, \"_\")\n file_name = file_name[:replace_index[-1]]\n\n mutation_dir = parserCommad().RQ1_mutant_path + \"mutant_set_\" + str(mutant_set_index) + \"/Mutant_source/\"\n mutation_file_list = os.listdir(mutation_dir)\n mutation_file_number = len(mutation_file_list)\n\n with open(parserCommad().RQ1_mutant_path + \"mutant_set_\" + str(mutant_set_index) + \"/res_execute_mutant.txt\", 'w') as f :\n f.write(\"\") # create and clean res_record.txt\n f.close()\n f = open(parserCommad().RQ1_mutant_path + \"mutant_set_\" + str(mutant_set_index) + \"/res_execute_mutant.txt\", 'a')\n\n for i in range(mutation_file_number):\n file_temp_name = file_name + \"_\" +str(i+1) + \".c.exe\"\n if file_temp_name in file_name_list:\n f.write(str(i+1)+\"\\n\")\n\n f.close()\n","repo_name":"chajishaji/HMBFL","sub_path":"HMBFLtool/_ideal_higher_mutant_set_extend/create_res_execute_RQ1_mutant.py","file_name":"create_res_execute_RQ1_mutant.py","file_ext":"py","file_size_in_byte":2002,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"15"} +{"seq_id":"1414243402","text":"#! /usr/bin/python3\n\nimport argparse\nimport logging\n\nimport sentencepiece as spm\n\n# assuming standard Sockeye vocab files\nPAD_ID = 0\nUNK_ID = 1\nBOS_ID = 2\nEOS_ID = 3\n\n\ndef parse_args():\n parser = argparse.ArgumentParser()\n\n parser.add_argument(\"--model-prefix\", type=str, help=\"Path where model file should be stored.\", required=True)\n parser.add_argument(\"--input\", type=str, help=\"Path to input text (for instance, truecased).\", required=True)\n parser.add_argument(\"--vocab-size\", type=int, help=\"Desired vocabulary size.\", required=True)\n\n args = parser.parse_args()\n\n return args\n\n\ndef main():\n\n args = parse_args()\n\n logging.basicConfig(level=logging.DEBUG)\n logging.debug(args)\n\n train_args = [\"--model_prefix=%s\" % args.model_prefix,\n \"--input=%s\" % args.input,\n \"--vocab_size=%d\" % args.vocab_size,\n \"--character_coverage=1.0\",\n \"--model_type=unigram\",\n \"--pad_id=%d\" % PAD_ID,\n \"--unk_id=%d\" % UNK_ID,\n \"--bos_id=%d\" % BOS_ID,\n \"--eos_id=%d\" % EOS_ID]\n\n train_args_str = \" \".join(train_args)\n\n spm.SentencePieceTrainer.Train(train_args_str)\n\n\nif __name__ == '__main__':\n main()\n","repo_name":"ZurichNLP/domain-robustness","sub_path":"scripts/train_sentencepiece.py","file_name":"train_sentencepiece.py","file_ext":"py","file_size_in_byte":1262,"program_lang":"python","lang":"en","doc_type":"code","stars":12,"dataset":"github-code","pt":"15"} +{"seq_id":"16579868815","text":"from config import Config\nfrom functools import wraps\nfrom flask import Blueprint, jsonify, abort, session, request\nfrom werkzeug.exceptions import HTTPException\nfrom pymysql.err import *\nfrom objects import mysql\nimport json, requests\n\ndb = mysql.DB()\napi = Blueprint('api', __name__)\n\nfuns = {\n 'get_mappool': db.get_mappool,\n 'get_teams': db.get_teams,\n 'get_players': db.get_players,\n 'get_matchs': db.get_matchs,\n 'get_staff': db.get_staff,\n}\n\ndef login_required(f):\n @wraps(f)\n def decorated_function(*args, **kwargs):\n if session == {}:\n abort(400, 'no session')\n return f(*args, **kwargs)\n return decorated_function\n\n@api.route('/show/')\n@login_required\ndef show_data(table_name):\n def sql():\n try:\n return db.query_all(\"SELECT * FROM `%s`;\" % table_name)\n except Exception:\n abort(404)\n\n if table_name == '*':\n return jsonify(db.query_all(\"SHOW TABLE STATUS FROM `tourney`;\"))\n elif table_name in funs.keys():\n return jsonify(funs.get(table_name, sql)())\n else:\n abort(404)\n\n@api.route('/data//')\n@login_required\ndef getdata(table_name:str, id:str):\n if table_name in ('group', 'map_group', 'mappool', 'match', 'player', 'round', 'staff', 'team', 'tourney', 'view_staff'):\n if id.isdigit():\n return jsonify(data=db.query_one('select * from `%s` where id = %s limit 1' % (table_name, id)))\n elif id == '*':\n return jsonify(data=db.query_all('select * from `%s`' % table_name))\n else:\n abort(404)\n else:\n abort(404)\n\n@api.route('/m_preduct/')\n@login_required\ndef getdata_preduct(id:int):\n res = db.query_one(\"SELECT JSON_OBJECT('id', m.id, 'team1', JSON_OBJECT('id', t1.id, 'full_name', t1.full_name, 'flag_name', t1.flag_name, 'acronym', t1.acronym), 'team2', JSON_OBJECT('id', t2.id, 'full_name', t2.full_name, 'flag_name', t2.flag_name, 'acronym', t2.acronym)) AS `json` FROM `match` m LEFT JOIN team t1 ON t1.id = m.team1 LEFT JOIN team t2 ON t2.id = m.team2 where m.id = %s\" % (id))\n d = json.loads(res['json'])\n for i in range(2):\n p = db.query_all(\"SELECT username FROM player WHERE team=%s\", (d[f'team{i+1}']['id']))\n d[f'team{i+1}']['players'] = []\n for w in p:\n d[f'team{i+1}']['players'].append(w['username'])\n return jsonify(data=d)\n\n@api.route('/match_mysql/')\n@login_required\ndef getdata_match_mysql(id:int):\n return jsonify(data=db.get_matchs(id=int(id)))\n \n@api.route('/check_round')\ndef check_round():\n if request.args.get('id'):\n return db.query(\"SELECT COUNT(*) as match_count, r.pool_publish from `match` lnner join `round` as r on r.id=round_id WHERE round_id = %s\", (request.args.get('id'),))\n else:\n abort(400, 'id?')\n\n@api.route('/check_map')\ndef map_round():\n if request.args.get('id'):\n return db.query(\"SELECT COUNT(*) as map_count, id AS map_id FROM `mappool` WHERE id = %s\", (request.args.get('id'),))\n else:\n abort(400, 'id?')\n\n@api.route('/teams//')\n@login_required\ndef teams(team_id: int):\n try:\n data = db.query_one(\"SELECT json FROM `json_team` WHERE id = %s\", (team_id,))\n return jsonify(json.loads(data['json']))\n except Exception as e:\n abort(400, e)\n\n@api.route('/maps//')\n@login_required\ndef maps(map_id: int):\n try:\n data = db.query_one(\"SELECT json FROM `json_mappool` WHERE id = %s\", (map_id,))\n return jsonify(json.loads(data['json']))\n except Exception as e:\n abort(400, e)\n\n@api.route('/web/

')\n@login_required\ndef osuapiv1(p):\n try:\n args = request.args.to_dict()\n args['k'] = Config.OSU_API_KEY\n req = requests.get(\n url = 'https://osu.ppy.sh/api/%s' % p,\n params = args\n )\n\n result = req.json()\n if result:\n return jsonify(result)\n else:\n return 'no context', 400\n except Exception as e:\n abort(400, e)\n\n@api.errorhandler(HTTPException)\ndef handle_exception(e):\n return jsonify(error=str(e)), HTTPException.code\n","repo_name":"Varkaria/oturna","sub_path":"blueprints/api.py","file_name":"api.py","file_ext":"py","file_size_in_byte":4176,"program_lang":"python","lang":"en","doc_type":"code","stars":2,"dataset":"github-code","pt":"15"} +{"seq_id":"71448656971","text":"import torch \nimport cv2 as cv\nimport Config\nimport numpy as np\nfrom scipy.io import savemat\nfrom matplotlib import pyplot as plt\n\ndef save_images_of_batch(inputs, targets, predictions, fname):\n rows = list()\n for input_, target, prediction in zip(inputs, targets, predictions):\n prediction = (prediction * 0.5 + 0.5) * 255\n target = (target * 0.5 + 0.5) * 255\n input_ = (input_ * 0.5 + 0.5) * 255\n prediction = prediction.permute(1, 2, 0)\n target = target.permute(1, 2, 0)\n input_ = input_.permute(1, 2, 0)\n\n row = np.hstack([input_.cpu().numpy(), target.cpu().numpy(), prediction.cpu().numpy()])\n rows.append(row)\n final_grid = rows[0]\n for row in rows[1:]:\n final_grid = cv.vconcat([final_grid, row])\n cv.imwrite(fname, final_grid)\n\n\ndef save_checkpoint(generator_model, generator_optimizer, discriminator_model, discriminator_optimizer, fname):\n model_dict = {\n \"generator_model\": generator_model.state_dict(),\n \"generator_optimizer\": generator_optimizer.state_dict(),\n \"discriminator_model\": discriminator_model.state_dict(),\n \"discriminator_optimizer\": discriminator_optimizer.state_dict()\n }\n torch.save(model_dict, fname)\n\n\ndef load_checkpoint(generator_model, generator_optimizer, discriminator_model, discriminator_optimizer, learning_rate, fname):\n model_dict = torch.load(fname, map_location=Config.DEVICE)\n generator_model.load_state_dict(model_dict[\"generator_model\"])\n generator_optimizer.load_state_dict(model_dict[\"generator_optimizer\"])\n discriminator_model.load_state_dict(model_dict[\"discriminator_model\"])\n discriminator_optimizer.load_state_dict(model_dict[\"discriminator_optimizer\"])\n\n for param_group in generator_optimizer.param_groups:\n param_group[\"lr\"] = learning_rate\n\n for param_group in discriminator_optimizer.param_groups: \n param_group[\"lr\"] = learning_rate\n\n\ndef save_history(discriminator_loss, generator_loss, fname=\"history \"):\n history_dict = {\n \"discriminator_loss\": discriminator_loss,\n \"generator_loss\": generator_loss\n }\n savemat(fname + '.mat', history_dict)\n plt.figure(figsize=(19.2, 10.9))\n plt.plot(discriminator_loss, label='Discriminator Loss')\n plt.plot(generator_loss, label='Generator Loss')\n plt.legend()\n plt.savefig(fname + 'png')\n\n\n \n\n \n\n \n\n","repo_name":"serkancancaglayan/Satellite2Map","sub_path":"Utils.py","file_name":"Utils.py","file_ext":"py","file_size_in_byte":2401,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"15"} +{"seq_id":"74252187851","text":"import json\nimport scrapy\n\nfrom locations.hourstudy import inputoutput\n\n\nclass CoopFoodSpider(scrapy.Spider):\n name = \"coopfood\"\n allowed_domains = [\"api.coop.co.uk\"]\n download_delay = 0.5\n page_number = 1\n start_urls = (\n 'https://api.coop.co.uk/locationservices/finder/food/?location=54.9966124%2C-7.308574799999974&distance=30000000000&always_one=true&format=json',\n )\n\n def parse(self, response):\n data = json.loads(response.body_as_unicode())\n\n for store in data['results']:\n open_hours = store['opening_hours']\n clean_hours = ''\n for time in open_hours:\n if time['opens'] is not None and time['closes'] is not None:\n clean_hours = clean_hours + time['name'][:2] + ' ' + time['opens'] + '-' + time['closes'] + ' ; '\n\n properties = {\n \"ref\": store['url'],\n \"name\": store['name'],\n \"opening_hours\": clean_hours,\n \"website\": \"https://finder.coop.co.uk\"+store['url'],\n \"addr_full\": store['street_address'] + \" \" + store['street_address2'] + \" \" + store['street_address3'],\n \"city\": store['town'],\n \"postcode\": store['postcode'],\n \"country\": 'United Kingdom',\n \"lon\": float(store['position']['x']),\n \"lat\": float(store['position']['y']),\n \"phone\": store[\"phone\"],\n }\n\n yield inputoutput(**properties)\n\n if data['next'] is not None:\n self.page_number = self.page_number + 1\n yield scrapy.Request(\n self.start_urls[0] + '&page=' + str(self.page_number)\n )\n","repo_name":"bealbrown/allhours","sub_path":"locations/spiders/noted/coopfood.py","file_name":"coopfood.py","file_ext":"py","file_size_in_byte":1716,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"15"} +{"seq_id":"15306005868","text":"import re\nimport subprocess\nimport sys\n\nfrom core.log import Log\n\nclass Jails:\n\n def __init__(self, jails = [], debug = False):\n self._jails = jails\n self._debug = debug\n\n def get_jail_details(self):\n jails_status = []\n\n for jail in self._jails:\n exec_fail2ban = subprocess.check_output(\"fail2ban-client status \"\\\n + jail,\n shell=True,\n stderr=subprocess.DEVNULL).decode('utf-8')\n\n jails_status.append(self.jail_ip_banned_list(exec_fail2ban))\n\n print(jails_status)\n\n return jails_status\n\n def generate_ip_banned_list(self, ip_banned_list):\n return [ip.split() for ip in ip_banned_list][0]\n\n def jail_ip_banned_list(self, jail_output):\n ip_banned_list = []\n\n ip_banned = re.search(r\"Banned IP list:(.*\\b)\", jail_output, re.IGNORECASE | re.MULTILINE)\n\n if ip_banned:\n ip_banned_list.append(ip_banned.group(1).strip())\n\n if self._debug:\n print(\"Total banned count: {0}\".format(ip_banned_list))\n\n return self.generate_ip_banned_list(ip_banned_list)\n","repo_name":"micas06gua/fail2ban-attack-monitoring","sub_path":"core/jail.py","file_name":"jail.py","file_ext":"py","file_size_in_byte":1178,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"15"} +{"seq_id":"33878890282","text":"import tensorflow as tf\nimport numpy as np\nfrom collections import Counter\n\nbatch_size=100\nseq_leng=9\n\ntest=open('qsum_data.csv','r')\nxy_test=test.read().split('\\n')\npos_dic={}\ntest_pos=[]\ntest_datas=[]\nfor i in range(len(xy_test)-1):\n pos_dic[int(xy_test[i].split(', ')[0])]=np.array(xy_test[i].split(', ')[1:],dtype=np.float32)\n xy_test[i]=xy_test[i].split(', ')[1:]\nxy_test=np.array(xy_test[:-1],dtype=np.float32)\nnp.random.shuffle(xy_test)\n\nsess=tf.Session()\n\nnew_saver=tf.train.import_meta_graph('./learning_model/sum.ckpt.meta')\nnew_saver.restore(sess,tf.train.latest_checkpoint('./learning_model/'))\n#sess.run(tf.global_variables_initializer())\n\ngraph=tf.get_default_graph()\nX=graph.get_tensor_by_name('X:0')\nY=graph.get_tensor_by_name('Y:0')\nprediction=graph.get_tensor_by_name('prediction:0')\naccuracy=graph.get_tensor_by_name('accuracy:0')\n\nret=open('ret_sum.txt','w')\nY_real=[]\nY_pred=[]\naccu=0\nfor i in range(int(np.ceil(78482/batch_size))):\n test_batch=xy_test[i*batch_size:i*batch_size+batch_size]\n test_x,test_y=test_batch[:,:-2].reshape(-1,seq_leng,1),test_batch[:,-2:]\n\n accu+=sess.run(accuracy,feed_dict={X:test_x,Y:test_y})\n\n Y_real+=list(sess.run(tf.argmax(Y,1),feed_dict={Y:test_y}))\n Y_pred+=list(sess.run(tf.argmax(prediction,1),feed_dict={X:test_x}))\n\nprint('accuracy : ',accu/int(np.ceil(78482/batch_size)))\n\nY_ret=2*np.array(Y_real)+np.array(Y_pred)\nprint(Counter(Y_ret))\ntrue_snp=[i for i, x in enumerate(Y_ret) if x==0]\nfalse_snp=[i for i, x in enumerate(Y_ret) if x==1]\n#print(len(true_snp),len(false_snp))\nc=0\nfor i in range(len(true_snp)):\n for pos in list(pos_dic.keys()):\n if np.array_equal(xy_test[true_snp[i]],pos_dic[pos]):\n ret.write(\"%s\\n\"%pos)\n print(c,i,pos)\n# print(c,pos)\n c+=1\nret.write(\"\\n\\n\")\nfor i in range(len(false_snp)):\n for pos in list(pos_dic.keys()):\n if np.array_equal(xy_test[false_snp[i]],pos_dic[pos]):\n ret.write(\"%s\\n\"%pos)\ntest.close()\nret.close()\n","repo_name":"DeeplearningforSNP/Deeplearning","sub_path":"saver_restore/test_snp.py","file_name":"test_snp.py","file_ext":"py","file_size_in_byte":2004,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"15"} +{"seq_id":"31915351685","text":"s, ans, i = input(), list(), 1\r\nwhile (i < len(s)):\r\n if (s[i] == '[' and s[i - 1].isalpha()):\r\n temp, j = \"\", i - 1\r\n while (s[j].isalpha()):\r\n temp += s[j]; j -= 1\r\n temp, j = temp[::-1] + \" \", i + 1\r\n while (s[j] != ']'):\r\n temp += s[j]; j += 1\r\n ans.append(temp)\r\n i = j; continue\r\n i += 1\r\nprint(-1 if not ans else \"\\n\".join(ans))\r\n\r\n\r\n'''\r\nimport re\r\n\r\nres = re.findall(r\"([a-zA-Z]+)\\[(\\w+-\\d+)\\]\", input())\r\nprint(-1 if res == [] else '\\n'.join([f'{x[0]} {x[1]}' for x in res]))\r\n'''","repo_name":"ayushman-25/Codechef-Submissions","sub_path":"Chintu’s internship project.py","file_name":"Chintu’s internship project.py","file_ext":"py","file_size_in_byte":560,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"15"} +{"seq_id":"6158101346","text":"\"\"\"Creacion de tablas productos y categorias\n\nRevision ID: 8157e10da6b2\nRevises: \nCreate Date: 2023-01-14 02:13:03.856457\n\n\"\"\"\nfrom alembic import op\nimport sqlalchemy as sa\n\n\n# revision identifiers, used by Alembic.\nrevision = '8157e10da6b2'\ndown_revision = None\nbranch_labels = None\ndepends_on = None\n\n\ndef upgrade():\n # ### commands auto generated by Alembic - please adjust! ###\n op.create_table('categorias',\n sa.Column('id', sa.Integer(), autoincrement=True, nullable=False),\n sa.Column('nombre', sa.String(length=45), nullable=False),\n sa.PrimaryKeyConstraint('id'),\n sa.UniqueConstraint('nombre')\n )\n op.create_table('productos',\n sa.Column('id', sa.Integer(), autoincrement=True, nullable=False),\n sa.Column('nombre', sa.String(length=50), nullable=False),\n sa.Column('precio', sa.Float(), nullable=True),\n sa.Column('disponible', sa.Boolean(), nullable=True),\n sa.PrimaryKeyConstraint('id'),\n sa.UniqueConstraint('nombre')\n )\n # ### end Alembic commands ###\n\n\ndef downgrade():\n # ### commands auto generated by Alembic - please adjust! ###\n op.drop_table('productos')\n op.drop_table('categorias')\n # ### end Alembic commands ###\n","repo_name":"Ricardo2930/backend-g-10","sub_path":"migrations/versions/8157e10da6b2_creacion_de_tablas_productos_y_.py","file_name":"8157e10da6b2_creacion_de_tablas_productos_y_.py","file_ext":"py","file_size_in_byte":1199,"program_lang":"python","lang":"en","doc_type":"code","stars":2,"dataset":"github-code","pt":"15"} +{"seq_id":"39932552547","text":"# -*- mode: python -*-\n\nimport gooey\n\ngooey_root = os.path.dirname(gooey.__file__)\ngooey_languages = Tree(os.path.join(gooey_root, 'languages'), prefix = 'gooey/languages')\ngooey_images = Tree(os.path.join(gooey_root, 'images'), prefix = 'gooey/images')\nblock_cipher = None\n\na = Analysis(['main.py'],\n pathex=['C:\\\\Users\\\\mackendy\\\\src\\\\python\\\\Anglistik'],\n binaries=[],\n datas=[],\n hiddenimports=[],\n hookspath=[],\n runtime_hooks=[],\n excludes=[],\n win_no_prefer_redirects=False,\n win_private_assemblies=False,\n cipher=block_cipher)\npyz = PYZ(a.pure, a.zipped_data,\n cipher=block_cipher)\nexe = EXE(pyz,\n a.scripts,\n a.binaries,\n a.zipfiles,\n a.datas,\n gooey_images,\n gooey_languages,\n name='ang',\n debug=False,\n strip=False,\n upx=True,\n runtime_tmpdir=None,\n console=False) \n","repo_name":"ecstatic-morse/anglistic-sched","sub_path":"main.spec","file_name":"main.spec","file_ext":"spec","file_size_in_byte":1030,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"15"} +{"seq_id":"38390144025","text":"# coding: utf-8\n\n\"\"\"Shows the usage of pywhatlang.\"\"\"\n\n\nimport pywhatlang\nTEXTS = [\n \"Hello world. It is my pleasure to be here!\",\n \"مرحباً بالجميع. من دواعي سروري أن أكون معكم!\"\n]\n\ndef main():\n for text in TEXTS:\n lang, confidence, is_reliable = pywhatlang.detect_lang(text)\n print(f\"The detected language is {lang}\\nConfidence: {confidence}\\nis_reliable: {is_reliable}\")\n\n\nif __name__ == '__main__':\n main()","repo_name":"blindpandas/pywhatlang","sub_path":"usage.py","file_name":"usage.py","file_ext":"py","file_size_in_byte":470,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"15"} +{"seq_id":"36635129031","text":"from flask import Flask,request, url_for, redirect, render_template\r\nimport pickle\r\nimport numpy as np\r\n\r\napp = Flask(__name__)\r\n\r\n\r\n@app.route('/')\r\ndef hello_world():\r\n return render_template(\"forest.html\")\r\n\r\n\r\n@app.route('/predict', methods=['POST', 'GET'])\r\ndef predict():\r\n knnModel = pickle.load(open('knnModel.pkl', 'rb'))\r\n int_features = [int(x) for x in request.form.values()]\r\n final = [np.array(int_features)]\r\n knnPrediction = knnModel.predict(final)\r\n if knnPrediction[0] == 1:\r\n svrModel = pickle.load(open('svrModel.pkl', 'rb'))\r\n svrPrediction = svrModel.predict(final)\r\n\r\n if knnPrediction[0] == 1 and svrPrediction[0] >= 0.45:\r\n return render_template('forest.html', pred='You are at a risk of heart attack. We recommend you to visit a cardiologist ({}% risk)'.format(int(svrPrediction[0]*100)))\r\n elif knnPrediction[0] == 1:\r\n return render_template('forest.html', pred='You are at a risk of heart attack. We recommend you to visit a cardiologist')\r\n else:\r\n return render_template('forest.html', pred='You are not at a risk of heart attack.')\r\n\r\n\r\nif __name__ == '__main__':\r\n app.run(debug=True)\r\n","repo_name":"rajaryan18/Heart-Attack-Predictor","sub_path":"app.py","file_name":"app.py","file_ext":"py","file_size_in_byte":1185,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"15"} +{"seq_id":"39566502731","text":"\n# Definition for singly-linked list.\n# class ListNode:\n# def __init__(self, x):\n# self.val = x\n# self.next = None\n'''\n需要一个carry 位 知道前面有没有溢出的数字\n\n'''\nclass Solution:\n def addTwoNumbers(self, l1: ListNode, l2: ListNode) -> ListNode:\n dummy = cur = ListNode(0)\n carry = 0\n while l1 or l2 or carry: # 这样是为了首先防止l1没了 l2还有的情况 还可以防止都没了 但是需要carry进位的情况\n if l1:\n carry += l1.val\n l1 = l1.next\n if l2:\n carry += l2.val\n l2 = l2.next\n cur.next = ListNode(carry%10)\n cur = cur.next\n carry//=10\n return dummy.next\n\n\n","repo_name":"Edison199902222/Leetcode_note","sub_path":"leetcode/Linked List/2. Add Two Numbers.py","file_name":"2. Add Two Numbers.py","file_ext":"py","file_size_in_byte":768,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"15"} +{"seq_id":"35112026823","text":"# -*- coding: utf-8 -*-\nfrom __future__ import unicode_literals\n\nfrom django_pgjson.fields import JsonField\n\nfrom django.db import models, migrations\n\n\nclass Migration(migrations.Migration):\n\n dependencies = [\n ('userstorage', '0001_initial'),\n ]\n\n operations = [\n migrations.RunSQL(\n sql='ALTER TABLE userstorage_storageentry ALTER COLUMN value DROP NOT NULL;',\n ),\n ]\n","repo_name":"andyzsf/taiga-back-","sub_path":"taiga/userstorage/migrations/0002_fix_json_field_not_null.py","file_name":"0002_fix_json_field_not_null.py","file_ext":"py","file_size_in_byte":414,"program_lang":"python","lang":"en","doc_type":"code","stars":2,"dataset":"github-code","pt":"15"} +{"seq_id":"18843493145","text":"# -*- coding: utf-8 -*-\r\n\"\"\"\r\nCreated on Thu Nov 7 14:35:59 2019\r\n\r\n@author: amelie\r\n\"\"\"\r\n\r\nimport matplotlib\r\nimport numpy as np\r\nimport matplotlib.pyplot as plt\r\nfrom mpl_toolkits.mplot3d import Axes3D\r\nimport matplotlib.animation as manimation\r\nfrom scipy.integrate import odeint\r\nimport scipy\r\nimport glob\r\nimport pandas as pd\r\n\r\n#%%\r\n#Load the two data bases\r\n\r\np = 30 #number of pedestrian of the scenario\r\n\r\n\r\n######################### GNM/Model Database\r\nfinal_split = []\r\nlast_time_step = 0\r\n\r\npath_of_output = glob.glob(\"outputGNM-\"+str(p)+\"/task5_*/postvis.trajectories\")\r\n\r\nfor path in path_of_output : \r\n file = open(path,'r').read()\r\n split = file.split('\\n')\r\n split = split[1:-1]\r\n \r\n for l in split : \r\n row = l.split(' ')\r\n row = [str(float(row[0])+ last_time_step)] + row[1:]\r\n final_split.append(row)\r\n last_time_step = float(row[0])\r\n \r\nglobal gnm\r\ngnm = pd.DataFrame(final_split, columns = [\"timeStep\",\"Id\",\"x\",\"y\",\"target_id\"] )\r\ngnm = gnm.astype(float)\r\nprint(gnm)\r\n\r\n############################# OSM / Ground Truth Database\r\npath_of_output = glob.glob(\"outputOSM-\"+str(p)+\"/task5_*/postvis.trajectories\")\r\nfinal_split = [] #we keep this value, we use it then in the functions\r\nlast_time_step = 0\r\n\r\nfor path in path_of_output : \r\n file = open(path,'r').read()\r\n split = file.split('\\n')\r\n split = split[1:-1]\r\n \r\n for l in split : \r\n row = l.split(' ')\r\n row = [str(float(row[0])+ last_time_step)] + row[1:]\r\n final_split.append(row)\r\n last_time_step = float(row[0])\r\n \r\nglobal osm\r\nosm = pd.DataFrame(final_split, columns = [\"timeStep\",\"Id\",\"x\",\"y\",\"target_id\"] )\r\nosm = osm.astype(float)\r\nprint(osm)\r\n#%%\r\n\r\ndef f_true(x,dt) :\r\n output = []\r\n global osm\r\n global output_time_out\r\n \r\n \r\n \r\n for i in range(0,x.shape[1],2) : \r\n init_row = osm.loc[ (osm['x'] == x[0][i]) & (osm['y'] == x[0][i+1]) ]\r\n \r\n \r\n if (init_row.empty) : #we look for the value with minimal distance\r\n #at this time step\r\n \r\n possible_values_x = osm.loc[(osm['timeStep'] == dt ) ]['x'].values.tolist()\r\n possible_values_y = osm.loc[(osm['timeStep'] == dt ) ]['y'].values.tolist()\r\n \r\n \r\n if possible_values_x == [] : #no more pedestrians\r\n return output_time_out\r\n \r\n else : \r\n distances = [(x[0][i] - possible_values_x[k])**(2)\r\n +(x[0][i+1] - possible_values_y[k])**(2)\r\n for i in range(len(possible_values_x))]\r\n \r\n \r\n xd = possible_values_x[np.argmin(distances)]\r\n yd = possible_values_y[np.argmin(distances)]\r\n init_row = osm.loc[ (osm['x'] == xd) & (osm['y'] == yd) ]\r\n \r\n \r\n #pedestrian id of interest\r\n p_id = init_row['Id'].values[0]\r\n \r\n next_row = osm.loc[(osm['Id'] == p_id)& (osm['timeStep'] == dt ) ]\r\n \r\n #if a pedestrian is on target, we keep the same location\r\n dt1 = dt\r\n if (next_row.empty) : \r\n dt1 -= 1\r\n row_to_be_pasted = osm.loc[(osm['Id'] == p_id)& (osm['timeStep'] == dt1 ) ]\r\n idex = osm.index.get_loc(row_to_be_pasted.iloc[0].name)\r\n for i in range(dt,NT) : \r\n row_to_be_pasted.at[idex,'timeStep'] = i\r\n osm = osm.append(row_to_be_pasted)\r\n \r\n next_row = osm.loc[(osm['Id'] == p_id)& (osm['timeStep'] == dt ) ]\r\n \r\n xc1 = next_row['x'].values.tolist()\r\n xc2 = next_row['y'].values.tolist()\r\n \r\n output.append(xc1[0])\r\n output.append(xc2[0])\r\n output_time_out = output\r\n \r\n return np.array(output)\r\n\r\n\r\n\r\ndef f_model(x,dt,b) :\r\n global gnm\r\n output = []\r\n\r\n \r\n \r\n for i in range(0,x.shape[1],2) :\r\n \r\n init_row = gnm.loc[ (gnm['x'] == x[0][i]) & (gnm['y'] == x[0][i+1]) ]\r\n #pedestrian id of interest\r\n \r\n \r\n \r\n if (init_row.empty) : #we look for the value with minimal distance\r\n #at this time step\r\n possible_values_x = gnm.loc[(gnm['timeStep'] == dt ) ]['x'].values.tolist()\r\n possible_values_y = gnm.loc[(gnm['timeStep'] == dt ) ]['y'].values.tolist()\r\n distances = [(x[0][i] - possible_values_x[k])**(2)\r\n +(x[0][i+1] - possible_values_y[k])**(2)\r\n for i in range(len(possible_values_x))]\r\n \r\n xd = possible_values_x[np.argmin(distances)]\r\n yd = possible_values_y[np.argmin(distances)]\r\n init_row = gnm.loc[ (gnm['x'] == xd) & (gnm['y'] == yd) ]\r\n \r\n \r\n \r\n p_id = init_row['Id'].values[0]\r\n next_row = gnm.loc[(gnm['Id'] == p_id)& (gnm['timeStep'] == dt ) ]\r\n \r\n \r\n dt1 = dt\r\n if (next_row.empty) : \r\n\r\n dt1 -= 1\r\n row_to_be_pasted = gnm.loc[(gnm['Id'] == p_id)& (gnm['timeStep'] == dt1 ) ]\r\n idex = gnm.index.get_loc(row_to_be_pasted.iloc[0].name)\r\n for i in range(dt,NT) : \r\n row_to_be_pasted.at[idex,'timeStep'] = i\r\n gnm = gnm.append(row_to_be_pasted)\r\n next_row = gnm.loc[(gnm['Id'] == p_id)& (gnm['timeStep'] == dt ) ]\r\n \r\n \r\n \r\n xc1 = next_row['x'].values.tolist()\r\n xc2 = next_row['y'].values.tolist()\r\n \r\n output.append(xc1[0])\r\n output.append(xc2[0])\r\n \r\n \r\n \r\n return np.array(output)\r\n#%%\r\ndef normal_draw(cov):\r\n \"\"\" draw an n-dimensional point from a Gaussian distribution with given covariance. \"\"\"\r\n return np.random.multivariate_normal(cov[:,0],cov,1)\r\n\r\n\r\n \r\n# compute ensemble Kalman smoothing\r\ndef algorithm1_enks(z_data, error_covariance_M, error_covariance_Q):\r\n t = z_data.shape[0]\r\n print(z_data.shape)\r\n ML = (error_covariance_M)\r\n QL = (error_covariance_Q)\r\n \r\n# initialize the initial guess for the model state with random numbers\r\n# normally, one would probably have a better guess\r\n xk = z_data.copy()\r\n for k in range(1,t):\r\n print('k' + str(k))\r\n zk = np.zeros((z_data.shape[1],))\r\n for i in range(m):\r\n print('i' + str(i))\r\n mkm1 = normal_draw(ML)\r\n xk[k,(i*nd):((i+1)*nd)] = f_model(xk[k-1,(i*nd):((i+1)*nd)].reshape(1,-1),k,0.1) +mkm1 \r\n qk = normal_draw(QL)\r\n zk[(i*nd):((i+1)*nd)] = f_true(xk[k,(i*nd):((i+1)*nd)].reshape(1,-1),k) + qk\r\n \r\n zkhat = 1/m*np.sum([zk[i::nd] for i in range(nd)],axis=1)\r\n zdiff = np.row_stack([(zk[(i*nd):((i+1)*nd)]-zkhat) for i in range(m)])\r\n Zk = np.cov(zdiff.T)\r\n \r\n for j in range(1,k+1):\r\n xjbar = np.array(1/m*np.sum([xk[j,i::nd] for i in range(nd)],axis=1))\r\n xdiff = np.row_stack([(xk[j,(i*nd):((i+1)*nd)]-xjbar) for i in range(m)])\r\n zdiff = np.row_stack([(zk[(i*nd):((i+1)*nd)]-zkhat) for i in range(m)])\r\n sigmaj = 1/(m-1) * (xdiff.T @ zdiff)\r\n matk = sigmaj @ np.linalg.pinv(Zk,rcond=1e-10)\r\n \r\n for i in range(m):\r\n xk[j,(i*nd):((i+1)*nd)] = xk[j,(i*nd):((i+1)*nd)] + matk @(z_data[k,(i*nd):((i+1)*nd)]-zk[(i*nd):((i+1)*nd)])\r\n return xk\r\n\r\n\r\n\r\ndef max_likelihood(xk):\r\n t = xk.shape[0]\r\n data = []\r\n for k in range(1, t-1):\r\n for i in range(m):\r\n fhat = f_model(xk[k,(i*nd):((i+1)*nd)].reshape(1,-1),k,0.1)\r\n xhat = xk[k+1,(i*nd):((i+1)*nd)]\r\n data.append((xhat-fhat))\r\n \r\n \r\n data = np.row_stack(np.array(data))\r\n\r\n# note that we do not compute it \"per agent\", as in the paper guy-2019b,\r\n# but for all coordinates of the state (we only consider one \"agent\" in this code)\r\n return np.cov(data.T)\r\n\r\n\r\n\r\n\r\ndef entropy(M):\r\n return 1/2 * n * np.log((2*np.pi*np.exp(1))**d * np.linalg.det(M))\r\n\r\n#%%\r\n\r\nrandom_seed = 1 # used throughout the example\r\n\r\nnp.random.seed(random_seed)\r\n\r\n# Number of time steps for the given simulation\r\nNT = 70\r\n# Physical time that passes in the given number of time steps\r\nT = 5\r\ndt = T / NT\r\ntime = np.linspace(0,T,NT)\r\n\r\n\r\n#model_error = 1e-0 # very noisy, entropy > 0\r\nmodel_error = 1e-1 # very smooth, entropy < 0\r\n\r\n# Initial state of the true and simulated data\r\nx_gnm = gnm.loc[gnm['timeStep'] == 1]['x'].values.tolist()\r\ny_gnm = gnm.loc[gnm['timeStep'] == 1]['y'].values.tolist()\r\n\r\nx_osm = osm.loc[osm['timeStep'] == 1]['x'].values.tolist()\r\ny_osm = osm.loc[osm['timeStep'] == 1]['y'].values.tolist()\r\n\r\n# this is the error in the true model, and also in the observations. You do not\r\n# need to change this.\r\n\r\ntrue_error = 1e-4\r\nm = 10 # ensemble runs\r\nn = len(x_gnm) # number of agents. Note that the models f_true and f_model only work for n=1.\r\nd = 2 # dimension per \"agent\" (we only have one here)\r\nnd = n*d # total state dimension\r\nxt = np.zeros((NT, (nd*m)))\r\nx0_gnm = []\r\nx0_osm = []\r\nfor i in range(n) :\r\n x0_gnm.append(x_gnm[i])\r\n x0_gnm.append(y_gnm[i])\r\n \r\n x0_osm.append(x_osm[i])\r\n x0_osm.append(y_osm[i])\r\n\r\n\r\nx0_gnm = np.array(x0_gnm+x0_gnm+x0_gnm+x0_gnm+x0_gnm\r\n +x0_gnm+x0_gnm+ x0_gnm + x0_gnm+x0_gnm)\r\n\r\n\r\n\r\n\r\n# initialize the ensembles with randomly perturbed states\r\n# in this example, this is not necessary because the model itself introduces errors\r\n\r\nxt[0,:m*nd] = np.column_stack(x0_gnm) #let's use the mathematical model first\r\n#state as initialisation\r\nxm = xt.copy()\r\n\r\n\r\n# this is the initial guess for the entropy matrix. can be pretty arbitrary\r\nM = np.identity(nd) \r\n# this is the guess for the true error in the observations. should be small here.\r\nQ = np.identity(nd) * true_error**2\r\n\r\nN_ITER = 4 # number of iterations of algorithm1_enks and max_likelihood\r\nMhat = M\r\nentropy_list =[]\r\nzk = np.zeros(np.shape(xt))\r\nzk[0,:] = f_true(xt[1:,:],1).reshape(1,-1)\r\nxm_hat = 0\r\nxm_hat_prev = 0\r\nfor k in range(N_ITER):\r\n \r\n print(k)\r\n xm_hat = algorithm1_enks(zk, Mhat, Q);\r\n print(xm_hat)\r\n Mhat = max_likelihood(xm_hat)\r\n print('current det(M)', np.linalg.det(Mhat))\r\n print('error change ', np.linalg.norm(xm_hat - xm_hat_prev))\r\n xm_hat_prev = xm_hat\r\n \r\n entropy_list.append(entropy(Mhat))\r\n\r\n\r\n#%%\r\nprint('entropy(M estimated) ', entropy(Mhat))\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n","repo_name":"Cyberlilie/EX1_practikum_crowd_modelling","sub_path":"Exercise 2/task5/Entropy_computation.py","file_name":"Entropy_computation.py","file_ext":"py","file_size_in_byte":10475,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"15"} +{"seq_id":"39306177980","text":"import pytest\nimport os\n\nfrom gumo.datastore.infrastructure.configuration import DatastoreConfiguration\n\nfrom google.cloud import datastore\nimport google.auth.exceptions\n\n\nclass TestDatastoreConfiguration:\n def setup_method(self, method):\n self.env_vars = {}\n for k, v in os.environ.items():\n self.env_vars[k] = v\n\n def teardown_method(self, method):\n for k in os.environ.keys():\n if k not in self.env_vars:\n del os.environ[k]\n\n for k, v in self.env_vars.items():\n os.environ[k] = v\n\n def test_build_success_with_standard_configuration(self):\n if 'DATASTORE_EMULATOR_HOST' in os.environ:\n del os.environ['DATASTORE_EMULATOR_HOST']\n assert os.environ['GOOGLE_CLOUD_PROJECT'] is not None\n assert 'DATASTORE_EMULATOR_HOST' not in os.environ\n\n try:\n o = DatastoreConfiguration()\n\n assert o.google_cloud_project.value == os.environ['GOOGLE_CLOUD_PROJECT']\n assert not o.use_local_emulator\n assert o.emulator_host is None\n assert o.namespace is None\n assert isinstance(o.client, datastore.Client)\n except google.auth.exceptions.DefaultCredentialsError as e:\n # Depending on the environment, it is correct behavior for this test to fail.\n assert 'Could not automatically determine credentials.' in str(e)\n\n def test_build_success_with_emulator_configuration(self):\n assert os.environ['GOOGLE_CLOUD_PROJECT'] is not None\n assert os.environ['DATASTORE_EMULATOR_HOST'] is not None\n\n o = DatastoreConfiguration()\n\n assert o.google_cloud_project.value == os.environ['GOOGLE_CLOUD_PROJECT']\n assert o.use_local_emulator\n assert o.emulator_host == os.environ['DATASTORE_EMULATOR_HOST']\n assert o.namespace is None\n assert isinstance(o.client, datastore.Client)\n\n def test_build_failure_without_google_cloud_project_env_vars(self):\n if 'GOOGLE_CLOUD_PROJECT' in os.environ:\n del os.environ['GOOGLE_CLOUD_PROJECT']\n\n with pytest.raises(RuntimeError, match='\"GOOGLE_CLOUD_PROJECT\" is undefined'):\n DatastoreConfiguration()\n\n def test_build_failure_with_emulator_configuration_and_without_emulator_env_vars(self):\n if 'DATASTORE_EMULATOR_HOST' in os.environ:\n del os.environ['DATASTORE_EMULATOR_HOST']\n assert os.environ['GOOGLE_CLOUD_PROJECT'] is not None\n assert 'DATASTORE_EMULATOR_HOST' not in os.environ\n\n with pytest.raises(RuntimeError, match='env-var \"DATASTORE_EMULATOR_HOST\" must be present'):\n DatastoreConfiguration(\n use_local_emulator=True\n )\n\n def test_build_failure_with_emulator_host_mismatched(self):\n assert os.environ['GOOGLE_CLOUD_PROJECT'] is not None\n assert os.environ['DATASTORE_EMULATOR_HOST'] is not None\n\n with pytest.raises(RuntimeError,\n match='Env-var \"DATASTORE_EMULATOR_HOST\" and self.emulator_host do not match.'):\n DatastoreConfiguration(\n use_local_emulator=True,\n emulator_host='example.localhost:12345'\n )\n","repo_name":"gumo-py/gumo-datastore","sub_path":"tests/datastore/configure_test.py","file_name":"configure_test.py","file_ext":"py","file_size_in_byte":3224,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"15"} +{"seq_id":"10763930291","text":"import os \r\n \r\n \r\n# File path to be opened \r\npath = 'save.txt'\r\n \r\n# Mode to be set \r\nmode = 0o666\r\n \r\n# flags \r\nflags = os.O_RDWR | os.O_CREAT \r\n \r\n \r\n# Open the specified file path \r\n# using os.open() method \r\n# and get the file descriptor for \r\n# opened file path \r\nfd = os.open(path, flags, mode) \r\n \r\nprint(\"File path opened successfully.\") \r\n \r\n \r\n# Write a string to the file \r\n# using file descriptor \r\nstr = \"GeeksforGeeks: A computer science portal for geeks.\"\r\nos.write(fd, str.encode()) \r\nprint(\"String written to the file descriptor.\") \r\n \r\n \r\n# Now read the file \r\n# from beginning \r\nos.lseek(fd, 0, 0) \r\nstr = os.read(fd, os.path.getsize(fd)) \r\nprint(\"\\nString read from the file descriptor:\") \r\nprint(str.decode()) \r\n \r\n# Close the file descriptor \r\nos.close(fd) \r\nprint(\"\\nFile descriptor closed successfully.\") ","repo_name":"badrishb/Movie-genre-predictor-application","sub_path":"test.py","file_name":"test.py","file_ext":"py","file_size_in_byte":845,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"15"} +{"seq_id":"1819147672","text":"from vtk import *\nimport vtk\nimport random as rd\nimport time\nimport numpy as np\nimport functools\n\n\n# 数据生成,输入为箱子种类数,箱子最大长、最小长、最大宽、最小宽、商品个数、商品最大长、最小长、最大宽、最小宽\n# 输出为生成的箱子列表和商品列表\nfrom vtkmodules.vtkCommonTransforms import vtkTransform\nfrom vtkmodules.vtkFiltersGeneral import vtkTransformPolyDataFilter\nfrom vtkmodules.vtkRenderingCore import vtkPolyDataMapper, vtkActor, vtkWindowToImageFilter\n\n\ndef data_generate_3d(nums_box, max_edge_box, min_edge_box, nums_good, max_edge_good, min_edge_good):\n # 随机生成箱子\n boxs = []\n for i in range(nums_box):\n boxs.append([int((max_edge_box - min_edge_box) * rd.random() + min_edge_box),\n int((max_edge_box - min_edge_box) * rd.random() + min_edge_box),\n int((max_edge_box - min_edge_box) * rd.random() + min_edge_box)])\n\n # 随机生成商品\n goods = []\n for i in range(nums_good):\n goods.append([int((max_edge_good - min_edge_good) * rd.random() + min_edge_good),\n int((max_edge_good - min_edge_good) * rd.random() + min_edge_good),\n int((max_edge_good - min_edge_good) * rd.random() + min_edge_good)])\n\n return boxs, goods\n\n\n# 二维商品排序用\ndef cmp_2d(x, y):\n if x[0] < y[0]:\n return -1\n elif x[0] > y[0]:\n return 1\n elif x[1] < y[1]:\n return -1\n elif x[1] > y[1]:\n return 1\n else:\n return 0\n\n\n# 三维商品排序用\ndef cmp_3d(x, y):\n if x[0] < y[0]:\n return -1\n elif x[0] > y[0]:\n return 1\n elif x[1] < y[1]:\n return -1\n elif x[1] > y[1]:\n return 1\n elif x[2] < y[2]:\n return -1\n elif x[2] > y[2]:\n return 1\n else:\n return 0\n\n\ndef data_pre(boxs, goods):\n # 箱子长边作长,放前面\n for i in range(len(boxs)):\n boxs[i] = sorted(boxs[i], reverse=True)\n\n # 箱子排序,大的放前面\n boxs = sorted(boxs, key=functools.cmp_to_key(cmp_3d), reverse=True)\n\n # 箱子种类去重\n i = 0\n while i < len(boxs) - 1:\n j = i + 1\n while j < len(boxs):\n if boxs[i][0] == boxs[j][0] and boxs[i][1] == boxs[j][1] and boxs[i][2] == boxs[j][2]:\n del boxs[j]\n else:\n j += 1\n i += 1\n\n # 商品长边作长,放前面\n for i in range(len(goods)):\n goods[i] = sorted(goods[i], reverse=True)\n\n # 商品排序,大的放前面\n goods = sorted(goods, key=functools.cmp_to_key(cmp_3d), reverse=True)\n\n return boxs, goods\n\n\n# 检验是否每个商品都能有一个箱子放下它\ndef check_3d(boxs, goods):\n for good in goods:\n can_put = False\n for box in boxs:\n if good[0] <= box[0] and good[1] <= box[1] and good[2] <= box[2]:\n can_put = True\n break\n if not can_put:\n print(good, \"太大,无合适箱子\")\n return False\n return True\n\n\ndef can_put_3d(l, w, h, goods):\n L = max(l, w, h)\n H = min(l, w, h)\n W = l + w + h - L - H\n\n for good in goods:\n lg = max(good[0], good[1], good[2])\n hg = min(good[0], good[1], good[2])\n wg = good[0] + good[1] + good[2] - lg - hg\n if lg > L or wg > W or hg > H:\n return False\n return True\n\n\n# 先以w为���制码垛,再以l为限制码垛\n# 输入为长、宽、商品集,输出为箱子个数\ndef packing_simple(l, w, h, goods):\n # 先检查是否每一个商品在此规则下都能放下\n if not can_put_3d(l, w, h, goods):\n return -1\n\n # 以h为限制码垛成条,商品排序,大的放前面\n goods1 = []\n for good in goods:\n if good[0] <= l and good[1] <= w and good[2] <= h:\n goods1.append([good[0], good[1], good[2]])\n elif good[0] <= l and good[2] <= w and good[1] <= h:\n goods1.append([good[0], good[2], good[1]])\n elif good[1] <= l and good[0] <= w and good[2] <= h:\n goods1.append([good[1], good[0], good[2]])\n elif good[1] <= l and good[2] <= w and good[0] <= h:\n goods1.append([good[1], good[2], good[0]])\n elif good[2] <= l and good[0] <= w and good[1] <= h:\n goods1.append([good[2], good[0], good[1]])\n else:\n goods1.append([good[2], good[1], good[0]])\n\n goods1 = sorted(goods1, key=functools.cmp_to_key(cmp_3d), reverse=True)\n\n strips = []\n goods1_used = [0 for i in range(len(goods1))]\n\n while sum(goods1_used) < len(goods1_used):\n l_used = 0\n w_used = 0\n h_used = 0\n for i in range(len(goods1_used)):\n if goods1_used[i] == 0 and h_used + goods1[i][2] <= h:\n l_used = max(l_used, goods1[i][0])\n w_used = max(w_used, goods1[i][1])\n h_used += goods1[i][2]\n goods1_used[i] = 1\n strips.append([l_used, w_used])\n\n strips = sorted(strips, key=functools.cmp_to_key(cmp_2d), reverse=True)\n\n # 以w为限制码垛成层\n levels = []\n strip_used = [0 for i in range(len(strips))]\n\n while sum(strip_used) < len(strip_used):\n l_used = 0\n w_used = 0\n for i in range(len(strips)):\n if strip_used[i] == 0 and w_used + strips[i][1] <= w:\n l_used = max(l_used, strips[i][0])\n w_used += strips[i][1]\n strip_used[i] = 1\n levels.append(l_used)\n\n # 再以l为限制码垛\n levels = sorted(levels, reverse=True)\n L_box_unused = [l]\n\n for level in levels:\n flag = -1\n for i in range(len(L_box_unused)):\n if L_box_unused[i] >= level:\n if flag == -1:\n flag = i\n elif L_box_unused[i] < L_box_unused[flag]:\n flag = i\n if flag == -1:\n L_box_unused.append(l - level)\n else:\n L_box_unused[flag] -= level\n\n return len(L_box_unused)\n\n\n# 选择合适的主箱子\ndef box_choose_3d(boxs, nums_simplePacking_1, nums_simplePacking_2, nums_simplePacking_3, nums_simplePacking_4,\n nums_simplePacking_5, nums_simplePacking_6):\n l = -1\n w = -1\n h = -1\n nums = -1\n for i in range(len(boxs)):\n if nums_simplePacking_1[i] != -1:\n if nums == -1 or (nums != -1 and nums > nums_simplePacking_1[i]) or (\n nums != -1 and nums == nums_simplePacking_1[i] and l * w * h > boxs[i][0] * boxs[i][1] * boxs[i][\n 2]):\n l = boxs[i][0]\n w = boxs[i][1]\n h = boxs[i][2]\n nums = nums_simplePacking_1[i]\n if nums_simplePacking_2[i] != -1:\n if nums == -1 or (nums != -1 and nums > nums_simplePacking_2[i]) or (\n nums != -1 and nums == nums_simplePacking_2[i] and l * w * h > boxs[i][0] * boxs[i][1] * boxs[i][\n 2]):\n l = boxs[i][0]\n w = boxs[i][2]\n h = boxs[i][1]\n nums = nums_simplePacking_2[i]\n if nums_simplePacking_3[i] != -1:\n if nums == -1 or (nums != -1 and nums > nums_simplePacking_3[i]) or (\n nums != -1 and nums == nums_simplePacking_3[i] and l * w * h > boxs[i][0] * boxs[i][1] * boxs[i][\n 2]):\n l = boxs[i][1]\n w = boxs[i][0]\n h = boxs[i][2]\n nums = nums_simplePacking_3[i]\n if nums_simplePacking_4[i] != -1:\n if nums == -1 or (nums != -1 and nums > nums_simplePacking_4[i]) or (\n nums != -1 and nums == nums_simplePacking_4[i] and l * w * h > boxs[i][0] * boxs[i][1] * boxs[i][\n 2]):\n l = boxs[i][1]\n w = boxs[i][2]\n h = boxs[i][0]\n nums = nums_simplePacking_4[i]\n if nums_simplePacking_5[i] != -1:\n if nums == -1 or (nums != -1 and nums > nums_simplePacking_5[i]) or (\n nums != -1 and nums == nums_simplePacking_5[i] and l * w * h > boxs[i][0] * boxs[i][1] * boxs[i][\n 2]):\n l = boxs[i][2]\n w = boxs[i][0]\n h = boxs[i][1]\n nums = nums_simplePacking_5[i]\n if nums_simplePacking_6[i] != -1:\n if nums == -1 or (nums != -1 and nums > nums_simplePacking_6[i]) or (\n nums != -1 and nums == nums_simplePacking_6[i] and l * w * h > boxs[i][0] * boxs[i][1] * boxs[i][\n 2]):\n l = boxs[i][2]\n w = boxs[i][1]\n h = boxs[i][0]\n nums = nums_simplePacking_6[i]\n return l, w, h\n\n\ndef packing_3d(l, w, h, goods):\n # 先检查是否每一个商品在此规则下都能放下\n if not can_put_3d(l, w, h, goods):\n return -1\n\n # 以h为限制码垛成条,商品排序,大的放前面\n goods1 = []\n for good in goods:\n if good[0] <= l and good[1] <= w and good[2] <= h:\n goods1.append([good[0], good[1], good[2]])\n elif good[0] <= l and good[2] <= w and good[1] <= h:\n goods1.append([good[0], good[2], good[1]])\n elif good[1] <= l and good[0] <= w and good[2] <= h:\n goods1.append([good[1], good[0], good[2]])\n elif good[1] <= l and good[2] <= w and good[0] <= h:\n goods1.append([good[1], good[2], good[0]])\n elif good[2] <= l and good[0] <= w and good[1] <= h:\n goods1.append([good[2], good[0], good[1]])\n else:\n goods1.append([good[2], good[1], good[0]])\n\n goods1 = sorted(goods1, key=functools.cmp_to_key(cmp_3d), reverse=True)\n\n strips = []\n strips_goods = []\n goods1_used = [0 for i in range(len(goods1))]\n\n while sum(goods1_used) < len(goods1_used):\n l_used = 0\n w_used = 0\n h_used = 0\n strip_goods = []\n for i in range(len(goods1_used)):\n if goods1_used[i] == 0 and h_used + goods1[i][2] <= h:\n l_used = max(l_used, goods1[i][0])\n w_used = max(w_used, goods1[i][1])\n strip_goods.append([goods1[i][0], goods1[i][1], goods1[i][2], 0, 0, h_used])\n h_used += goods1[i][2]\n goods1_used[i] = 1\n strips.append([l_used, w_used])\n strips_goods.append(strip_goods)\n\n # 以w为限制码垛成层\n for i in range(len(strips) - 1):\n for j in range(i + 1, len(strips)):\n if strips[i][0] < strips[j][0] or (strips[i][0] == strips[j][0] and strips[i][1] < strips[j][1]):\n temp = strips[i]\n strips[i] = strips[j]\n strips[j] = temp\n temp1 = strips_goods[i]\n strips_goods[i] = strips_goods[j]\n strips_goods[j] = temp1\n\n levels = []\n levels_goods = []\n strip_used = [0 for i in range(len(strips))]\n\n while sum(strip_used) < len(strip_used):\n l_used = 0\n w_used = 0\n level_goods = []\n for i in range(len(strips)):\n if strip_used[i] == 0 and w_used + strips[i][1] <= w:\n l_used = max(l_used, strips[i][0])\n for g in strips_goods[i]:\n level_goods.append([g[0], g[1], g[2], 0, w_used, g[5]])\n w_used += strips[i][1]\n strip_used[i] = 1\n levels.append(l_used)\n levels_goods.append(level_goods)\n\n # 再以l为限制码垛\n for i in range(len(levels) - 1):\n for j in range(i + 1, len(levels)):\n if levels[i] < levels[j]:\n temp = levels[i]\n levels[i] = levels[j]\n levels[j] = temp\n temp1 = levels_goods[i]\n levels_goods[i] = levels_goods[j]\n levels_goods[j] = temp1\n\n L_box_unused = [l]\n L_goods = []\n L_coordinates = []\n\n L_goods.append([])\n L_coordinates.append([])\n\n for i in range(len(levels)):\n flag = -1\n for j in range(len(L_box_unused)):\n if L_box_unused[j] >= levels[j]:\n if flag == -1 or (flag != -1 and L_box_unused[j] < L_box_unused[flag]):\n flag = j\n if flag == -1:\n L_box_unused.append(l - levels[i])\n L_goods.append([levels_goods[i][j][:3] for j in range(len(levels_goods[i]))])\n L_coordinates.append([levels_goods[i]])\n else:\n L_box_unused[flag] -= levels[i]\n L_goods[flag] += [levels_goods[i][j][:3] for j in range(len(levels_goods[i]))]\n if len(L_coordinates[flag]) == 0:\n L_coordinates[flag] += [levels_goods[i]]\n else:\n L_coordinates[flag] += [[[levels_goods[i][j][0], levels_goods[i][j][1], levels_goods[i][j][2],\n L_coordinates[flag][-1][0][0] + L_coordinates[flag][-1][0][3],\n levels_goods[i][j][4], levels_goods[i][j][5]] for j in\n range(len(levels_goods[i]))]]\n\n L_coordinates_merge = []\n\n for i in range(len(L_coordinates)):\n L_coordinates_i = []\n for j in range(len(L_coordinates[i])):\n L_coordinates_i += L_coordinates[i][j]\n L_coordinates_merge.append(L_coordinates_i)\n\n L_box = [[l, w, h] for i in range(len(L_box_unused))]\n\n return L_box, L_goods, L_coordinates_merge\n\n\n# 正交二叉树启发式,试每一种箱子装下所有的商品需要的个数,取最少的,再去缩减最后一个箱子\ndef OBT_3d(boxs, goods):\n # 分别以长宽作为限制,依次码垛成层\n nums_simplePacking_1 = []\n nums_simplePacking_2 = []\n nums_simplePacking_3 = []\n nums_simplePacking_4 = []\n nums_simplePacking_5 = []\n nums_simplePacking_6 = []\n\n for box in boxs:\n nums_simplePacking_1.append(packing_simple(box[0], box[1], box[2], goods))\n nums_simplePacking_2.append(packing_simple(box[0], box[2], box[1], goods))\n nums_simplePacking_3.append(packing_simple(box[1], box[0], box[2], goods))\n nums_simplePacking_4.append(packing_simple(box[1], box[2], box[0], goods))\n nums_simplePacking_5.append(packing_simple(box[2], box[0], box[1], goods))\n nums_simplePacking_6.append(packing_simple(box[2], box[1], box[0], goods))\n\n # 找箱子数最少的箱子\n l, w, h = box_choose_3d(boxs, nums_simplePacking_1, nums_simplePacking_2, nums_simplePacking_3,\n nums_simplePacking_4, nums_simplePacking_5, nums_simplePacking_6)\n\n # 装载\n L_box, L_goods, L_coordinates = packing_3d(l, w, h, goods)\n\n return L_box, L_goods, L_coordinates\n\n\n# 检验结果中的商品集是否和原始的商品集一致\ndef goods_check(goods, L_goods):\n nums = 0\n for gs in L_goods:\n nums += len(gs)\n\n if len(goods) == nums:\n return True\n\n return False\n\n\n# 添加商品图形\ndef Addcube_3d(ren, coordinate, edge_max, x_re, y_re, z_re):\n cube = vtk.vtkCubeSource()\n cube.SetXLength(coordinate[0] / edge_max)\n cube.SetYLength(coordinate[1] / edge_max)\n cube.SetZLength(coordinate[2] / edge_max)\n cube.Update()\n\n translation = vtkTransform()\n translation.Translate((coordinate[3] + coordinate[0] / 2.0) / edge_max + x_re,\n (coordinate[4] + coordinate[1] / 2.0) / edge_max + y_re,\n (coordinate[5] + coordinate[2] / 2.0) / edge_max + z_re)\n transformFilter = vtkTransformPolyDataFilter()\n transformFilter.SetInputConnection(cube.GetOutputPort())\n transformFilter.SetTransform(translation)\n transformFilter.Update()\n\n transformedMapper = vtkPolyDataMapper()\n transformedMapper.SetInputConnection(transformFilter.GetOutputPort())\n transformedActor = vtkActor()\n transformedActor.SetMapper(transformedMapper)\n transformedActor.GetProperty().SetColor((rd.uniform(0, 1), rd.uniform(0, 1), rd.uniform(0, 1)))\n\n ren.AddActor(transformedActor)\n\n\ndef png_save(renWin, name):\n windowToImageFilter = vtkWindowToImageFilter()\n windowToImageFilter.SetInput(renWin)\n windowToImageFilter.Update()\n writer = vtk.vtkPNGWriter()\n writer.SetFileName(name)\n writer.SetInputConnection(windowToImageFilter.GetOutputPort())\n writer.Write()\n\n\n# 三维展示,输入为箱子集和商品集,包裹的箱子和商品集一一对应\ndef show_3d(L_box, L_coordinates):\n # nums = len(L_box)\n edge_max = max([max(L_box)])\n\n # 预设参数\n CL_p = 1.1\n CW_p = 1\n CH_p = 0.01\n gap = 0.25\n\n x_re = -0.5\n y_re = -0.5\n z_re = -0.5\n\n # 渲染及渲染窗口,并根据捕捉的鼠标事件执行相应的操作\n ren = vtk.vtkRenderer()\n renWin = vtk.vtkRenderWindow()\n renWin.AddRenderer(ren)\n renWin.SetSize(1200, 600)\n iren = vtk.vtkRenderWindowInteractor()\n iren.SetRenderWindow(renWin)\n\n \"\"\"画容器\"\"\"\n cube = vtk.vtkCubeSource()\n cube.SetXLength(L_box[0] / edge_max)\n cube.SetYLength(L_box[1] / edge_max)\n cube.SetZLength(L_box[2] / edge_max)\n cube.Update()\n\n translation = vtkTransform()\n translation.Translate(L_box[0] / edge_max / 2.0 + x_re, L_box[1] / edge_max / 2.0 + y_re,\n L_box[2] / edge_max / 2.0 + z_re)\n transformFilter = vtkTransformPolyDataFilter()\n transformFilter.SetInputConnection(cube.GetOutputPort())\n transformFilter.SetTransform(translation)\n transformFilter.Update()\n\n transformedMapper = vtkPolyDataMapper()\n transformedMapper.SetInputConnection(transformFilter.GetOutputPort())\n transformedActor = vtkActor()\n transformedActor.SetMapper(transformedMapper)\n transformedActor.GetProperty().SetColor((1, 1, 1))\n transformedActor.GetProperty().SetRepresentationToWireframe()\n\n ren.AddActor(transformedActor)\n\n \"\"\"画托盘\"\"\"\n cube = vtk.vtkCubeSource()\n cube.SetXLength(CL_p)\n cube.SetYLength(CW_p)\n cube.SetZLength(CH_p)\n cube.Update()\n\n translation = vtkTransform()\n translation.Translate(CL_p / 2.0 + x_re, CW_p / 2.0 + y_re, -CH_p / 2.0 + z_re)\n transformFilter = vtkTransformPolyDataFilter()\n transformFilter.SetInputConnection(cube.GetOutputPort())\n transformFilter.SetTransform(translation)\n transformFilter.Update()\n\n transformedMapper = vtkPolyDataMapper()\n transformedMapper.SetInputConnection(transformFilter.GetOutputPort())\n transformedActor = vtkActor()\n transformedActor.SetMapper(transformedMapper)\n transformedActor.GetProperty().SetColor((0.2, 0.4, 0.8))\n\n ren.AddActor(transformedActor)\n\n for i in range(len(L_coordinates)):\n Addcube_3d(ren, L_coordinates[i], edge_max, x_re, y_re, z_re)\n\n camera = vtk.vtkCamera()\n camera.SetPosition(5, -0.5, 2)\n camera.SetViewUp(0, 0, 1)\n ren.SetActiveCamera(camera)\n\n iren.Initialize()\n renWin.Render()\n # 保存过程\n png_save(renWin, \"result_D3.png\")\n # 展示\n iren.Start()\n\n\nif __name__ == \"__main__\":\n #生成箱子集和商品集,计算并展示\n boxs,goods = data_generate_3d(nums_box = 2, max_edge_box = 20, min_edge_box = 10, nums_good = 10, max_edge_good = 10, min_edge_good = 1)\n L_box, L_goods, L_coordinates = OBT_3d(boxs, goods)\n print(L_box, L_coordinates)\n show_3d(L_box, L_coordinates)\n\n","repo_name":"foretmer/Algorithm-Lin","sub_path":"2022202210146王海宁+2022202210115罗伊文/3D-online-packing/draw_3d.py","file_name":"draw_3d.py","file_ext":"py","file_size_in_byte":19334,"program_lang":"python","lang":"en","doc_type":"code","stars":8,"dataset":"github-code","pt":"15"} +{"seq_id":"9336347201","text":"import socket, time, random\n\nconfigList = open(\"config.txt\").read().splitlines()\n\ntheaterIP = configList[1].split(\":\")[1]\ntheaterPort = int(configList[1].split(\":\")[2])\n\nmovieIP = configList[2].split(\":\")[1]\nmoviePort = int(configList[2].split(\":\")[2])\n\ntheaterSocket = socket.socket(socket.AF_INET, socket.SOCK_STREAM)\ntheaterSocket.connect((theaterIP, theaterPort))\n\nmovieSocket = socket.socket(socket.AF_INET, socket.SOCK_STREAM)\nmovieSocket.connect((movieIP, moviePort))\n\nglobal kioskNum\nkioskNum = -1;\nmessage = \"kioskhandshake\"\ntheaterSocket.sendall(message.encode())\nkioskNum = int(theaterSocket.recv(1024).decode())\n\nif kioskNum < 0:\n print(\"Handshake failed\")\n\nwhile True:\n if random.randint(1, 2) == 1:\n serverSocket = theaterSocket\n else:\n serverSocket = movieSocket\n\n ticketType = input(\"Enter ticket type (\\'movie\\' or \\'play\\'), or type \\'quit\\' to exit: \")\n\n if ticketType == \"quit\":\n serverSocket.close()\n break;\n\n elif ticketType != \"movie\" and ticketType != \"play\":\n print(\"Error: incorrect ticket type\")\n continue\n\n else:\n numTickets = input(\"Please enter number of tickets: \")\n\n try:\n int(numTickets)\n except ValueError:\n print(\"Error: Invalid number of tickets\")\n\n else:\n if int(numTickets) < 0:\n print(\"Error: Cannot purchase negative number of tickets\")\n else:\n message = str(kioskNum) + \":\" + ticketType + \":\" + str(numTickets)\n serverSocket.sendall(message.encode())\n receipt = serverSocket.recv(1024).decode()\n origin, succeeded, numTickets = receipt.split(\":\", 2)\n\n if succeeded == \"success\":\n print(\"Purchased \" + numTickets + \" \" + ticketType + \" tickets.\")\n else:\n print(\"Not enough tickets remaining to purchase \" + numTickets + \" tickets.\")","repo_name":"artem-j/CS171-PA1","sub_path":"TicketKiosk.py","file_name":"TicketKiosk.py","file_ext":"py","file_size_in_byte":1950,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"15"} +{"seq_id":"8239709616","text":"import requests\nfrom bs4 import BeautifulSoup\n\ndef ektraksi_data():\n \"\"\"\n Tanggal: 08 Desember 2021\n Waktu: 05:18:33 WIB\n Magnitudo: 3.4\n Kedalaman : 7 km\n Lokasi: 6.71 LS - 107.35 BT\n Pusat Gempa : Pusat gempa berada di darat 18 km Barat Daya Purwakarta\n Dirasakan: Dirasakan (Skala MMI): III Cipeundeuy, III Cirata, III Maniis, II Purwakarta\n \"\"\"\n try:\n content = requests.get('https://bmkg.go.id')\n except Exception:\n return None\n if content.status_code ==200:\n soup = BeautifulSoup(content.text, 'html.parser')\n result = soup.find('span',{'class':'waktu'})\n result = result.text.split(',')\n tanggal = result[0]\n waktu = result[1]\n\n result = soup.find('div', {'class', 'col-md-6 col-xs-6 gempabumi-detail no-padding'})\n result = result.findChildren('li')\n i=0\n magnitudo = None\n kedalaman = None\n ls = None\n bt = None\n lokasi = None\n\n for res in result:\n if i == 1:\n magnitudo= res.text\n elif i == 2:\n kedalaman= res.text\n elif i == 3:\n koordinat = res.text.split(' - ')\n ls = koordinat[0]\n bt = koordinat[1]\n elif i == 4:\n lokasi= res.text\n elif i == 5:\n tsunami = res.text\n\n i = i + 1\n\n hasil = dict()\n hasil['tanggal']= tanggal\n hasil['waktu']= waktu\n hasil['magnitudo']= magnitudo\n hasil['kedalaman']= kedalaman\n hasil['koordinat']= {'ls':ls,'bt':bt}\n hasil['lokasi']= lokasi\n hasil['tsunami']= tsunami\n return hasil\n else:\n return None\n\n\n\ndef tampilkan_data(result):\n print(f'Gempa Terakhir berdasarkan BMKG')\n print(f\"Tanggal {result['tanggal']}\")\n print(f\"Waktu{result['waktu']}\")\n print(f\"Magnitudo {result['magnitudo']}\")\n print(f\"Kedalaman {result['kedalaman']}\")\n print(f\"Koordinat: 'LS'= {result['koordinat']['ls']}, 'BT'={result['koordinat']['bt']}\")\n print(f\"Lokasi : {result['lokasi']}\")\n print(f\"Apakah Berpotensi Tsunami : {result['tsunami']}\")\n","repo_name":"fadilcirebon/deteksi-gempa-terkini","sub_path":"gempa_terkini/__init__.py","file_name":"__init__.py","file_ext":"py","file_size_in_byte":2197,"program_lang":"python","lang":"id","doc_type":"code","stars":0,"dataset":"github-code","pt":"14"} +{"seq_id":"34798690058","text":"from typing import Callable, Dict, Any, Awaitable\n\nfrom aiogram import BaseMiddleware\nfrom aiogram.types import Message, CallbackQuery\nfrom aiomysql import Pool\n\n\nclass DataBaseMiddleWare(BaseMiddleware):\n def __init__(self, pool: Pool):\n self.pool = pool\n\n async def __call__(\n self,\n handler: Callable[[CallbackQuery, Dict[str, Any]], Awaitable[Any]],\n event: Message,\n data: Dict[str, Any]\n ) -> Any:\n data[\"pool\"] = self.pool\n await handler(event, data)\n","repo_name":"BizneSSmen/Dubai_wallet_bot","sub_path":"Middlewares/database_middleware.py","file_name":"database_middleware.py","file_ext":"py","file_size_in_byte":532,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"14"} +{"seq_id":"20292964685","text":"\"\"\"Train the LSTM decoder model.\"\"\"\nimport time\nfrom lstm_decoder import *\nfrom lstm_decoder_repeated_feed_image import *\nfrom lstm_decoder_scratch import *\nfrom lstm_decoder_attention import *\nimport lstm_decoder_config as configuration\nfrom data_loader import DataLoader\nfrom vocabulary import Vocabulary\nimport numpy as np\n\nFLAGS = tf.app.flags.FLAGS\n\ntf.flags.DEFINE_string(\"training_data_loader\", \"\",\n \"Serialized data loader file for training set.\")\ntf.flags.DEFINE_string(\"validation_data_loader\", \"\",\n \"Serialized data loader file for validation set.\")\ntf.flags.DEFINE_string(\"vocab_file\", \"\",\n \"Vocabulary file.\")\ntf.flags.DEFINE_string(\"train_dir\", \"train_dir\",\n \"Directory for saving and loading model checkpoints.\")\ntf.flags.DEFINE_string(\"summary_dir\", \"summary_dir\",\n \"Directory for saving summaries.\")\ntf.flags.DEFINE_integer(\"number_of_steps\", 1000000, \"Number of training steps.\")\ntf.flags.DEFINE_integer(\"log_every_n_steps\", 1,\n \"Frequency at which loss and global step are logged.\")\ntf.flags.DEFINE_string(\"decoder_version\", \"RepeatedFeed\",\n \"SingleFeed/RepeatedFeed/Scratch\")\ntf.flags.DEFINE_integer(\"validation_loss_every_n_steps\", 10,\n \"Frequency at which validation loss is computed for one mini-batch.\")\ntf.logging.set_verbosity(tf.logging.INFO)\n\n\ndef generate_dumb_batch(batch_size, num_segments):\n feature_size = 1024\n sigma = 0.1\n image_features = sigma * np.random.rand(batch_size, num_segments, feature_size)\n input_sequence = np.zeros(shape=(batch_size, const_config.lstm_truncated_length))\n input_mask = np.ones(shape=(batch_size, const_config.lstm_truncated_length), dtype=np.int)\n target_sequence = np.zeros(shape=(batch_size, const_config.lstm_truncated_length))\n return image_features, input_sequence, input_mask, target_sequence\n\n\ndef main(args):\n assert FLAGS.training_data_loader, \"--training_data_loader is required\"\n assert FLAGS.vocab_file, \"--vocab_file is required\"\n assert FLAGS.train_dir, \"--train_dir is required\"\n\n model_config = configuration.ModelConfig()\n training_config = configuration.TrainingConfig()\n\n print('Loading vocabulary file...')\n vocab = Vocabulary(FLAGS.vocab_file)\n vocab_size = vocab.get_vocabulary_size()\n\n # Assign parameters to model configuration.\n model_config.vocab_size = vocab_size\n training_config.train_dir = FLAGS.train_dir\n training_config.num_iterations = FLAGS.number_of_steps\n training_config.log_every_n_steps = FLAGS.log_every_n_steps\n training_config.validation_loss_every_n_steps = FLAGS.validation_loss_every_n_steps\n\n # Create training directory.\n if not tf.gfile.IsDirectory(training_config.train_dir):\n tf.logging.info(\"Creating training directory: %s\", training_config.train_dir)\n tf.gfile.MakeDirs(training_config.train_dir)\n\n # Build the TensorFlow graph.\n g = tf.Graph()\n with g.as_default():\n print('Building LSTM decoder model...')\n if FLAGS.decoder_version == 'SingleFeed':\n model = LSTMDecoder(model_config, mode=\"train\")\n elif FLAGS.decoder_version == 'RepeatedFeed':\n model = LSTMDecoderRepeatedImageFeed(model_config, mode=\"train\")\n elif FLAGS.decoder_version == 'Scratch':\n model = LSTMDecoderScratch(model_config, mode=\"train\")\n else: # FLAGS.decoder_version == 'Attention':\n model = LSTMDecoderAttention(model_config, mode=\"train\")\n model.build()\n\n # Setup learning rate decay.\n num_batches_per_epoch = (training_config.num_examples_per_epoch /\n model_config.batch_size)\n decay_steps = int(num_batches_per_epoch *\n training_config.num_epochs_per_decay)\n global_step = tf.Variable(0, name='global_step', trainable=False)\n learning_rate = tf.train.exponential_decay(\n training_config.initial_learning_rate, global_step,\n decay_steps=decay_steps,\n decay_rate=training_config.learning_rate_decay_factor,\n staircase=True)\n tf.summary.scalar('learning_rate', learning_rate)\n\n # Setup optimizer.\n optimizer = tf.train.AdamOptimizer(learning_rate)\n train = optimizer.minimize(model.total_loss, global_step=global_step)\n\n # Setup summary.\n all_summary = tf.summary.merge_all()\n train_writer = tf.summary.FileWriter(FLAGS.summary_dir + '/train')\n val_writer = tf.summary.FileWriter(FLAGS.summary_dir + '/val')\n\n # Create saver\n saver = tf.train.Saver(max_to_keep=training_config.max_checkpoints_to_keep)\n\n # Initialize variables.\n print('Initializing variables...')\n init = tf.global_variables_initializer()\n sess = tf.Session()\n sess.run(init)\n\n print('Initializing data loader for training set...')\n start = time.time()\n data_loader_train = DataLoader()\n data_loader_train.load(FLAGS.training_data_loader)\n end = time.time()\n time_elapsed = end - start\n print('Finished initializing data loader (time elapsed: %f)' % time_elapsed)\n\n print('Initializing data loader for validation set...')\n start = time.time()\n data_loader_val = DataLoader()\n data_loader_val.load(FLAGS.validation_data_loader)\n end = time.time()\n time_elapsed = end - start\n print('Finished initializing data loader (time elapsed: %f)' % time_elapsed)\n\n print('Start training...')\n # Stochastic Gradient Descent\n for i in range(training_config.num_iterations):\n print('Sampling mini-batch...')\n image_features, input_sequence, input_mask, target_sequence = data_loader_train.segmental_sampling(batch_size=training_config.batch_size, num_segments=model_config.num_segments)\n # image_features, input_sequence, input_mask, target_sequence = generate_dumb_batch(training_config.batch_size, model_config.num_segments)\n\n _, total_loss, summary = sess.run((train, model.total_loss, all_summary),\n feed_dict={\"input_features:0\": image_features,\n \"input_feed:0\": input_sequence,\n \"input_mask:0\": input_mask,\n \"target_sequences:0\": target_sequence})\n train_writer.add_summary(summary, i)\n\n # Logging\n if i % training_config.log_every_n_steps == 0:\n print('[%d/%d] loss: %f' % (i, training_config.num_iterations, total_loss))\n\n # Save model.\n if i % training_config.save_every_n_steps == 0:\n print('Saving model at step %d...' % i)\n saver.save(sess, FLAGS.train_dir + '/model', global_step=i)\n\n # evaluate the loss with validation set at every epoch\n if i % training_config.validation_loss_every_n_steps == 0:\n image_features, input_sequence, input_mask, target_sequence = \\\n data_loader_val.segmental_sampling(batch_size=training_config.batch_size,\n num_segments=model_config.num_segments)\n\n total_loss, summary = sess.run((model.total_loss, all_summary),\n feed_dict={\"input_features:0\": image_features,\n \"input_feed:0\": input_sequence,\n \"input_mask:0\": input_mask,\n \"target_sequences:0\": target_sequence})\n val_writer.add_summary(summary, i)\n\n\nif __name__ == \"__main__\":\n tf.app.run()\n","repo_name":"ymao1993/TSCN","sub_path":"lstm_decoder/train_lstm_decoder.py","file_name":"train_lstm_decoder.py","file_ext":"py","file_size_in_byte":7973,"program_lang":"python","lang":"en","doc_type":"code","stars":5,"dataset":"github-code","pt":"14"} +{"seq_id":"28208628721","text":"def get_header(x):\n header = {\"Accept\": \"text/javascript, text/html, application/xml, text/xml, */*\",\n \"Accept-Encoding\": \"gzip,deflate,sdch\",\n \"Accept-Language\": \"en-US,en;q=0.8\",\n \"Host\": \"steamcommunity.com\",\n \"Referer\": x,\n \"Origin\": \"http://steamcommunity.com\",\n \"User-Agent\": \"Mozilla/5.0 (Windows NT 10.0; WOW64; rv:40.0) Gecko/20100101 Firefox/40.0\"\n }\n return header\n","repo_name":"ucshadow/Tor_steambot","sub_path":"header.py","file_name":"header.py","file_ext":"py","file_size_in_byte":480,"program_lang":"python","lang":"en","doc_type":"code","stars":3,"dataset":"github-code","pt":"14"} +{"seq_id":"3271276744","text":"import ins_parser\nfrom sys import stderr, stdout\nfrom ins_parser import insts\nimport xlwt\nfrom bin_parser import get_hex\nfrom copy import deepcopy\nimport utils\nfrom utils import printe\nfrom upro import Uinst\nfrom bin_parser import read_bin\nimport inst\nimport lst_parser\n\n# TODO: 在这里填入配置信息\n\"\"\"\nins_path: INS(指令系统)文件路径\nbin_path: BIN(EM二进制文件)路径\nlst_path: LST文件路径\nsimulation_times: 模拟的微指令周期数,即模拟多少次\"单微指令执行\"\nins_description: 指令的解释,以汇编文件中指令的位置为索引;也可以修改为以指令本身做索引(即不同位置的相同指令采用相同的描述)\n\"\"\"\nins_path = 'samples/divide/DIVIDE.INS'\nbin_path = 'samples/divide/DIVIDE.BIN'\nlst_path = 'samples/divide/DIVIDE.LST'\ntrace_path = 'samples/divide/DIVIDE Trace.xls'\nsimulation_times = 2000\n\n\ndef ins2description(inst):\n \"\"\"\n 指令翻译成解释\n \"\"\"\n ins = inst.split(' ')[0]\n for i in inst.split(' ')[1:]:\n if len(i)>0:\n opt = i.split(',')\n break\n\n if ins == 'MOV':\n return f'将{opt[1]}送入{opt[0]}'\n elif ins == 'ADD':\n return f'将{opt[0]}加上{opt[1]}'\n elif ins == 'AND':\n return f'将{opt[1]}与{opt[0]}相与'\n elif ins == 'OR':\n return f'将{opt[1]}与{opt[0]}相或'\n elif ins == 'SUB':\n return f'将{opt[0]}减去{opt[1]}'\n elif ins == 'RRC':\n return f'将{opt[0]}带进位右移'\n elif ins == 'RLC':\n return f'将{opt[0]}带进位左移'\n elif ins == 'CPL':\n return f'将{opt[0]}按位取反'\n elif ins == 'JZ':\n return f'结果为0则跳转到{opt[0]}'\n elif ins == 'JC':\n return f'有进位则跳转到{opt[0]}'\n elif ins == 'JMP':\n return f'无条件跳转到{opt[0]}'\n else:\n return 'Not Defined'\n\n# simulation\n\nutils.IS_DEBUG_MODE = True\n\n# read macro instructions\num = [\n Uinst(b'\\xff\\xff\\xcb\\x00'),\n Uinst(b'\\xff\\xff\\xff\\x00'),\n Uinst(b'\\xff\\xff\\xff\\x00'),\n Uinst(b'\\xff\\xff\\xff\\x00'),\n]\nins_parser.init()\naddr_to_ins = {}\n\nwith open(ins_path, \"rb\") as f:\n # parse ins\n ins_parser.is_valid_ins_file(f)\n ins_parser.parse_insts(f)\n for ins in ins_parser.insts:\n addr_to_ins[ins.addr] = ins\n addr_to_ins[0] = inst.Inst('_FATCH_', 0)\n # parse uM\n f.read(15)\n for _ in range(252):\n um.append(Uinst(f.read(4)))\nprint('uM read finished:')\nfor i in range(256):\n print('uM[{0}]:\\t{1}'.format(i, hex(um[i].byte)))\n\naddr_to_ins_text = lst_parser.parse_lst(lst_path)\nprint('LST read finished.')\n\n# read EM memory\nem = read_bin(bin_path)\n\n# virtual devices\npc = 0\nupc = 0\nA = 0\nW = 0\nC = 0\nZ = 0\n\n\nclass ALU:\n d = 0\n l = 0\n r = 0\n\n\nalu = ALU()\n\nR = [0] * 4\n\nIR = 0\nST = 0\n# IA=E0\nMAR = 0\n\nIN = 0\nOUT = 0\n\nABUS = 0\nDBUS = 0\nIBUS = 0\n\nprint('Simulation start:')\n\nuins = lambda: um[upc]\n\n\nclass Log:\n ins: str\n ins_addr: str\n machine_code: str\n ins_description: str\n pc: str\n upc: str\n difference = \"\"\n\n def __init__(self):\n self.macro_programs = []\n\n\nclass Status:\n \"\"\"\n 记录运行某时刻的寄存器情况,用于之后进行对比\n \"\"\"\n\n def __init__(self):\n self.pc = pc\n self.upc = upc\n self.A = A\n self.W = W\n self.C = C\n self.Z = Z\n\n self.R = deepcopy(R)\n\n self.IR = IR\n self.ST = ST\n\n self.MAR = MAR\n\n self.IN = IN\n self.OUT = OUT\n\n self.ABUS = ABUS\n self.DBUS = DBUS\n self.IBUS = IBUS\n\n def get_difference(self):\n \"\"\"\n 作为上一次状态,与当前状态对比,返回不一致的值\n \"\"\"\n result = []\n if self.pc != pc:\n result.append(('pc', get_hex(pc)))\n if self.upc != upc:\n result.append(('upc', get_hex(upc)))\n if self.A != A:\n result.append(('A', get_hex(A)))\n if self.W != W:\n result.append(('W', get_hex(W)))\n if self.C != C:\n result.append(('C', get_hex(C)))\n if self.Z != Z:\n result.append(('Z', get_hex(Z)))\n\n for i in range(4):\n if self.R[i] != R[i]:\n result.append(('R[{0}]'.format(i), get_hex(W)))\n\n if self.MAR != MAR:\n result.append(('MAR', get_hex(MAR)))\n\n if self.IN != IN:\n result.append(('IN', get_hex(IN)))\n if self.OUT != OUT:\n result.append(('OUT', get_hex(OUT)))\n\n return result\n\n\nlast_status = Status()\n\n\ndef trace():\n \"\"\"\n 追踪距上一次trace()运行,各主要寄存器的数据变化\n \"\"\"\n global last_status\n difference = last_status.get_difference()\n last_status = Status()\n return '\\n'.join(['{0}: {1}'.format(item[0], item[1]) for item in difference])\n\n\ndef debug_em():\n \"\"\"\n 打印EM数据矩阵\n \"\"\"\n for i in range(16):\n for j in range(16):\n print(get_hex(em[i * 16 + j]) + ' ', end='')\n print()\n\n\nrun_log = []\n# Main Simulation Loop\nfor time in range(simulation_times):\n print('-------------------------')\n print(\"circle:{0}\\tpc:{1}\\tins:{2}\".format(time, hex(pc),\n addr_to_ins[upc // 4 * 4] if upc // 4 * 4 in addr_to_ins else 'UNDEF'))\n print('upc={0}\\t{1}'.format(hex(upc), uins().get_upro()))\n\n if len(run_log) > 0:\n run_log[-1].macro_programs.append(uins().get_upro())\n\n \"\"\"\n 处理ABUS地址总线输入\n \"\"\"\n # address input\n if uins().pcoe():\n ABUS = pc\n if uins().maroe():\n ABUS = MAR\n\n \"\"\"\n 考虑add等指令,这里认为是先执行运算,再考虑DBUS的输入\n 但其实将运算放到微指令周期的最后也可以\n \"\"\"\n # do ALU calculation\n method = uins().get_ss()\n C_out_D = 0\n if method == 0:\n # add\n alu.d = A + W\n if alu.d >= 256:\n C_out_D = 1\n alu.d -= 256\n elif method == 1:\n # minus\n alu.d = A - W\n if alu.d < 0:\n C_out_D = 1\n alu.d += 256\n elif method == 2:\n # or\n alu.d = A | W\n elif method == 3:\n # and\n alu.d = A & W\n elif method == 4:\n # add with lower\n alu.d = A + W + C\n if alu.d >= 256:\n C_out_D = 1\n alu.d -= 256\n elif method == 5:\n # minus with lower\n alu.d = A - W - C\n if alu.d < 0:\n C_out_D = 1\n alu.d += 256\n elif method == 6:\n # !A\n alu.d = A ^ 255\n elif method == 7:\n # A out\n alu.d = A\n\n \"\"\"\n ALU的L/D/R各自维护一个进位标志,实际执行时根据DBUS的连接方式,将对应的Cout/Zout写入C/Z标志位\n CN和FEN同时启用时可能出现问题 建议避免\n \"\"\"\n alu.l = ((alu.d & 127) << 1) + (C & uins().cn() // 512)\n C_out_L = 1 if alu.d & 128 else 0\n alu.r = ((alu.d & 254) >> 1) + (C & uins().cn() // 512) * 128\n C_out_R = alu.d & 1\n\n \"\"\"\n 由X2 X1 X0决定DBUS的输入端\n \"\"\"\n # data -> dbus\n if uins().get_xs() == 0:\n # \"用户IN\"\n DBUS = 0\n elif uins().get_xs() == 1:\n # \"中断地址IA\"\n DBUS = 0\n elif uins().get_xs() == 2:\n # \"堆栈寄存器ST\"\n DBUS = ST\n elif uins().get_xs() == 3:\n # \"PC值\"\n DBUS = pc\n elif uins().get_xs() == 4:\n # \"ALU直通\"\n DBUS = alu.d\n if uins().fen():\n C = C_out_D\n Z = (alu.d == 0)\n elif uins().get_xs() == 5:\n # \"ALU右移\"\n DBUS = alu.r\n if uins().fen():\n C = C_out_R\n Z = (alu.r == 0)\n elif uins().get_xs() == 6:\n # \"ALU左移\"\n DBUS = alu.l\n if uins().fen():\n C = C_out_L\n Z = (alu.l == 0)\n elif uins().get_xs() == 7:\n # \"浮空\"\n if uins().emen() and uins().emrd():\n # \"EM存储器输入\"\n DBUS = em[ABUS]\n elif uins().rrd():\n DBUS = R[IR % 4]\n else:\n DBUS = 0\n\n \"\"\"\n 依次考虑从DBUS取出数据的操作\n \"\"\"\n # dbus -> data\n if uins().emen() and uins().emwr():\n em[ABUS] = DBUS\n if uins().maren():\n MAR = DBUS\n if uins().sten():\n ST = DBUS\n if uins().rwr():\n R[IR % 4] = DBUS\n if uins().aen():\n A = DBUS\n if uins().wen():\n W = DBUS\n\n \"\"\"\n 当前微指令执行功能结束,准备下一条指令\n 以下三个_next是下一个微指令周期的数据,在本周期完全结束时统一覆盖\n \"\"\"\n upc_next = upc\n pc_next = pc\n IR_next = IR\n\n \"\"\"\n 如果iren启用,从内存中读入IR和upc值\n IR值从内存中��接取(包括末两位的R?选择)\n upc需要去除末两位信息,用4对齐地址\n IR的唯一作用是提供R?选择信息,以及决定JMP/JZ/JC的跳转方式\n \"\"\"\n # uPC\n if uins().iren():\n IR_next = em[pc]\n upc_next = em[pc] // 4 * 4\n printe('got next instruction: {0}\\tupc={1}'\n .format(addr_to_ins[upc_next], um[upc_next].get_upro())\n )\n if len(run_log) > 0:\n run_log[-1].difference = trace()\n pass\n run_log.append(Log())\n run_log[-1].ins_addr = get_hex(pc - 1)\n run_log[-1].machine_code = addr_to_ins[upc_next].get_addr_str()\n run_log[-1].upc = get_hex(upc_next)\n run_log[-1].pc = get_hex(pc)\n run_log[-1].ins = addr_to_ins_text[get_hex(pc)]\n run_log[-1].ins_description = ins2description(run_log[-1].ins)\n else:\n upc_next = upc + 1\n\n \"\"\"\n 如果elp打开,赋值pc\n 否则pc+1\n 注意elp与iren是相互独立的,没有直接关系\n \"\"\"\n # PC\n if uins().elp():\n if (IR >> 2) % 4 == 0 and C:\n # JC\n pc_next = DBUS\n printe('! jc: pc set to:{1}\\tnext_ins={0}'\n .format(addr_to_ins[em[pc_next] // 4 * 4], hex(pc_next))\n )\n elif (IR >> 2) % 4 == 1 and Z:\n # JZ\n pc_next = DBUS\n printe('! jz to: pc set to:{1}\\tnext_ins={0}'\n .format(addr_to_ins[em[pc_next] // 4 * 4], hex(pc_next))\n )\n elif (IR >> 2) % 4 == 3 or (IR >> 2) % 4 == 2:\n pc_next = DBUS\n printe('! jmp to: pc set to:{1}\\tnext_ins={0}'\n .format(addr_to_ins[em[pc_next] // 4 * 4], hex(pc_next))\n )\n elif uins().pcoe():\n pc_next = pc + 1\n elif uins().pcoe():\n pc_next = pc + 1\n\n \"\"\"\n 指令周期最终阶段,覆盖pc/upc/ir,进入下一周期\n \"\"\"\n pc = pc_next\n upc = upc_next\n IR = IR_next\n pass\n\nprint('Simulation completed.')\n\nprint('The Final Em is:')\ndebug_em()\n\n# write runtime logs\nprint('Output Runtime Logs...')\nworkbook = xlwt.Workbook(encoding='utf-8')\nworksheet = workbook.add_sheet('ins Trace')\nstyle = xlwt.XFStyle()\nfont = xlwt.Font()\nfont.name = \"等线\"\nfont.bold = True\nfont.height = 210\nstyle.font = font\nstyle.alignment.horz = 2\nstyle.alignment.vert = 1\nstyle.alignment.wrap = 1\n\nworksheet.write(0, 0, label=\"汇编指令\", style=style)\nworksheet.write(0, 1, label=\"程序地址\", style=style)\nworksheet.write(0, 2, label=\"机器码\", style=style)\nworksheet.write(0, 3, label=\"指令说明\", style=style)\nworksheet.write(0, 4, label=\"微程序\", style=style)\nworksheet.write(0, 5, label=\"PC\", style=style)\nworksheet.write(0, 6, label=\"mPC\", style=style)\nworksheet.write(0, 7, label=\"运行时寄存器或存储器的值\", style=style)\nfor row, log in enumerate(run_log):\n worksheet.write(row + 1, 0, label=log.ins, style=style)\n worksheet.write(row + 1, 1, label=log.ins_addr, style=style)\n worksheet.write(row + 1, 2, label=log.machine_code, style=style)\n worksheet.write(row + 1, 3, label=log.ins_description, style=style)\n worksheet.write(row + 1, 4, label='\\r\\n'.join(log.macro_programs), style=style)\n worksheet.write(row + 1, 5, label=log.pc, style=style)\n worksheet.write(row + 1, 6, label=log.upc, style=style)\n worksheet.write(row + 1, 7, label=log.difference, style=style)\nworkbook.save(trace_path)\n","repo_name":"i-Pear/COP3000","sub_path":"simulation.py","file_name":"simulation.py","file_ext":"py","file_size_in_byte":12216,"program_lang":"python","lang":"en","doc_type":"code","stars":13,"dataset":"github-code","pt":"14"} +{"seq_id":"19905470185","text":"import aiosqlite\nimport os\nimport asyncio\n\n\nasync def reset_db():\n\n # User database\n if os.path.exists(\"userHistory.db\"):\n os.remove(\"userHistory.db\")\n\n async with aiosqlite.connect('userHistory.db') as conn:\n async with conn.cursor() as cursor:\n await cursor.execute(\"\"\"CREATE TABLE USERS (\n discord_ID INTEGER NOT NULL PRIMARY KEY,\n class TEXT,\n level INTEGER,\n unit TEXT,\n march_size TEXT,\n alliance TEXT,\n mm_traps TEXT,\n skins TEXT,\n status TEXT,\n lottery INTEGER,\n interacted_with_event INTEGER\n );\n \"\"\")\n await conn.commit()\n\n # Event database\n if os.path.exists(\"eventInfo.db\"):\n os.remove(\"eventInfo.db\")\n\n async with aiosqlite.connect('eventInfo.db') as conn:\n async with conn.cursor() as cursor:\n await cursor.execute(\"\"\"CREATE TABLE EVENT (\n title TEXT,\n time TEXT,\n message_ID INT,\n channel_ID INT\n );\n \"\"\")\n await cursor.execute(\"INSERT INTO EVENT (title, time, message_ID, channel_ID) values ('placeholder', 'placeholder', 0, 0)\")\n await conn.commit()\n\n\nif __name__ == \"__main__\":\n confirm_reset = input(\"Are you sure you want to reset the database? Type CONFIRM to confirm.\\n\")\n if confirm_reset.lower() == \"confirm\":\n asyncio.run(reset_db())\n","repo_name":"evanm1455/svsInvitationBot","sub_path":"reset_db.py","file_name":"reset_db.py","file_ext":"py","file_size_in_byte":1626,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"14"} +{"seq_id":"13409953993","text":"# parse_jp.py\n# (C) 2021 Marquis Kurt.\n# This Source Code Form is subject to the terms of the Mozilla Public\n# License, v. 2.0. If a copy of the MPL was not distributed with this\n# file, You can obtain one at https://mozilla.org/MPL/2.0/.\n\nimport os\nfrom random import randrange, shuffle\nfrom string import ascii_lowercase\nfrom typing import Iterable, List, Tuple\n\n\ndef get_valid_words_from_files() -> List[str]:\n \"\"\"Returns a list of words from the specified words files that are valid.\"\"\"\n words_file = \"outside_sources/words\" if os.path.isfile(\n \"outside_sources/words\") else \"/usr/share/dict/words\"\n with open(words_file, 'r') as words:\n valid_words = [w.strip().lower() for w in words.readlines() if is_admissible(w)]\n with open(\"outside_sources/jp-romaji.txt\") as jp_data:\n valid_words += [w.strip().lower() for w in jp_data.readlines()]\n return valid_words\n\n\ndef is_admissible(word: str) -> bool:\n \"\"\"Returns whether a word is considered admissible for the dataset.\n \n For the purposes of the dataset, a word is admissible if it conforms to the following:\n - The word must be at least three characters long.\n - The word only contains ASCII characters; i.e., the word does not have any accents.\n - The word only contains letters in the alphabet\n - The word is not a proper noun or acronym (i.e., the word doesn't have uppercase letters)\n - The word is not a contraction.\n \"\"\"\n real_word = word.strip()\n return len(real_word) >= 3 and real_word.isascii() and real_word.isalpha(\n ) and real_word.islower() and not real_word.endswith(\"'s\")\n\n\ndef random_string(max_size: int) -> str:\n \"\"\"Returns a string of a random length between 3 and 12 characters, with no syllabic structure in mind.\"\"\"\n length = randrange(3, max_size) if max_size > 3 else 3\n string = \"\"\n for _ in range(length):\n next_index = randrange(0, len(ascii_lowercase) - 1)\n string += ascii_lowercase[next_index]\n return string\n\n\ndef pad_sequence(sequence: Iterable, max_length: int = 8) -> list:\n \"\"\"Returns a list of characters along with a \"null character\" string to pad out to a maximum length.\n\n Args:\n sequence (Iterable): The iterable of characters to get a padded sequence for.\n max_length (int, optional): The maximum length of the sequence. Defaults to 8.\n\n Returns:\n list: [description]\n \"\"\"\n diff = max_length - sum(1 for _ in sequence)\n return [i for i in sequence] + [\"*\" for _ in range(diff)]\n\n\nif __name__ == \"__main__\":\n # Create the dataset pools for valid and invalid words.\n valid_word_dataset = get_valid_words_from_files()\n avg_length = sum([len(str(w)) for w in valid_word_dataset]) // len(valid_word_dataset)\n invalid_word_dataset = [random_string(avg_length) for _ in range(len(valid_word_dataset))]\n\n # Filter out words that are too long for our tests.\n valid_word_dataset = [w for w in valid_word_dataset if len(w) <= avg_length]\n invalid_word_dataset = [w for w in invalid_word_dataset if len(w) <= avg_length]\n\n # Create the columns for the CSV files.\n col_valid: List[Tuple[str, str]] = [(word, \"valid\") for word in valid_word_dataset]\n col_invalid: List[Tuple[str, str]] = [(word, \"invalid\") for word in invalid_word_dataset]\n columns = col_valid + col_invalid\n\n # Shuffle the dataset.\n for _ in range(randrange(25, 50)):\n shuffle(columns)\n\n # Find the split marker for the 80/20 split.\n split_point = int(len(columns) * 0.8)\n\n # Split the columns into training and testing pools.\n train, test = columns[:split_point], columns[split_point:]\n\n # Create the CSV header that will be used to label features and targets.\n csv_header = \",\".join((f\"char{i+1:02d}\" for i in range(avg_length))) + \",Valid\\n\"\n csv_header_predictive = \",\".join(\n (f\"char{i+1:02d}\" for i in range(avg_length))) + \",prediction\\n\"\n\n # Write the training data to the training dataset.\n with open(\"datasets/dtrain.csv\", \"w+\") as train_file:\n train_file.write(csv_header)\n for word, classifier in train:\n train_file.write(\",\".join(pad_sequence(word, avg_length)) + f\",{classifier}\\n\")\n\n # Write the testing data to the testing dataset.\n with open(\"datasets/dtest.csv\", \"w+\") as test_file:\n test_file.write(csv_header)\n for word, classifier in test:\n test_file.write(\",\".join(pad_sequence(word, avg_length)) + f\",{classifier}\\n\")\n\n # Write the training data to the training dataset using the predictive headers.\n with open(\"datasets/dtrain_predict.csv\", \"w+\") as train_predict_file:\n train_predict_file.write(csv_header_predictive)\n for word, classifier in train:\n train_predict_file.write(\",\".join(pad_sequence(word, avg_length)) + f\",{classifier}\\n\")\n\n # Write the testing data to the testing dataset using the predictive headers.\n with open(\"datasets/dtest_predict.csv\", \"w+\") as test_predict_file:\n test_predict_file.write(csv_header_predictive)\n for word, classifier in test:\n test_predict_file.write(\",\".join(pad_sequence(word, avg_length)) + f\",{classifier}\\n\")\n","repo_name":"alicerunsonfedora/abysima","sub_path":"scripts/create_dataset.py","file_name":"create_dataset.py","file_ext":"py","file_size_in_byte":5170,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"14"} +{"seq_id":"21364351243","text":"\"\"\"\nutilities\n~~~~~~~~~\n\nThis module provides utility functions that might be useful in\nseveral places within the Advent Of Code projects.\n\n\n\"\"\"\n\nclass AStarNode():\n \"\"\"A node class for A* Pathfinding\"\"\"\n\n def __init__(self, parent=None, position=None):\n self.parent = parent\n self.position = position\n\n self.g = 0\n self.h = 0\n self.f = 0\n\n def __eq__(self, other):\n return self.position == other.position\n\n\ndef astar(maze, start, end, walkableItem, allow_diagonal_movement = False):\n \"\"\"\n Returns a list of tuples as a path from the given start to the given end in the given maze\n :param maze: 2D array like maze[row][col], with values indicating paths\n :param start: (row,col) tuple corresponding to maze starting position\n :param end: (row,col) tuple corresponding to the desired end point\n :param walkableItem: symbol that indicates a walkable path (type corresponding to maze)\n :return: None if not walkable\n \"\"\"\n\n def return_path(current_node):\n path = []\n current = current_node\n while current is not None:\n path.append(current.position)\n current = current.parent\n return path[::-1] # Return reversed path\n\n # Create start and end node\n start_node = AStarNode(None, start)\n start_node.g = start_node.h = start_node.f = 0\n end_node = AStarNode(None, end)\n end_node.g = end_node.h = end_node.f = 0\n\n # Initialize both open and closed list\n open_list = []\n closed_list = []\n\n # Add the start node\n open_list.append(start_node)\n \n # Adding a stop condition\n outer_iterations = 0\n max_iterations = (len(maze)*(len(maze[0])+1)) ** 2\n\n # what squares do we search\n #adjacent_squares = ((0, -1), (0, 1), (-1, 0), (1, 0),)\n adjacent_squares = ((-1, 0), (0, -1), (0, 1), (1, 0),)\n if allow_diagonal_movement:\n adjacent_squares = ((0, -1), (0, 1), (-1, 0), (1, 0), (-1, -1), (-1, 1), (1, -1), (1, 1),)\n\n # Loop until you find the end\n while len(open_list) > 0:\n outer_iterations += 1\n \n # Get the current node\n current_node = open_list[0]\n current_index = 0\n for index, item in enumerate(open_list):\n if item.f < current_node.f:\n current_node = item\n current_index = index\n \n if outer_iterations > max_iterations:\n # if we hit this point return the path such as it is\n # it will not contain the destination\n #warn(\"giving up on pathfinding too many iterations\")\n print(\"astar: giving up on pathfinding, too many iterations\")\n return None # return_path(current_node)\n\n # Pop current off open list, add to closed list\n open_list.pop(current_index)\n closed_list.append(current_node)\n\n # Found the goal\n if current_node == end_node:\n return return_path(current_node)\n\n # Generate children\n children = []\n \n for new_position in adjacent_squares: # Adjacent squares\n\n # Get node position\n node_position = (current_node.position[0] + new_position[0], current_node.position[1] + new_position[1])\n\n # Make sure within range\n if node_position[0] > (len(maze) - 1) or node_position[0] < 0 or node_position[1] > (len(maze[len(maze)-1]) -1) or node_position[1] < 0:\n continue\n\n # Make sure walkable terrain\n if maze[node_position[0]][node_position[1]] != walkableItem:\n continue\n\n # Create new node\n new_node = AStarNode(current_node, node_position)\n\n # Append\n children.append(new_node)\n\n # Loop through children\n for child in children:\n \n # Child is on the closed list\n if len([closed_child for closed_child in closed_list if closed_child == child]) > 0:\n continue\n\n # Create the f, g, and h values\n child.g = current_node.g + 1\n child.h = ((child.position[0] - end_node.position[0]) ** 2) + ((child.position[1] - end_node.position[1]) ** 2)\n child.f = child.g + child.h\n\n # Child is already in the open list\n if len([open_node for open_node in open_list if child == open_node and child.g >= open_node.g]) > 0:\n continue\n\n # Add the child to the open list\n open_list.append(child)\n\n\ndef testAStar():\n\n maze = [[0, 0, 0, 0, 1, 0, 0, 0, 0, 0],\n [0, 0, 0, 0, 1, 0, 0, 0, 0, 0],\n [0, 0, 0, 0, 1, 0, 0, 0, 0, 0],\n [0, 0, 0, 0, 1, 0, 0, 0, 0, 0],\n [0, 0, 0, 0, 1, 0, 0, 0, 0, 0],\n [0, 0, 0, 0, 1, 0, 0, 0, 0, 0],\n [0, 0, 0, 0, 1, 0, 0, 0, 0, 0],\n [0, 0, 0, 0, 1, 0, 0, 0, 0, 0],\n [0, 0, 0, 0, 0, 0, 0, 0, 0, 0],\n [0, 0, 0, 0, 1, 0, 0, 0, 0, 0]]\n# maze = [[0, 1, 0],\n# [0, 1, 0],\n# [0, 1, 0]]\n\n start = (0, 0)\n end = (7, 6)\n# start = (0, 0)\n# end = (2, 2)\n\n path = astar(maze, start, end, 0, False)\n print(path)\n# path = astar(maze, start, end, 0, [(0, -1), (0, 1), (-1, 0), (1, 0)])\n# print(path)\n\nif __name__ == '__main__':\n testAStar()","repo_name":"jborlik/AdventOfCode2018","sub_path":"utilities.py","file_name":"utilities.py","file_ext":"py","file_size_in_byte":5310,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"14"} +{"seq_id":"37032240288","text":"import os, random\nimport torch, torch.nn as nn\nimport torch.nn.functional as F\n\n\ndef create_model(model_name):\n if model_name=='mnistcnn4':\n output_channel = random.choice([60, 64])\n model = MnistCNN4(output_channel)\n model_name = 'mnistcnn4_' + str(output_channel)\n elif model_name=='cifarcnn4':\n model = CifarCNN4()\n elif model_name=='resnet18':\n model = ResNet18()\n return model_name, model\n\n\n# 分层模型\nclass LayeringModel(nn.Module):\n def __init__(self):\n super(LayeringModel, self).__init__()\n self.representor = None\n self.predictor = None\n \n def forward(self, x):\n representation = self.representor(x)\n logits = self.predictor(representation)\n scores = F.log_softmax(logits, dim=1)\n return representation, logits, scores\n\n def forward_rep(self, representation):\n logits = self.predictor(representation)\n scores = F.log_softmax(logits, dim=1)\n return logits, scores\n\n def freeze_pre(self):\n for param in self.predictor.parameters():\n param.requires_grad = False\n self.predictor.eval()\n \n def freeze_rep(self):\n for param in self.representor.parameters():\n param.requires_grad = False\n self.representor.eval()\n\n def weight_flatten(self):\n params = []\n for u in self.parameters():\n params.append(u.clone().detach().view(-1))\n params = torch.cat(params)\n return params\n\n def grad_flatten(self):\n grads = []\n for u in self.parameters():\n if u.requires_grad:\n grads.append(u.grad.clone().detach().view(-1))\n grads = torch.cat(grads)\n return grads\n\n\nclass Linear(LayeringModel):\n def __init__(self):\n super(Linear, self).__init__()\n self.representor = nn.Sequential(\n nn.Flatten(1),\n )\n self.predictor = nn.Linear(in_features=64, out_features=4, bias=True)\n\n\nclass MLP(LayeringModel):\n def __init__(self):\n super(MLP, self).__init__()\n self.representor = nn.Sequential(\n nn.Flatten(1),\n nn.Linear(64, 16),\n )\n self.predictor = nn.Linear(in_features=16, out_features=4, bias=True)\n\n\nclass MnistMLP(LayeringModel):\n def __init__(self):\n super(MnistMLP, self).__init__()\n self.representor = nn.Sequential(\n nn.Flatten(1),\n nn.Linear(784, 256),\n nn.ReLU(),\n nn.Linear(256, 32),\n )\n self.predictor = nn.Linear(in_features=32, out_features=10, bias=True)\n\n\nclass MnistCNN2(LayeringModel):\n def __init__(self):\n super(MnistCNN2, self).__init__()\n self.representor = nn.Sequential(\n nn.Conv2d(1, 6, kernel_size=3, stride=2, padding=1),\n nn.BatchNorm2d(6),\n nn.ReLU(),\n nn.Conv2d(6, 16, kernel_size=3, stride=2, padding=1),\n nn.BatchNorm2d(16),\n nn.ReLU(),\n nn.Flatten(1),\n nn.Linear(784, 32),\n )\n self.predictor = nn.Linear(in_features=32, out_features=10, bias=False)\n\n\nclass MnistCNN4(LayeringModel):\n def __init__(self, output_channel):\n super(MnistCNN4, self).__init__()\n if output_channel==60:\n channel = 240\n elif output_channel==64:\n channel = 256\n self.representor = nn.Sequential(\n nn.Conv2d(1, 6, kernel_size=3, stride=2, padding=1),\n nn.BatchNorm2d(6),\n nn.ReLU(),\n nn.Conv2d(6, 16, kernel_size=3, stride=2, padding=1),\n nn.BatchNorm2d(16),\n nn.ReLU(),\n nn.Conv2d(16, 32, kernel_size=3, stride=2, padding=1),\n nn.BatchNorm2d(32),\n nn.ReLU(),\n nn.Conv2d(32, output_channel, kernel_size=3, stride=2, padding=1),\n nn.BatchNorm2d(output_channel),\n nn.ReLU(),\n nn.Flatten(1),\n nn.Linear(channel, 32),\n )\n self.predictor = nn.Linear(in_features=32, out_features=10, bias=False)\n\n\nclass CifarCNN4(LayeringModel):\n def __init__(self):\n super(CifarCNN4, self).__init__()\n self.representor = nn.Sequential(\n nn.Conv2d(3, 64, kernel_size=(3, 3), stride=(1, 1), padding=(1, 1)),\n nn.BatchNorm2d(64, eps=1e-5, momentum=0.1, affine=True, track_running_stats=False),\n nn.ReLU(),\n nn.MaxPool2d(kernel_size=2, stride=2, padding=0, dilation=1, ceil_mode=False),\n nn.Conv2d(64, 64, kernel_size=(3, 3), stride=(1, 1), padding=(1, 1)),\n nn.BatchNorm2d(64, eps=1e-5, momentum=0.1, affine=True, track_running_stats=False),\n nn.ReLU(),\n nn.MaxPool2d(kernel_size=2, stride=2, padding=0, dilation=1, ceil_mode=False),\n nn.Conv2d(64, 64, kernel_size=(3, 3), stride=(1, 1), padding=(1, 1)),\n nn.BatchNorm2d(64, eps=1e-5, momentum=0.1, affine=True, track_running_stats=False),\n nn.ReLU(),\n nn.MaxPool2d(kernel_size=2, stride=2, padding=0, dilation=1, ceil_mode=False),\n nn.Conv2d(64, 64, kernel_size=(3, 3), stride=(1, 1), padding=(1, 1)),\n nn.BatchNorm2d(64, eps=1e-5, momentum=0.1, affine=True, track_running_stats=False),\n nn.ReLU(),\n nn.MaxPool2d(kernel_size=2, stride=2, padding=0, dilation=1, ceil_mode=False),\n nn.Flatten(1),\n )\n self.predictor = nn.Linear(in_features=256, out_features=10, bias=True)\n\n\n\ndef conv3x3(in_planes, out_planes, stride=1, groups=1, dilation=1):\n \"\"\"3x3 convolution with padding\"\"\"\n return nn.Conv2d(\n in_planes,\n out_planes,\n kernel_size=3,\n stride=stride,\n padding=dilation,\n groups=groups,\n bias=False,\n dilation=dilation,\n )\n\n\ndef conv1x1(in_planes, out_planes, stride=1):\n \"\"\"1x1 convolution\"\"\"\n return nn.Conv2d(in_planes, out_planes, kernel_size=1, stride=stride, bias=False)\n\n\nclass BasicBlock(nn.Module):\n expansion = 1\n\n def __init__(\n self,\n inplanes,\n planes,\n stride=1,\n downsample=None,\n groups=1,\n base_width=64,\n dilation=1,\n norm_layer=None,\n ):\n super(BasicBlock, self).__init__()\n if norm_layer is None:\n norm_layer = nn.BatchNorm2d\n if groups != 1 or base_width != 64:\n raise ValueError(\"BasicBlock only supports groups=1 and base_width=64\")\n if dilation > 1:\n raise NotImplementedError(\"Dilation > 1 not supported in BasicBlock\")\n # Both self.conv1 and self.downsample layers downsample the input when stride != 1\n self.conv1 = conv3x3(inplanes, planes, stride)\n self.bn1 = norm_layer(planes)\n self.relu = nn.ReLU(inplace=True)\n self.conv2 = conv3x3(planes, planes)\n self.bn2 = norm_layer(planes)\n self.downsample = downsample\n self.stride = stride\n\n def forward(self, x):\n identity = x\n\n out = self.conv1(x)\n out = self.bn1(out)\n out = self.relu(out)\n\n out = self.conv2(out)\n out = self.bn2(out)\n\n if self.downsample is not None:\n identity = self.downsample(x)\n\n out += identity\n out = self.relu(out)\n\n return out\n\n\nclass Bottleneck(nn.Module):\n expansion = 4\n\n def __init__(\n self,\n inplanes,\n planes,\n stride=1,\n downsample=None,\n groups=1,\n base_width=64,\n dilation=1,\n norm_layer=None,\n ):\n super(Bottleneck, self).__init__()\n if norm_layer is None:\n norm_layer = nn.BatchNorm2d\n width = int(planes * (base_width / 64.0)) * groups\n # Both self.conv2 and self.downsample layers downsample the input when stride != 1\n self.conv1 = conv1x1(inplanes, width)\n self.bn1 = norm_layer(width)\n self.conv2 = conv3x3(width, width, stride, groups, dilation)\n self.bn2 = norm_layer(width)\n self.conv3 = conv1x1(width, planes * self.expansion)\n self.bn3 = norm_layer(planes * self.expansion)\n self.relu = nn.ReLU(inplace=True)\n self.downsample = downsample\n self.stride = stride\n\n def forward(self, x):\n identity = x\n\n out = self.conv1(x)\n out = self.bn1(out)\n out = self.relu(out)\n\n out = self.conv2(out)\n out = self.bn2(out)\n out = self.relu(out)\n\n out = self.conv3(out)\n out = self.bn3(out)\n\n if self.downsample is not None:\n identity = self.downsample(x)\n\n out += identity\n out = self.relu(out)\n\n return out\n\n\nclass ResNet(LayeringModel):\n def __init__(\n self,\n block,\n layers,\n num_classes=10,\n zero_init_residual=False,\n groups=1,\n width_per_group=64,\n replace_stride_with_dilation=None,\n norm_layer=None,\n ):\n super(ResNet, self).__init__()\n if norm_layer is None:\n norm_layer = nn.BatchNorm2d\n self._norm_layer = norm_layer\n self.inplanes = 64\n self.dilation = 1\n if replace_stride_with_dilation is None:\n # each element in the tuple indicates if we should replace\n # the 2x2 stride with a dilated convolution instead\n replace_stride_with_dilation = [False, False, False]\n if len(replace_stride_with_dilation) != 3:\n raise ValueError(\n \"replace_stride_with_dilation should be None \"\n \"or a 3-element tuple, got {}\".format(replace_stride_with_dilation)\n )\n self.groups = groups\n self.base_width = width_per_group\n self.representor = nn.Sequential(\n nn.Conv2d(3, self.inplanes, kernel_size=3, stride=1, padding=1, bias=False),\n norm_layer(self.inplanes),\n nn.ReLU(inplace=True),\n nn.MaxPool2d(kernel_size=3, stride = 2, padding=1),\n self._make_layer(block, 64, layers[0]),\n self._make_layer(block, 128, layers[1], stride=2, dilate=replace_stride_with_dilation[0]),\n self._make_layer(block, 256, layers[2], stride=2, dilate=replace_stride_with_dilation[1]),\n self._make_layer(block, 512, layers[3], stride=2, dilate=replace_stride_with_dilation[2]),\n nn.AdaptiveAvgPool2d((1, 1)),\n nn.Flatten(1),\n nn.Linear(512, 256),\n )\n self.predictor = nn.Linear(256, num_classes)\n\n for m in self.modules():\n if isinstance(m, nn.Conv2d):\n nn.init.kaiming_normal_(m.weight, mode=\"fan_out\", nonlinearity=\"relu\")\n elif isinstance(m, (nn.BatchNorm2d, nn.GroupNorm)):\n nn.init.constant_(m.weight, 1)\n nn.init.constant_(m.bias, 0)\n\n # Zero-initialize the last BN in each residual branch,\n # so that the residual branch starts with zeros, and each residual block behaves like an identity.\n # This improves the model by 0.2~0.3% according to https://arxiv.org/abs/1706.02677\n if zero_init_residual:\n for m in self.modules():\n if isinstance(m, Bottleneck):\n nn.init.constant_(m.bn3.weight, 0)\n elif isinstance(m, BasicBlock):\n nn.init.constant_(m.bn2.weight, 0)\n\n def _make_layer(self, block, planes, blocks, stride=1, dilate=False):\n norm_layer = self._norm_layer\n downsample = None\n previous_dilation = self.dilation\n if dilate:\n self.dilation *= stride\n stride = 1\n if stride != 1 or self.inplanes != planes * block.expansion:\n downsample = nn.Sequential(\n conv1x1(self.inplanes, planes * block.expansion, stride),\n norm_layer(planes * block.expansion),\n )\n\n layers = []\n layers.append(\n block(\n self.inplanes,\n planes,\n stride,\n downsample,\n self.groups,\n self.base_width,\n previous_dilation,\n norm_layer,\n )\n )\n self.inplanes = planes * block.expansion\n for _ in range(1, blocks):\n layers.append(\n block(\n self.inplanes,\n planes,\n groups=self.groups,\n base_width=self.base_width,\n dilation=self.dilation,\n norm_layer=norm_layer,\n )\n )\n\n return nn.Sequential(*layers)\n\n\ndef _resnet(arch, block, layers, pretrained, progress, device, **kwargs):\n model = ResNet(block, layers, **kwargs)\n if pretrained:\n script_dir = os.path.dirname(__file__)\n state_dict = torch.load(\n script_dir + \"/state_dicts/\" + arch + \".pt\", map_location=device\n )\n model.load_state_dict(state_dict)\n return model\n\n\ndef ResNet18(pretrained=False, progress=True, device=\"cpu\", **kwargs):\n return _resnet(\n \"resnet18\", BasicBlock, [2, 2, 2, 2], pretrained, progress, device, **kwargs\n )\n","repo_name":"candy1126xx/FedPR","sub_path":"utils/models.py","file_name":"models.py","file_ext":"py","file_size_in_byte":13184,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"14"} +{"seq_id":"38441291783","text":"import random\n\ndef getrandomlist(*x):\n randomlist = []\n if len(x[0]) == 1:\n randomlist.append(random.randint(1))\n elif len(x[0]) == 2:\n for i in range(x[1]):\n randomlist.append(random.randint(x[0][0]))\n elif len(x) == 3:\n for i in range(x[1]):\n randomlist.append(random.randint(x[0][0],x[0][1]))\n else:\n print('please input your parameter correctly:[start = 0, end , number')\n return []\n\ndef sortlist(x):\n if len(x)<2:\n return x\n else:\n for i in range(len(x)):\n for j in range(i+1,len(x)):\n if x[i] > x[j]:\n tem = x[i]\n x[i] = x[j]\n x[j] = tem\n elif x[i] == x[j]:\n x.pop(j)\n else:\n pass\n return x\ndef transFrmstr2dig(str):\n tem = str.split(\",\")\n return [int(tem[x]) for x in range(len(tem))]\nprint('please inout those parameter:')\n\nrdlst = getrandomlist(transFrmstr2dig(input()))\n\n\nprint(sortlist(rdlst))","repo_name":"CMOnly/Matplotlib_exercise","sub_path":"exercise100/Exercise5.py","file_name":"Exercise5.py","file_ext":"py","file_size_in_byte":1056,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"14"} +{"seq_id":"72699700174","text":"import requests\r\nfrom bs4 import BeautifulSoup as bs\r\nimport pandas as pd\r\nimport re\r\nimport numpy as np\r\nimport json\r\nimport time ### testing purpose on code speed\r\n## main function, calls subfunction for specific websites and returns the data in pandas df or dict\r\ndef scrape_country(country,website,ReturnType = 'pandas'): # takes in no caps country and website\r\n # imports country list and checks if its on the list\r\n # make a dict file assocated with the websites used:\r\n # CASE SENS FOR COUNTRY????\r\n \r\n weblist={'worldometer':'https://www.worldometers.info/coronavirus/country/'} # lib of websites to use\r\n country_dict=scrape_pop() # generates a dict of country names and populations\r\n if country in country_dict:\r\n if website=='worldometer':\r\n return WorldometerScrape_country(country,website,ReturnType,weblist,country_dict)\r\n else:\r\n raise ValueError(\"Bad Site\")\r\n return 0\r\n else:\r\n print(country_dict(country) +'~~~~'+ country)\r\n raise ValueError(\"Invalid Country\")\r\n return 0 \r\n\r\n\r\ndef WorldometerScrape_country(country,website,ReturnType,weblist,country_dict):\r\n start_time = time.time()#### start time check\r\n url=(weblist[website]+country+'/') # combines url \r\n requests.get(url)\r\n import_page=requests.get(url)\r\n htmlcontent = import_page.content\r\n soup = str(bs(htmlcontent, \"html.parser\"))\r\n### finds Dates \r\n n = soup.find(\"Deaths per Day
\") \r\n n_cat = soup[n:].find(\"categories:\")\r\n n_start = soup[n_cat+n:].find('[')\r\n n_lengh = soup[n+n_cat+n_start:].find(']')\r\n start1=int(n+n_cat+n_start)+1\r\n stop1=int(start1+n_lengh)-1\r\n #print(soup[start1:stop1])\r\n p=soup[start1:stop1]\r\n split_dates = re.split(r',(?=\")', p) #splits with comma delimiter while ignoring values inside quotes\r\n ############# maybe convert this format if i cant plot\r\n### finds daily deaths\r\n n_cat = soup[n:].find(\"data:\") \r\n n_start = soup[n_cat+n:].find('[')\r\n n_lengh = soup[n+n_cat+n_start:].find(']')\r\n start2=int(n+n_cat+n_start)+1\r\n stop2=int(start2+n_lengh)-1\r\n dataY=soup[start2:stop2]\r\n daily_deaths = np.array(dataY.replace('null','0').split(','),dtype='int') #splits + replace null>>0\r\n### finds total deaths\r\n n = soup.find(\"'Total Coronavirus Deaths'\") \r\n n_cat = soup[n:].find(\"data:\")\r\n n_start = soup[n_cat+n:].find('[')\r\n n_lengh = soup[n+n_cat+n_start:].find(']')\r\n start3=int(n+n_cat+n_start)+1\r\n stop3=int(start3+n_lengh)-1\r\n dataY=soup[start3:stop3]\r\n cum_deaths = np.array(dataY.replace('null','0').split(','),dtype='int') # unrapped from pd.array( ) to fix dividing\r\n ###### data formatting\r\n df = pd.DataFrame(columns=['Dates']) # builds blank dataframe with headers \r\n months = {'jan': '01','feb': '02','mar': '03','apr':'04','may':'05',\r\n 'jun':'06','jul':'07','aug':'08','sep':'09',\r\n 'oct':'10','nov':'11','dec':'12'} # dict to convert 'xxx' month to '#'\r\n format_dates=[]\r\n for d in split_dates: # converts Jan 02, 2020 to format 2020-01-02\r\n mm=months[d[1:4].casefold()]\r\n dd=d[5:7]\r\n yyyy=d[9:13]\r\n format_dates.append(yyyy+'-'+mm+'-'+dd)\r\n df['Index']=range(0,len(format_dates)) ################## not really needed just for plotting testing ########################\r\n df['Dates']=format_dates\r\n df['Daily Deaths']=daily_deaths\r\n df['Total Deaths']=cum_deaths \r\n df['Daily Deaths per 100k']=np.divide(daily_deaths,int(country_dict[country][0]))*100000\r\n df['Total Deaths per 100k']=np.divide(cum_deaths,int(country_dict[country][0]))*100000\r\n print(country+\"--- %s seconds ---\" % (time.time() - start_time))##### cycle time check\r\n### sets the output type\r\n if ReturnType=='pandas': \r\n return df\r\n elif ReturnType=='dict':\r\n return df.to_dict()\r\n\r\ndef OurWorldData_json():\r\n url = 'https://covid.ourworldindata.org/data/owid-covid-data.csv'\r\n r = requests.get(url, allow_redirects=True)\r\n rd=r.content.decode(\"utf-8\")\r\n data=pd.read_csv(rd)\r\n return data\r\n #open('OurWorldData_Covid.json', 'w').write(r2)\r\n\r\n\r\n## this doesnt work so far. maybe create static country and pop list for countries we want to use\r\n\r\ndef scrape_C_names(): \r\n url='https://www.worldometers.info/coronavirus/#countries'\r\n import_page=requests.get(url)\r\n htmlcontent = import_page.content\r\n soup = str(bs(htmlcontent, \"html.parser\"))\r\n# finds Dates \r\n n = soup.find('''table id=\"main_table_countries_today''') \r\n print(n)\r\n n_cat = soup[n:].find(\"categories:\")\r\n n_start = soup[n_cat+n:].find('[')\r\n n_lengh = soup[n+n_cat+n_start:].find(']')\r\n #start1=int(n+n_cat+n_start)+1\r\n #stop1=int(start1+n_lengh)-1\r\n start1=n+1\r\n stop1=start1+10\r\n #print(soup[start1:stop1])\r\n p=soup[start1:stop1]\r\n return p\r\n\r\n\r\n\r\ndef scrape_pop():\r\n url='https://www.worldometers.info/world-population/population-by-country/'\r\n requests.get(url)\r\n import_page=requests.get(url)\r\n htmlcontent = import_page.content\r\n soup = bs(htmlcontent, \"html.parser\")\r\n table_data = soup.find('table', class_ = 'table table-striped table-bordered')\r\n headers = []\r\n for th in table_data.find_all('th'):\r\n title = th.text\r\n headers.append(title)\r\n pop_table = pd.DataFrame(columns = headers)\r\n \r\n for j in table_data.find_all('tr')[1:]:\r\n row_data = j.find_all('td')\r\n row = [tr.text for tr in row_data]\r\n length = len(pop_table)\r\n pop_table.loc[length] = row\r\n\r\n df_cut= pop_table.loc[:,['Country (or dependency)','Population (2020)']]\r\n df_cut['Country (or dependency)']=df_cut['Country (or dependency)'].str.lower()\r\n \r\n df_cut['Population (2020)']=df_cut['Population (2020)'].str.replace(',','')\r\n \r\n Country_list=df_cut.set_index('Country (or dependency)').T.to_dict('list') # converts to library\r\n Country_list['us'] = Country_list.pop('united states') # fixes name for united states to us\r\n Country_list['viet-nam'] = Country_list.pop('vietnam') # fixes name \r\n Country_list['congo'] = Country_list.pop('dr congo')\r\n Country_list['saint-vincent-and-the-grenadines'] = Country_list.pop('st. vincent & grenadines')\r\n \r\n \r\n return Country_list\r\n \r\ndef json_frame_writer(countries,site,filename='CovidData.json'):\r\n out={}\r\n for i in countries:\r\n temp=scrape_country(i,site).to_dict()\r\n out[i]=temp\r\n out = json.dumps(out)\r\n with open(filename, 'w') as outfile:\r\n outfile.write(out) \r\n\r\n","repo_name":"brookefur/P1_Covid_Dashboard","sub_path":"Part_1/ScrapeWebsite.py","file_name":"ScrapeWebsite.py","file_ext":"py","file_size_in_byte":6658,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"14"} +{"seq_id":"35532086467","text":"import os\n\nfrom fastapi import FastAPI\nfrom fastapi.openapi.docs import get_swagger_ui_html\nfrom fastapi.responses import ORJSONResponse\nfrom starlette.staticfiles import StaticFiles\n\nfrom app.apis.router import api_router\nfrom app.core.config import settings\nfrom app.core.exception import register_exception\nfrom app.core.middleware import register_cross, register_middleware, register_startup_and_shutdown\n\n\ndef create_app():\n app = FastAPI(\n title=\"peachTreePlanting\",\n version=\"0.1.1\",\n default_response_class=ORJSONResponse,\n )\n\n if settings.DEV_ENV:\n static_dir = os.path.join(\n os.path.dirname(os.path.abspath(__file__)), \"..\", \"static\"\n )\n\n app.mount(\"/static\", StaticFiles(directory=static_dir), name=\"static\")\n\n @app.get(\"/docs\")\n async def custom_swagger_ui_html():\n return get_swagger_ui_html(\n openapi_url=app.openapi_url,\n title=app.title + \" - Swagger UI\",\n oauth2_redirect_url=app.swagger_ui_oauth2_redirect_url,\n swagger_js_url=\"/static/swagger-ui/swagger-ui-bundle.js\",\n swagger_css_url=\"/static/swagger-ui/swagger-ui.css\",\n )\n\n # 导入路由\n app.include_router(api_router, prefix=\"/api\")\n\n register_exception(app)\n register_cross(app)\n register_middleware(app)\n register_startup_and_shutdown(app)\n\n return app\n\n\napp = create_app()\n","repo_name":"Liwenru88/peach-tree-planting","sub_path":"app/__init__.py","file_name":"__init__.py","file_ext":"py","file_size_in_byte":1447,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"14"} +{"seq_id":"28992637198","text":"from peewee import *\r\n\r\ndb = PostgresqlDatabase('prep3', user='postgres', password='bdwdcb8y',\r\n host='localhost')\r\n\r\n\r\nclass workers(Model):\r\n id_worker = AutoField(column_name='id_worker', primary_key=True)\r\n fnp = TextField(column_name='fnp')\r\n brth = DateTimeField(column_name='brth')\r\n department = TextField(column_name='department')\r\n\r\n class Meta:\r\n table_name = 'workers'\r\n database = db\r\n\r\nclass in_out(Model):\r\n id_worker = ForeignKeyField(workers, column_name='id_worker')\r\n cur_date = DateTimeField(column_name='cur_date')\r\n cur_day = TextField(column_name='cur_day')\r\n cur_time = TimeField(column_name='cur_time')\r\n cur_type = TextField(column_name='cur_type')\r\n\r\n class Meta:\r\n table_name = 'in_out'\r\n database = db\r\n\r\n\r\n# Вывести все отделы и количество сотрудников хоть раз опоздавших за всю историю учета\r\ndef task_3():\r\n '''res = (in_out.select(workers.id_worker, in_out.cur_type, workers.fnp)\\\r\n .join(workers, on=workers.id_worker == in_out.id_worker))'''\r\n\r\n num = SQL('id_worker')\r\n cur_date = SQL('cur_date')\r\n cur_time = SQL('cur_time')\r\n cur_date = SQL('cur_date')\r\n cur_type = SQL('cur_type')\r\n num = SQL('num')\r\n\r\n temp_res = (workers\r\n .select(workers.department, fn.count(SQL('id_worker1').distinct()).alias('cnt'))\\\r\n .from_(in_out\r\n .select(SQL('id_worker1'), SQL('cur_date'), SQL('cur_time'), SQL('cur_date'), SQL('cur_type'), SQL('num'))\\\r\n .from_(in_out\r\n .select(in_out.id_worker.alias('id_worker1'), in_out.cur_date.alias('cur_date'), in_out.cur_time.alias('cur_time'),\r\n in_out.cur_type.alias('cur_type'),\r\n fn.RANK().over(partition_by=[in_out.id_worker, in_out.cur_date],\r\n order_by=[in_out.cur_time]).alias('num'))\\\r\n .where(in_out.cur_type == 1))\\\r\n .where(SQL('cur_time') > '09:00:00')\\\r\n .where(SQL('num') == 1))\r\n .join(workers, on=workers.id_worker == SQL('id_worker1'))\\\r\n .group_by(workers.department))\r\n\r\n print(temp_res)\r\n for row in temp_res:\r\n print(row.department, row.cnt)\r\n\r\n# Найти средний возраст сотрудников, не находящихся на рабочем месте 8 часов в день\r\ndef task_2():\r\n temp = (in_out\r\n .select(in_out.id_worker, in_out.cur_date, in_out.cur_time.alias('time_out'),\r\n in_out.cur_type,\r\n fn.RANK().over(partition_by=[in_out.id_worker, in_out.cur_date],\r\n order_by=[in_out.cur_time]).alias('num'))\\\r\n .where(SQL('cur_type') == 2).alias('res2'))\r\n\r\n temp_res = (in_out\r\n .select(workers.id_worker)\\\r\n .from_(in_out\r\n .select(SQL('res1.id_worker'), SQL('res1.cur_date'), (fn.SUM(SQL('time_out')) - fn.SUM(SQL('time_in'))).alias('hours'))\\\r\n .from_(in_out\r\n .select(in_out.id_worker, in_out.cur_date, in_out.cur_time.alias('time_in'),\r\n in_out.cur_type,\r\n fn.RANK().over(partition_by=[in_out.id_worker, in_out.cur_date],\r\n order_by=[in_out.cur_time]).alias('num'))\\\r\n .where(SQL('cur_type') == 1).alias('res1'))\r\n .join(temp, on=SQL('res1.id_worker') == SQL('res2.id_worker') and SQL('res1.num') == SQL('res2.num') and SQL('res1.cur_date') == SQL('res2.cur_date'))\\\r\n .group_by(SQL('res1.id_worker'), SQL('res1.cur_date')))\\\r\n .join(workers, on=SQL('res1.id_worker') == workers.id_worker)\\\r\n .where(SQL('hours') < 8))\r\n\r\n print(temp_res)\r\n for row in temp_res:\r\n print(row.id_worker)\r\n\r\n\r\n\r\ndef task_1_2():\r\n res = (workers\r\n .select(workers.department)\\\r\n .group_by(workers.department)\\\r\n .having(fn.COUNT(workers.id_worker) > 10))\r\n\r\n for row in res:\r\n print(row.department)\r\n\r\n\r\ndef task_2_2(dt):\r\n temp_1 = (in_out\r\n .select(in_out.id_worker, in_out.cur_date)\\\r\n .where(in_out.cur_type == 1)\\\r\n .where(in_out.cur_date == dt)\\\r\n .group_by(in_out.id_worker, in_out.cur_date)\\\r\n .having(fn.COUNT(in_out.id_worker) == 1).alias('res1'))\r\n\r\n temp_2 = (in_out\r\n .select(in_out.id_worker, in_out.cur_date) \\\r\n .where(in_out.cur_type == 2) \\\r\n .where(in_out.cur_time >= '17:30:00') \\\r\n .group_by(in_out.id_worker, in_out.cur_date) \\\r\n .having(fn.COUNT(in_out.id_worker) == 1).alias('res2'))\r\n\r\n res = (workers\r\n .select(workers.fnp)\\\r\n .join(temp_1, on=workers.id_worker == SQL('res1.id_worker'))\\\r\n .join(temp_2, on=workers.id_worker == SQL('res2.id_worker')))\r\n\r\n for row in res:\r\n print(row.fnp)\r\n\r\n\r\n\r\n#task_2()\r\n#task_3()\r\n\r\n#task_1_2()\r\ntask_2_2('14-12-2018')\r\n\r\n\r\n\r\n\r\n\r\n\r\n","repo_name":"Bryanskaya/DataBase","sub_path":"prepare_rk3/lmb_phr.py","file_name":"lmb_phr.py","file_ext":"py","file_size_in_byte":5326,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"14"} +{"seq_id":"41903047403","text":"from siamese import train_images, train_labels, test_images, test_labels\nfrom tensorflow.keras.models import Model\nfrom tensorflow.keras.layers import Input, Flatten, Dense, Dropout, Conv2D, Softmax, Reshape, concatenate, Add\nfrom tensorflow.keras.optimizers import Adam\nimport numpy as np\nfrom tensorflow.python.keras.utils.vis_utils import plot_model\nfrom keras.utils import np_utils\nfrom tensorflow.keras.callbacks import CSVLogger\n\n\ndef intialize_cnn():\n input = Input(shape=(28, 28,), name=\"base_input\")\n u = Reshape((28, 28, 1))(input)\n x = Conv2D(filters=32, kernel_size=[4, 4], padding='valid', use_bias=True)(u)\n x = Conv2D(filters=16, kernel_size=[3, 3], padding='valid', use_bias=True)(x)\n y = Conv2D(filters=32, kernel_size=[4, 4], padding='valid', use_bias=True)(u)\n y = Conv2D(filters=16, kernel_size=[3, 3], padding='valid', use_bias=True)(y)\n x = Add()([x, y])\n x = Flatten()(x)\n x = Dense(128, activation=\"relu\")(x)\n x = Dropout(0.1)(x)\n x = Dense(64, activation=\"relu\")(x)\n x = Dropout(0.1)(x)\n x = Dense(10, activation=\"softmax\")(x)\n return Model(inputs=input, outputs=x)\n\n\nadam = Adam()\ninput1 = Input(shape=(28, 28,), name=\"initial_input\")\noutput = intialize_cnn()\noutput1 = output(input1)\nmodel = Model(input1, output1)\nmodel.compile(loss='categorical_crossentropy', optimizer=adam, metrics=['accuracy'])\n\n# plot_model(model, show_shapes=True, show_layer_names=True, to_file='CNN.png')\n# print(output.summary())\nhistory = model.fit(x=train_images, y=np_utils.to_categorical(train_labels), epochs=5, batch_size=128,\n validation_data=(test_images, np_utils.to_categorical(test_labels)), callbacks=[CSVLogger(\"train.csv\")])\n","repo_name":"piyumalanthony/TF2_fuctionalities","sub_path":"CNN_classification.py","file_name":"CNN_classification.py","file_ext":"py","file_size_in_byte":1704,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"14"} +{"seq_id":"71496118094","text":"import os\r\nfrom PIL import Image\r\ndef fun():\r\n\tpath = 'detector/patches'\r\n\tfiles = os.listdir(path)\r\n\r\n\tfor file in files:\r\n\t filename = path + '/' + file\r\n\t img = Image.open(filename)\r\n\t img = img.resize((121,121))\r\n\t img.save(filename)\r\n","repo_name":"themis0888/CS408-Project","sub_path":"detector/resize_imgs.py","file_name":"resize_imgs.py","file_ext":"py","file_size_in_byte":247,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"14"} +{"seq_id":"38845095754","text":"#!/usr/bin/python3\n\nimport adrsir\nimport ir_control\nimport os, sys, time\nimport argparse\nimport fcntl\n\nBASE_DIR = os.path.dirname(__file__)\nIR_DATA_DIR = os.path.join(BASE_DIR, 'ir_data/')\nLOCK_FILE = os.path.join(BASE_DIR, 'ir_control.lock')\n\ndef send(file, num):\n\n if os.path.isfile(LOCK_FILE) == False:\n with open(LOCK_FILE, 'w'): pass\n\n ifp = open(LOCK_FILE, 'r')\n fcntl.flock(ifp.fileno(), fcntl.LOCK_EX)\n\n filepath = IR_DATA_DIR + file\n print('[*] send {} {} time(s)'.format(filepath, num))\n if not os.path.isfile(filepath):\n print('[!] {} does not exist'.format(filepath))\n return\n\n with open(filepath, 'r') as fp:\n data = fp.read()\n\n for i in range(num):\n adrsir.trans(data)\n time.sleep(0.5)\n\n fcntl.flock(ifp.fileno(), fcntl.LOCK_UN)\n ifp.close()\n\ndef main():\n args = sys.argv\n for arg in args:\n print(arg)\n if arg != 'ir_send_control.py':\n send(arg, 1)\n\n return\n\nif __name__ == '__main__':\n main()\n","repo_name":"fernangit/ras_py_InfraredRemoteControl","sub_path":"ir_send_control.py","file_name":"ir_send_control.py","file_ext":"py","file_size_in_byte":1017,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"14"} +{"seq_id":"23098196221","text":"import json\nimport time\nfrom multiprocessing import Process,Lock\n\ndef search(i):\n with open('ticket',encoding='utf-8') as f:\n ticket = json.load(f)\n print('%s :当前的余票是%s张'%(i,ticket['count']))\n\ndef buy_ticket(i):\n with open('ticket',encoding='utf-8') as f:\n ticket = json.load(f)\n if ticket['count']>0:\n ticket['count'] -= 1\n print('%s买到票了'%i)\n time.sleep(0.1)\n with open('ticket', mode='w',encoding='utf-8') as f:\n json.dump(ticket,f)\n\ndef get_ticket(i,lock):\n search(i)\n with lock: # 代替acquire和release 并且在此基础上做一些异常处理,保证即便一个进程的代码出错退出了,也会归还钥匙\n buy_ticket(i)\n\n\nif __name__ == '__main__':\n lock = Lock() # 互斥锁\n for i in range(10):\n Process(target=get_ticket,args=(i,lock)).start()\n\n# import time\n# from multiprocessing import Lock,Process\n# def func(i,lock):\n# lock.acquire() # 拿钥匙\n# print('被锁起来的代码%s'%i)\n# lock.release() # 还钥匙\n# time.sleep(1)\n#\n# if __name__ == '__main__':\n# lock = Lock()\n# for i in range(10):\n# p = Process(target=func,args=(i,lock))\n# p.start()\n\n\n# from multiprocessing import Lock # 互斥锁 不能再同一个进程中连续acquire多次\n# lock = Lock()\n# lock.acquire()\n# print(1)\n# lock.release()\n# lock.acquire()\n# print(2)\n# lock.release()\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n","repo_name":"tianshang486/Pythonlaonanhai","sub_path":"day33 课堂笔记以及代码/day33/6.抢票的例子_锁.py","file_name":"6.抢票的例子_锁.py","file_ext":"py","file_size_in_byte":1440,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"14"} +{"seq_id":"18158116221","text":"# filename: amazon-shop.py\r\n# by: abhay gupta\r\n# date: 22-03-03\r\n#\r\n# desc: amazon demo qn: \r\n# given two groups, determine if cart contains both groups in order\r\n\r\ndef recurse(cart, group):\r\n for item in cart:\r\n if item == group[0] or group[0] == \"anything\":\r\n if len(group) == 1:\r\n return 1\r\n return recurse(cart[1:], group[1:])\r\n return 0\r\n\r\ndef isWinner(group1, group2, cart):\r\n group = group1 + group2\r\n \r\n print(group)\r\n return (recurse(cart, group))\r\n\r\nif __name__ == \"__main__\":\r\n group1 = [\"pear\", \"peach\", \"apple\", \"anything\"]\r\n group2 = [\"kiwi\"]\r\n cart = [\"pear\", \"peach\", \"orange\", \"apple\",\"kiwi\"]\r\n \r\n print(isWinner(group1, group2, cart))\r\n \r\n ","repo_name":"ab12gu/coding-challenges","sub_path":"python/interview/amazon/amazon-shop.py","file_name":"amazon-shop.py","file_ext":"py","file_size_in_byte":697,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"14"} +{"seq_id":"35752176798","text":"import sys\nimport codecs\nimport requests\nimport bs4\nimport random\nimport time\nimport json\n\ndef main():\n\n outfile = codecs.open('13_한국쓰리축.txt', 'w', 'utf-8')\n outfile.write(\"NAME|BRANCH|ADDR|TELL\\n\")\n\n sido_list = ['서울', '경기', '강원', '충북', '충남', '경북', '경남', '전북', '전남', '인천', '대전', '울산', '광주', '대구', '부산', '세종', '제주']\n for sido in sido_list:\n store_list = getStoreInfo(sido)\n print(sido)\n for store in store_list:\n outfile.write(u'%s|' % store['name'])\n outfile.write(u'%s|' % store['branch'])\n outfile.write(u'%s|' % store['addr'])\n outfile.write(u'%s\\n' % store['tell'])\n time.sleep(random.uniform(0.3, 0.9))\n\n outfile.close()\n\ndef getStoreInfo(sido):\n url = 'http://www.koreatriaxle.com/'\n data = {\n 'controller': 'Location',\n 'action': 'Service',\n # 'SIDO': '인천',\n }\n data['SIDO'] = sido\n headers = {\n 'Accept': 'text/html,application/xhtml+xml,application/xml;q=0.9,image/avif,image/webp,image/apng,*/*;q=0.8,application/signed-exchange;v=b3;q=0.9',\n 'Accept-Encoding': 'gzip, deflate',\n 'Accept-Language': 'ko,en;q=0.9,ko-KR;q=0.8',\n 'Cache-Control': 'no-cache',\n 'Connection': 'keep-alive',\n 'Cookie': 'ASPSESSIONIDACCACBDQ=LPAFOMFCOKFDBEGDKDKGKBGB',\n 'Host': 'www.koreatriaxle.com',\n 'Pragma': 'no-cache',\n 'Referer': 'http://www.koreatriaxle.com/?controller=Location&action=Service&SIDO=%EC%A0%9C%EC%A3%BC',\n 'Upgrade-Insecure-Requests': '1',\n 'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/86.0.4240.75 Safari/537.36',\n }\n pageString = requests.get(url,params = data, headers = headers).text\n bsObj = bs4.BeautifulSoup(pageString,\"html.parser\")\n li = bsObj.find_all('li')\n\n result = []\n for info in li :\n try:\n name = '한국쓰리축'\n branch = info.find('strong').text\n infos = str(info.find('address')).replace('\\r','').replace('\\n','').replace('\\t','').replace('

','').replace('
','').split('
')\n addr = infos[1]\n tell = infos[2]\n if len(addr) < 14 :\n addr = infos[0]\n tell = infos[1]\n except:\n try:\n name = '한국쓰리축'\n branch = info.find('strong').text\n infos = str(info.find('address')).replace('\\r','').replace('\\n','').replace('\\t','').replace('
','').replace('
','').split('
')\n addr = infos[0]\n tell = infos[1]\n result.append({'name': name, 'branch': branch, 'addr': addr, 'tell': tell})\n except:pass\n else:\n result.append({'name':name,'branch':branch,'addr':addr,'tell':tell})\n\n return result\n\ndef errExit(msg):\n sys.stderr.write(msg + '\\n')\n sys.exit(0)\n\nif __name__ == '__main__':\n main()\n\n","repo_name":"jjunmong/01_Public_Repo","sub_path":"00_crawling/일반사이트/트럭서비스센터/13_한국쓰리축.py","file_name":"13_한국쓰리축.py","file_ext":"py","file_size_in_byte":3068,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"14"} +{"seq_id":"72250584335","text":"import cv2\nimport numpy as np\nfrom tqdm import tqdm\n\nfrom utils import draw_label, draw_box\nfrom utils.masker import Masker\nfrom speedometer import Speedometer \n\n\nblue = (255, 0, 0)\ngreen = (0, 255, 0)\nred = (0, 0, 255)\n\n\ndef detect_on_video(video_path, out_path, detector, tracker, coef_file='coef.json', mask_file = 'mask.png' , to_mp4 = False, class_names = None):\n\tif class_names is None:\n\t\tclass_names = ['car', 'minibus', 'trolleybus', 'tram', 'truck', 'bus', 'middle_bus', 'ambulance', 'fire_truck', 'middle_truck', 'tractor', 'uncategorized', 'van', 'person']\n\n\t# Создаём считыватель исходного видео\n\tistream = cv2.VideoCapture(video_path)\n\n\t# Получаем данные о исходном видео\n\tw = int(istream.get(cv2.CAP_PROP_FRAME_WIDTH))\n\th = int(istream.get(cv2.CAP_PROP_FRAME_HEIGHT))\n\tfps = int(istream.get(cv2.CAP_PROP_FPS))\n\tframe_count = int(istream.get(cv2.CAP_PROP_FRAME_COUNT))\n\n\t# Создаём писателя для результирующего видео\n\tif to_mp4:\n\t\tfourcc = cv2.VideoWriter_fourcc(*'XVID')\n\telse:\n\t\tfourcc = cv2.VideoWriter_fourcc(*'VP80')\n\twriter = cv2.VideoWriter(out_path, fourcc, fps, (w, h), True)\n\n\t# Создаём экземпляр класса Masker для выделения проезжей части на каждом кадре\n\tmasker = Masker(mask_file, (w, h))\n\n\t# Создаём трекер для отслеживания автомобилей на разных кадрах\n\ttracker = Sort()\n\tspeedometer = Speedometer(coef_file, fps=fps, size=(w, h))\n\n\n\t# Обрабатываем видео покадрово\n\tfor frame_id in tqdm(range(frame_count)):\n\t\t# Считываем кадр, создаём кадр для видео с результатом\n\t\tret, frame = istream.read()\n\t\tif not ret:\n\t\t\tbreak\n\t\telse:\n\t\t\tout_frame = frame\n\n\t\t# Выделяем проезжую часть\n\t\tmasked_frame = masker.apply(frame)\n\n\t\t# Распознаём объекты на кадре\n\t\toutputs = detector(masked_frame)\n\n\t\t# Получаем bbox (рамки) и вероятность принадлежности классу для каждого найденного объекта\n\t\tboxes = outputs['instances'].pred_boxes.tensor.to(\"cpu\").numpy()\n\t\tscores = outputs['instances'].scores.to(\"cpu\").numpy()\n\t\tclasses = outputs['instances'].pred_classes.to(\"cpu\").numpy()\n\n\t\t# Обновляем трекер, получаем track_id (id объекта на предыдущих кадрах) для каждого найденного объекта\n\t\tfor_tracker = np.concatenate([boxes, scores[:, None]], axis=1)\n\t\tdets, associaties = tracker.update(for_tracker, make_associaties = True)\n\n\t\tspeeds = spmeter.update(dets)\n\n\n\t\tfor i in range(scores.shape[0]):\n\t\t\tbox = boxes[i].astype(np.int16)\n\t\t\ttrack_id = associaties[i]\n\n\t\t\tif track_id == 0: continue\n\t\t\t\n\t\t\tspeed = spmeter.ms_to_kmh(speeds[track_id])\n\t\t\tclass_id = classes[i]\n\t\t\tclass_label = class_names[class_id]\n\n\t\t\tdraw_box(out_frame, box)\n\n\t\t\tdraw_label(out_frame, track_id, box[:2], size=2, shadow=True)\n\t\t\tdraw_label(out_frame, round(speed, 2), (box[0], box[1] + 10), color=(255, 100, 100), shadow=True)\n\t\t\tdraw_label(out_frame, class_label, (box[0], box[1] + 25), color=(100, 255, 100), shadow=True)\n\n\t\t# Добавляем кадр с разметкой к результирующему видео\n\t\twriter.write(out_frame)\n\n\t# Сохраняем видео с результатом\n\twriter.release()\n\treturn True","repo_name":"alxgrents/determining_vehicle_speed","sub_path":"utils/detect.py","file_name":"detect.py","file_ext":"py","file_size_in_byte":3498,"program_lang":"python","lang":"ru","doc_type":"code","stars":0,"dataset":"github-code","pt":"14"} +{"seq_id":"23499062615","text":"import numpy as np \nimport os\nimport csv\nimport random\n\ndatapath_train = '/home/lss/Desktop/cky/NAN-test/FDDB_feature'\nfile_haeader = [\"subject\",\"template\",\"feature_path\"]\ncsvTrain = open(\"train_fddb.csv\", \"w\")\nwriter_train = csv.writer(csvTrain)\npersons = os.listdir(datapath_train)\nwriter_train.writerow(file_haeader)\nfor person in persons:\n feature_dir = os.path.join(datapath_train,person)\n templates = os.listdir(feature_dir)\n # train_head = 0\n # test_head = 0\n # train_speak = 0\n # test_speak = 0\n for template in templates:\n template_dir = os.path.join(feature_dir,template)\n frames = os.listdir(template_dir)\n tmp = [person,template,template_dir]\n writer_train.writerow(tmp)\ndatapath_test = '/home/lss/Desktop/cky/NAN-test/Conrad Dataset'\nfile_haeader = [\"subject\",\"template\",\"feature_path\"]\ncsvTest = open(\"test_CD.csv\", \"w\")\nwriter_test = csv.writer(csvTest)\npersons = os.listdir(datapath_test)\nwriter_test.writerow(file_haeader)\nnum_objects = len(persons)\ncount = 0\nfor person in persons:\n feature_dir = os.path.join(datapath_test,persons[count],'feature')\n templates = os.listdir(feature_dir)\n for i in range(5):\n idx_diff = random.randint(0,len(persons)-1)\n if(idx_diff == count):\n idx_diff = (idx_diff+3)%len(persons)\n diff_path = feature_dir = os.path.join(datapath_test,persons[idx_diff],'feature')\n diff_tem = os.listdir(diff_path)\n idx_a = random.randint(0,len(templates)-1)\n diff_dir = os.path.join(datapath_test,persons[idx_diff],'feature',diff_tem[(idx_a+1)%len(diff_tem)],diff_tem[(idx_a+1)%len(diff_tem)]+'.mat')\n if not os.path.exists(diff_dir):\n print(diff_dir)\n print(\"ddd\")\n\n template_dir_a = os.path.join(datapath_test,persons[count],'feature',templates[idx_a],templates[idx_a]+'.mat')\n if not os.path.exists(template_dir_a):\n print(templates)\n print(template_dir_a) \n print(persons[count])\n print(count)\n print(os.listdir(os.path.join(datapath_test,persons[count],'feature',persons[count],'feature'))) \n print(\"aaa\") \n idx_b = random.randint(0,len(templates)-1)\n if(idx_a == idx_b):\n idx_b = (idx_b+3)%len(templates)\n template_dir_b = os.path.join(datapath_test,persons[count],'feature',templates[idx_b],templates[idx_b]+'.mat')\n if not os.path.exists(template_dir_b):\n print(template_dir_b)\n print(\"bbb\")\n is_same = True\n tmp = [template_dir_a,template_dir_b,is_same]\n writer_test.writerow(tmp)\n is_same = False\n tmp = [template_dir_a,diff_dir,is_same]\n writer_test.writerow(tmp)\n count += 1\n # if (template[0:3] == \"head\"):\n # if((random.random()<0.33 and test_head < 1) or train_head == 2):\n # test_head = test_head + 1\n # template_dir = os.path.join(feature_dir,template)\n # frames = os.listdir(template_dir)\n # for frame in frames:\n # feature_path = os.path.join(template_dir,frame)\n # tmp = [person,template,feature_path]\n # writer_test.writerow(tmp)\n # else:\n # train_head = train_head + 1\n # template_dir = os.path.join(feature_dir,template)\n # frames = os.listdir(template_dir)\n # for frame in frames:\n # feature_path = os.path.join(template_dir,frame)\n # tmp = [person,template,feature_path]\n # writer_train.writerow(tmp)\n # else:\n # if((random.random()<0.3 and test_speak < 3) or train_speak == 7):\n # test_speak = test_speak + 1\n # template_dir = os.path.join(feature_dir,template)\n # frames = os.listdir(template_dir)\n # for frame in frames:\n # feature_path = os.path.join(template_dir,frame)\n # tmp = [person,template,feature_path]\n # writer_test.writerow(tmp)\n # else:\n # train_head = train_head + 1\n # template_dir = os.path.join(feature_dir,template)\n # frames = os.listdir(template_dir)\n # for frame in frames:\n # feature_path = os.path.join(template_dir,frame)\n # tmp = [person,template,feature_path]\n # writer_train.writerow(tmp)\n","repo_name":"Kaiyang-Chen/NAN-test","sub_path":"generate_csv.py","file_name":"generate_csv.py","file_ext":"py","file_size_in_byte":4538,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"14"} +{"seq_id":"71352998414","text":"from transaction.transaction import Transaction\nfrom p2pnetwork.node import Node as p2pNode\nfrom hexbytes import HexBytes\n\n# p2pNode is the Node implementation as provided by the p2pnetwork package.\n# We have to extend it to do blockchain stuff.\n\n\nclass Node(p2pNode):\n # Python class constructor\n def __init__(self, host, port, id=None, callback=None, max_connections=0):\n super(Node, self).__init__(host, port, id, callback, max_connections)\n self.block_found_by_peer = False\n\n def outbound_node_connected(self, connected_node):\n print(f\"outbound_node_connected: {connected_node.port}\")\n\n def inbound_node_connected(self, connected_node):\n print(f\"inbound_node_connected: {connected_node.port}\")\n print(f\"sending blockchain state to: {connected_node.port}\")\n self.send_to_nodes({\"state\": self.blockchain.save_state()})\n\n def inbound_node_disconnected(self, connected_node):\n print(f\"inbound_node_disconnected: {connected_node.port}\")\n\n def outbound_node_disconnected(self, connected_node):\n print(f\"outbound_node_disconnected: {connected_node.port}\")\n\n def node_message(self, connected_node, data):\n # print(f\"node_message from {connected_node.port}\" + \": \" + str(data))\n print(f\"node_message from {connected_node.port}.\")\n # self.block_found_by_peer = True\n if \"state\" in data and not self.blockchain.synced: # Initial sync.\n print(f\"Got initial blockchain state from {connected_node.port}\")\n self.blockchain.load_state(data[\"state\"])\n self.blockchain.synced = True\n elif \"new_block\" in data: # Someone else found a block.\n self.blockchain.new_blocks.append(data[\"new_block\"])\n print(f\"{connected_node.port} found a block: {data['new_block']}\")\n self.block_found_by_peer = True\n elif \"new_tx\" in data:\n print(f\"{connected_node.port} sent a tx: {data['new_tx']}\")\n tx = Transaction(\n _fr=\"\",\n _to=\"\",\n _amount=\"\",\n _nonce=\"\",\n _signature=\"\",\n _data=\"\",\n _gas_price=\"\",\n _tx_dict=data[\"new_tx\"],\n )\n self.blockchain.pending_txs.append(tx)\n else:\n print(f\"received unexpected message. {data}\")\n exit(0)\n\n def node_disconnect_with_outbound_node(self, connected_node):\n print(\n f\"node wants to disconnect with other outbound node: {connected_node.port}\"\n )\n\n def node_request_to_stop(self):\n print(\"node is requested to stop!\")\n","repo_name":"izcoser/simplechain","sub_path":"node/node.py","file_name":"node.py","file_ext":"py","file_size_in_byte":2644,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"14"} +{"seq_id":"1052607966","text":"### 데이터셋 다운로드 (resize해서 작은 모델)\n'''\n%mkdir /content/yolov5/hardhat\n%cd /content/yolov5/hardhat\n!curl -L \"http\"\n'''\nfrom glob import glob\n\ntrain_img_list = glob('content/yolov5/hardhat/train/images/*.jpg')\ntest_img_list = glob('content/yolov5/hardhat/test/images/*.jpg')\nprint(len(train_img_list))\n\n#split해서 val을 만들어줌\nfrom sklearn.model_selection import train_test_split\n\ntest_img_list, val_img_list = train_test_split(test_img_list, test_size=0.5, random_state=777)\nprint(len(test_img_list))\n\nimport yaml\n\nwith open('content/yolov5/hardhat/train.txt', 'w') as f:\n f.write('\\n'.join(train_img_list)+ '\\n')\nwith open('content/yolov5/hardhat/test.txt', 'w') as f:\n f.write('\\n'.join(test_img_list)+ '\\n')\nwith open('content/yolov5/hardhat/val.txt', 'w') as f:\n f.write('\\n'.join(val_img_list)+ '\\n')\n\n#%cat content/yolov5/hardhat/data.yaml #확인 후 수정\n\n#data.yaml 파일 수정\n'''\n%%writetemplate content/yolov5/hardhat/data.yaml\n\ntrain: ./hardhat/train/images\ntest: ./hardhat/test/images\nval: ./hardhat/test/images\n\nnc: 3\nnames:['head','helmet','person']\n'''\n\n\n### 모델 구성\nwith open('data.yaml', 'r') as stream:\n num_classes = str(yaml.safe_load(stream)['nc'])\n\n#%cat /content/yolov5/models/yolov5s.yaml\n\n#custom yolov5 만듬\n'''\n%%writetemplate /content/yolov5/models/custom_yolov5s.yaml\n\n#parameters\nnc: {num_classes}\n\n.....\n'''\n\n### 학습\n'''\n%time\n%cd /content/yolov5\n!python train.py --img 416 --batch 64 --epoch 50 --data ./hardhat/data.yaml --cfg ./models/custom_yolov5s.yaml --weights '' --name hardhat_results --cache\n'''\n\n'''\n%load_ext tensorboard\n%tensorboard --logdir runs\n'''\n\nImage(filename='runs/train/hardhat_results/results.png', width=1000)\nImage(filename='runs/train/hardhat_results/train_batch0.png', width=1000)\nImage(filename='runs/train/hardhat_results/val_batch0_label.png', width=1000)\n\n\n### 검증\n#!python val.py --weight runs/train/hardhat_results/weights/best.py --data ./hardhat/data.yaml --img 416 --iou 0.6 --half\n\n#!python val.py --weight runs/train/hardhat_results/weights/best.py --data ./hardhat/data.yaml --img 416 --task test\n\n### 추론\n","repo_name":"newmade01/ML","sub_path":"DNN(DeepLearning)/CNN_합성곱신경망/Detection/Yolo/YOLOv5_EX3.py","file_name":"YOLOv5_EX3.py","file_ext":"py","file_size_in_byte":2135,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"14"} +{"seq_id":"74089655373","text":"# Module for pairwise comparison of performances of algorithm\n\n################################################\n#### Metrics for pairwise methods ####\n#### and significance tests ####\n################################################\n\n# TODO: clarify names, add scored version of NHST and more.\n\nimport numpy as np\nfrom scipy.stats import binom_test\nfrom baycomp import two_on_single, two_on_multiple\n\ndef declare_ties(a, b, comparison_func=None, **kwargs):\n \"\"\" Declare ties between a and b using an assymetrical boolean comparison function in both directions.\n\n Args:\n a: Ballot representing one candidate (array-like).\n b: Ballot representing one candidate (array-like).\n comparison_func: Assymetrical function used to compare two candidates.\n The function comparison_func(a, b) should return 1 if a beats b and 0 otherwise.\n By default it's p_wins (defined in the same module), performing a binomial test.\n reverse: If True, a and b are considered equivalent.\n kwargs: Argument of the comparison function.\n \"\"\"\n if comparison_func is None:\n comparison_func = p_wins\n return comparison_func(a, b, **kwargs) == comparison_func(b, a, **kwargs)\n\ndef hard_wins(a, b, reverse=False):\n \"\"\" Function returning True if a wins against b in a majority vote.\n\n Args:\n a: Ballot representing one candidate (array-like).\n b: Ballot representing one candidate (array-like).\n reverse: If True, lower is better.\n \"\"\"\n a, b = np.array(a), np.array(b)\n Wa, Wb = np.sum(a > b), np.sum(b > a)\n if reverse:\n Wa, Wb = np.sum(a < b), np.sum(b < a)\n return Wa > Wb # hard comparisons\n\ndef copeland_wins(a, b, reverse=False):\n \"\"\" Function returning 1 if a wins against b in a majority vote, 0.5 in case of a tie and 0 otherwise.\n\n Useful for to compute Copeland's method.\n\n Args:\n a: Ballot representing one candidate (array-like).\n b: Ballot representing one candidate (array-like).\n reverse: If True, lower is better.\n \"\"\"\n a, b = np.array(a), np.array(b)\n Wa, Wb = np.sum(a > b), np.sum(b > a)\n if reverse:\n Wa, Wb = np.sum(a < b), np.sum(b < a)\n if Wa > Wb: # hard comparisons\n return 1\n elif Wb > Wa:\n return 0\n else: # Copeland's method\n return 0.5\n\ndef p_wins(a, b, pval=0.05, reverse=False):\n \"\"\" Function returning True if a significantly wins against b (binomial test).\n\n Args:\n a: Ballot representing one candidate (array-like).\n b: Ballot representing one candidate (array-like).\n pval: A win is counted only if the probability of the null hypothesis (tie) is equal or smaller than pval.\n If pval is set to 1, then p_wins is equivalent to hard_wins function.\n reverse: If True, lower is better.\n \"\"\"\n a, b = np.array(a), np.array(b)\n Wa, Wb = np.sum(a > b), np.sum(b > a)\n if reverse:\n Wa, Wb = np.sum(a < b), np.sum(b < a)\n significant = binom_test(Wa, n=len(a), p=0.5) <= pval\n wins = Wa > Wb\n return significant and wins # count only significant wins\n\ndef bayes_wins(a, b, width=0.1, independant=False, score=False):\n \"\"\" Compare a and b using a Bayesian signed-ranks test.\n\n Args:\n a: Ballot representing one candidate (array-like).\n b: Ballot representing one candidate (array-like).\n width: the width of the region of practical equivalence.\n independant: True if the different scores are correlated (e.g. bootstraps or cross-validation scores).\n score: If True, returns the probability of winning instead of a boolean.\n \"\"\"\n a, b = np.array(a), np.array(b)\n if independant:\n p_a, p_tie, p_b = two_on_multiple(a, b, rope=width)\n else:\n p_a, p_tie, p_b = two_on_single(a, b, rope=width)\n if score:\n res = p_a\n else:\n res = p_a == max([p_a, p_tie, p_b])\n return res\n\ndef bayes_score(a, b, **kwargs):\n \"\"\" Alias for bayes_wins but returning probability of winning.\n \"\"\"\n return bayes_wins(a, b, score=True, **kwargs)\n\ndef success_rate(a, b, reverse=False, ties=False):\n \"\"\" Returns the frequency (rate) of a > b.\n\n Args:\n a: Ballot representing one candidate (array-like).\n b: Ballot representing one candidate (array-like).\n reverse: If True, lower is better.\n ties: If True, ties are taken into account (with value 0.5) instead of hard comparisons\n \"\"\"\n a, b = np.array(a), np.array(b)\n if not reverse: # normal behavior\n Wa = np.sum(a > b)\n else:\n Wa = np.sum(a < b)\n if ties:\n Eq = np.sum(a == b)\n Wa = Wa + Eq * 0.5\n return Wa / len(a) # hard comparisons\n\ndef relative_difference(a, b, reverse=False):\n \"\"\" Returns the mean relative difference between a and b.\n\n Args:\n a: Ballot representing one candidate (array-like).\n b: Ballot representing one candidate (array-like).\n reverse: If True, lower is better.\n \"\"\"\n a, b = np.array(a, dtype='float'), np.array(b, dtype='float')\n if reverse:\n num = b - a\n else:\n num = a - b\n denom = a + b\n s = np.divide(num, denom, out=np.zeros_like(num), where=denom!=0)\n return np.mean(s)\n################################################\n################################################\n","repo_name":"Didayolo/ranky","sub_path":"ranky/duel.py","file_name":"duel.py","file_ext":"py","file_size_in_byte":5368,"program_lang":"python","lang":"en","doc_type":"code","stars":33,"dataset":"github-code","pt":"14"} +{"seq_id":"73821617935","text":"from collections import OrderedDict\r\n\r\n\r\ndef is_stressful(subj):\r\n bad_guys = ['help', 'asp', 'asap', 'urgent']\r\n\r\n subject = subj.split()\r\n # case1:\r\n if subj.isupper():\r\n return True\r\n\r\n # case2:\r\n if subj[-3] == '!!!':\r\n return True\r\n\r\n # case3:\r\n for word in subject:\r\n stage_1 = [letter.lower().replace('.', '').replace('!', '') for letter in word if letter.isalpha()] # convert to lower case and get rid of non alpha\r\n clean_subj = ''.join(OrderedDict.fromkeys(stage_1))\r\n print(clean_subj)\r\n if clean_subj in bad_guys:\r\n return True\r\n return False\r\n\r\n#is_stressful(\"I neeed HELP\")\r\n#print( ' ---------- ')\r\n#is_stressful(\"H-E-L-P\")\r\n\r\n#print( ' ---------- ')\r\n#is_stressful(\"HHHEEEEEEEEELLP\")\r\n\r\nis_stressful(\"We need you A.S.A.P.!!\")","repo_name":"anton-shablyko/checkio_solutions","sub_path":"sendgrid/stressfull_subject.py","file_name":"stressfull_subject.py","file_ext":"py","file_size_in_byte":822,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"14"} +{"seq_id":"8637299598","text":"# 지역-지역번호, 성-이름처럼 dict 자료형을 만들었을 때, key값만 가지고 value값을 꺼내고 싶을 경우\n# 예시 1\ntext_dict = {'저기':'응?', '뭐해' : '그냥 있어', '볼래?' : '어디서?', '갈까?':'내가 갈게'}\n\nkey = input()\nprint(text_dict.get(key)) # get(key, 디폴트값) # 해당 key에 value가 없을 경우 디폴트값이 출력\n\n# 예시 2\nheroine_dict = {'제인 에어':'제인 에어', '광막한 사르가소 바다':'앙투아네트 메이슨', \n '폭풍의 언덕':'캐서린 언쇼' , '오만과 편견':'엘리자베스 베넷', '안네의 일기':'안네 프랑크'}\nkey = input()\nprint(heroine_dict.get(key))","repo_name":"WinterBlue16/Function-for-work","sub_path":"Data Structure/dict/6_Key 값으로 value값 꺼내기.py","file_name":"6_Key 값으로 value값 꺼내기.py","file_ext":"py","file_size_in_byte":687,"program_lang":"python","lang":"ko","doc_type":"code","stars":0,"dataset":"github-code","pt":"14"} +{"seq_id":"24693304248","text":"import nuke\nimport string\n\n#Select a tracked camera and this will create a duplicate projection camera with a freeze frame control.\n#Saves you having to remove all animation from a copied camera, plus gives you the advantage of changing the frozen frame later\n#Also means any updates to the camera tracker will be reflected in all your projection cameras too.\n#You can copy and paste any ProjectorCam node once it has been made.\n#It works with cameras tracked in Nuke, as well as imported cameras.\n\n#Made by David Emeny, inspired by a tutorial from FXPHD's Sean Devereaux\n\ndef MNE_ProjectorCam():\n\t\t\n\t#check if any nodes are selected\n\tif len(nuke.selectedNodes()) == 1:\n\t\t\n\t\t#get selected camera\n\t\tcam = nuke.selectedNode()\n\n\t\t#check it's a camera\n\t\tif cam.Class() == \"Camera\" or cam.Class() == \"Camera2\":\n\t\t\t\n\t\t\t#check it's not a ProjectorCam\n\t\t\tif cam['label'].value() != \"[value freezeFrame]\":\n\t\t\t\t\n\t\t\t\t#store its position\n\t\t\t\txx = cam['xpos'].value()\n\t\t\t\tyy = cam['ypos'].value()\n\t\t\t\n\t\t\t\t#copy the camera\n\t\t\t\tnuke.nodeCopy(cam['name'].value())\n\t\t\t\t#deselect first camera\n\t\t\t\tcam['selected'].setValue(False)\n\t\t\t\t#paste it into new reference\n\t\t\t\tnewCam = nuke.nodePaste(cam['name'].value())\n\t\t\t\t#show the panel in properties\n\t\t\t\tnewCam.showControlPanel()\n\t\t\t\t#change the name\n\t\t\t\tnewName = checkNodeName('Proj_Cam')\n\t\t\t\tnewCam['name'].setValue(newName)\n\t\t\t\t\n\t\t\t\t#Create a custom tab in the new camera node (which will show by default)\n\t\t\t\ttabKnob = nuke.Tab_Knob('Freeze Frame')\n\t\t\t\tnewCam.addKnob(tabKnob)\n\t\t\t\t\t\n\t\t\t\t#make the knob for the tab\n\t\t\t\tintKnob = nuke.Int_Knob('freezeFrame','Freeze on frame')\n\t\t\t\tintKnob.setValue(nuke.frame())\n\t\t\t\tupdateKnob = nuke.PyScript_Knob('Set to this frame')\n\t\t\t\tupdateKnob.setValue(\"nuke.thisNode()['freezeFrame'].setValue(nuke.frame())\")\n\t\t\t\t\n\t\t\t\t#add the new knobs\n\t\t\t\tnewCam.addKnob(intKnob)\n\t\t\t\tnewCam.addKnob(updateKnob)\n\t\t\t\t\n\t\t\t\t#set the freeze frame to show on the node's label\n\t\t\t\tnewCam['label'].setValue('[value freezeFrame]')\n\t\t\t\t\n\t\t\t\t#turn the new camera node an icy blue\n\t\t\t\tnewCam['tile_color'].setValue(int(0x84e0d0ff))\n\t\t\t\t\n\t\t\t\t#position it next to the original camera\n\t\t\t\tnewCam['xpos'].setValue(xx+200)\n\t\t\t\tnewCam['ypos'].setValue(yy)\n\t\t\t\t\n\t\t\t\t#link all values (and add the expression)\n\t\t\t\t\n\t\t\t\tif(cam.Class()==\"Camera2\"):\n\t\t\t\t\t#this is an imported camera, so do things differently\n\t\t\t\t\t#there are no expressions only curves. If there's no animation, the value is already there\n\t\t\t\t\t#so don't do anything\n\t\t\t\t\n\t\t\t\t\t#translate\n\t\t\t\t\tif(newCam['translate'].isAnimated()):\n\t\t\t\t\t\tnewCam['translate'].setExpression(\"curve(freezeFrame)\")\n\t\t\t\t\t\n\t\t\t\t\t#rotate\n\t\t\t\t\tif(newCam['rotate'].isAnimated()):\n\t\t\t\t\t\tnewCam['rotate'].setExpression(\"curve(freezeFrame)\")\n\t\t\t\t\t\n\t\t\t\t\t#win_translate\n\t\t\t\t\tif(newCam['win_translate'].isAnimated()):\n\t\t\t\t\t\tnewCam['win_translate'].setExpression(\"curve(freezeFrame)\")\n\t\t\t\t\t\n\t\t\t\t\t#win_scale\n\t\t\t\t\tif(newCam['win_scale'].isAnimated()):\n\t\t\t\t\t\tnewCam['win_scale'].setExpression(\"curve(freezeFrame)\")\n\n\t\t\t\t\t#focal\n\t\t\t\t\tif(newCam['focal'].isAnimated()):\n\t\t\t\t\t\tnewCam['focal'].setExpression(\"curve(freezeFrame)\")\n\t\t\t\t\t\n\t\t\t\t\t#haperture\n\t\t\t\t\tif(newCam['haperture'].isAnimated()):\n\t\t\t\t\t\tnewCam['haperture'].setExpression(\"curve(freezeFrame)\")\n\t\t\t\t\t\n\t\t\t\t\t#vaperture\n\t\t\t\t\tif(newCam['vaperture'].isAnimated()):\n\t\t\t\t\t\tnewCam['vaperture'].setExpression(\"curve(freezeFrame)\")\n\t\t\t\t\n\t\t\t\telse:\n\t\t\t\t\n\t\t\t\t\t#translate\n\t\t\t\t\ttempString = newCam['translate'].toScript() #get the expression string\n\t\t\t\t\ttempArray = string.split(tempString, \" \") #split into three for x,y,z\n\t\t\t\t\ttheExpr = tempArray[0][1:-1] + \"(freezeFrame)\" #take the x expressions, chop off the {} and add the frame number variable\n\t\t\t\t\tnewCam['translate'].setExpression(theExpr)\n\t\t\t\t\t\n\t\t\t\t\t#rotate\n\t\t\t\t\ttempString = newCam['rotate'].toScript() #get the expression string\n\t\t\t\t\ttempArray = string.split(tempString, \" \") #split into three for x,y,z\n\t\t\t\t\ttheExpr = tempArray[0][1:-1] + \"(freezeFrame)\" #take the x expressions, chop off the {} and add the frame number variable\n\t\t\t\t\tnewCam['rotate'].setExpression(theExpr)\n\t\t\t\t\t\n\t\t\t\t\t#win_translate\n\t\t\t\t\ttempString = newCam['win_translate'].toScript() #get the expression string\n\t\t\t\t\ttempArray = string.split(tempString, \" \") #split into two for x,y\n\t\t\t\t\ttheExpr = tempArray[0][1:-1] + \"(freezeFrame)\" #take the x expressions, chop off the {} and add the frame number variable\n\t\t\t\t\tnewCam['win_translate'].setExpression(theExpr)\n\t\t\t\t\t\n\t\t\t\t\t#win_scale\n\t\t\t\t\ttempString = newCam['win_scale'].toScript() #get the expression string\n\t\t\t\t\ttempArray = string.split(tempString, \" \") #split into two for x,y\n\t\t\t\t\ttheExpr = tempArray[0][1:-1] + \"(freezeFrame)\" #take the x expressions, chop off the {} and add the frame number variable\n\t\t\t\t\tnewCam['win_scale'].setExpression(theExpr)\n\t\t\t\t\n\t\t\t\t\t#focal\n\t\t\t\t\ttempString = newCam['focal'].toScript() #get the expression string\n\t\t\t\t\ttheExpr = tempString[1:-1] + \"(freezeFrame)\" #take the expression, chop off the {} and add the frame number variable\n\t\t\t\t\tnewCam['focal'].setExpression(theExpr)\n\t\t\t\t\t\n\t\t\t\t\t#haperture\n\t\t\t\t\ttempString = newCam['haperture'].toScript() #get the expression string\n\t\t\t\t\ttheExpr = tempString[1:-1] + \"(freezeFrame)\" #take the expression, chop off the {} and add the frame number variable\n\t\t\t\t\tnewCam['haperture'].setExpression(theExpr)\n\t\t\t\t\t\n\t\t\t\t\t#vaperture\n\t\t\t\t\ttempString = newCam['vaperture'].toScript() #get the expression string\n\t\t\t\t\ttheExpr = tempString[1:-1] + \"(freezeFrame)\" #take the expression, chop off the {} and add the frame number variable\n\t\t\t\t\tnewCam['vaperture'].setExpression(theExpr)\n\t\t\t\t\t\n\t\t\telse:\n\t\t\t\tnuke.message(\"You can't create a ProjectorCam out of another ProjectorCam. Select a tracked camera.\")\n\t\t\n\t\telse:\n\t\t\tnuke.message(\"The node you selected isn't a camera.\")\n\telse:\n\t\tnuke.message(\"Please select a camera node.\")\n\ndef checkNodeName(theName):\n\t#adds a number in brackets to the string if another node\n\t#exists with that name, otherwise just returns the string\n\ti = 1\n\tstillChecking = True\n\torigName = theName\n\twhile stillChecking:\n\t\talreadyUsed = False\n\t\tfor a in nuke.allNodes():\n\t\t\tif (a['name'].value()==(theName)):\n\t\t\t\talreadyUsed = True\t\n\t\t\t\tbreak\n\t\tif alreadyUsed:\n\t\t\ttheName = origName + ' (' + str(i) + ')'\n\t\t\ti = i+1\t\n\t\telse:\n\t\t\tstillChecking=False\n\t\n\treturn theName","repo_name":"tws0002/gs-code","sub_path":"apps/nuke/scripts/python/ProjectorCamDef.py","file_name":"ProjectorCamDef.py","file_ext":"py","file_size_in_byte":6241,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"14"} +{"seq_id":"28523686711","text":"'''\n Reduce #repeat specs to #compose specs\n'''\n\ndef parse_repeat(spec):\n\n if isinstance(spec, dict):\n return dict([\n (key, parse_repeat(val))\n if key != '#repeat'\n else get_reduced_spec(val)\n for key, val in spec.items()\n ])\n\n if isinstance(spec, list):\n return [\n parse_repeat(item) for item in spec\n ]\n\n return spec\n\ndef get_reduced_spec(body):\n return (\n '#compose',\n [body['operator']] * body['times']\n )\n","repo_name":"keplr-io/picard","sub_path":"picard/parser/repeat.py","file_name":"repeat.py","file_ext":"py","file_size_in_byte":525,"program_lang":"python","lang":"en","doc_type":"code","stars":52,"dataset":"github-code","pt":"14"} +{"seq_id":"18031540959","text":"import torch\nimport torch.nn as nn\n\ndef Encoder(input_size: int, output_size: int):\n\n dims = [input_size, 64, 32, 16, output_size]\n\n return nn.Sequential(\n nn.Linear(dims[0], dims[1]),\n nn.ReLU(inplace=True),\n nn.Linear(dims[1], dims[2]),\n nn.ReLU(inplace=True),\n nn.Linear(dims[2], dims[3]),\n nn.ReLU(inplace=True),\n nn.Linear(dims[3], dims[4])\n )\n\ndef Decoder(input_size: int, output_size: int):\n\n dims = [input_size, 16, 32, 64, output_size]\n\n return nn.Sequential(\n nn.Linear(dims[0], dims[1]),\n nn.ReLU(inplace=True),\n nn.Linear(dims[1], dims[2]),\n nn.ReLU(inplace=True),\n nn.Linear(dims[2], dims[3]),\n nn.ReLU(inplace=True),\n nn.Linear(dims[3], dims[4])\n )\n\nclass Autoeconder(nn.Module):\n def __init__(self, input_size: int, num_classes: int, device: object):\n super().__init__()\n\n self.encoder = Encoder(input_size, num_classes)\n self.decoder = Decoder(num_classes, input_size)\n\n self.device = device\n\n def forward(self, x):\n z = self.encoder(x)\n x_reconstructed = self.decoder(z)\n\n return z, x_reconstructed\n\nclass Loss_Contrastive(nn.Module):\n def __init__(self, margin: float, lambda_: float):\n super().__init__()\n\n self.criterion_reconstructed = nn.MSELoss(reduction=\"mean\")\n\n self.margin = margin\n self.lambda_ = lambda_\n\n self.eps = 1e-10\n\n def forward(self, x: torch.tensor, z: torch.tensor, x_reconstructed: torch.tensor, y: torch.tensor):\n loss_reconstructed = self.criterion_reconstructed(x, x_reconstructed)\n\n left_idx = torch.arange(0, int(x.size(0) / 2)).to(x.device)\n right_idx = torch.arange(int(x.size(0) / 2), int(x.size(0) / 2) * 2).to(x.device)\n dist = torch.sqrt(torch.sum(torch.pow(z[left_idx] - z[right_idx], 2), 1) + self.eps)\n in_same_class = torch.zeros_like(dist).to(x.device)\n in_same_class[y[left_idx] == y[right_idx]] = 1\n in_diff_class = torch.zeros_like(dist).to(x.device)\n in_diff_class[y[left_idx] != y[right_idx]] = 1\n loss_contrastive = torch.mean(in_same_class * dist + in_diff_class * nn.ReLU(inplace=True)(self.margin - dist))\n\n return loss_reconstructed + self.lambda_ * loss_contrastive, loss_reconstructed, loss_contrastive","repo_name":"KaiWangGitHub/BARS","sub_path":"smoothed_cade/classifier/autoencoder.py","file_name":"autoencoder.py","file_ext":"py","file_size_in_byte":2353,"program_lang":"python","lang":"en","doc_type":"code","stars":5,"dataset":"github-code","pt":"14"} +{"seq_id":"1577292285","text":"from data_preprocessing import Preprocess\r\nfrom sklearn.gaussian_process import GaussianProcessRegressor\r\nfrom sklearn.gaussian_process.kernels \\\r\n import RBF, WhiteKernel, RationalQuadratic, ExpSineSquared, ConstantKernel, WhiteKernel\r\nimport pandas as pd\r\nimport numpy as np\r\nfrom matplotlib import pyplot as plt\r\nfrom sklearn.metrics import mean_absolute_error\r\nfrom sklearn.model_selection import KFold\r\nfrom tqdm import tqdm\r\n\r\n\r\ndef TrainGPR():\r\n n_iter = 0\r\n kfold = KFold(n_splits=10, shuffle=True)\r\n kernel_info = []\r\n cv_test_mae = []\r\n cv_train_mae = []\r\n\r\n # KFold객체의 split( ) 호출하면 폴드 별 학습용, 검증용 데이터의 로우 인덱스를 array로 반환 \r\n for train_index, test_index in tqdm(kfold.split(np.array(scaled_1abcd))):\r\n # kfold.split( )으로 반환된 인덱스를 이용하여 학습용, 검증용 데이터 추출\r\n X_train, X_test = np.array(scaled_1abcd)[train_index], np.array(scaled_1abcd)[test_index]\r\n y_train, y_test = np.array(y_target)[train_index], np.array(y_target)[test_index]\r\n \r\n #학습 및 예측 \r\n gpr.fit(X_train,y_train)\r\n y_test_pred = gpr.predict(X_test)\r\n y_train_pred = gpr.predict(X_train)\r\n \r\n n_iter += 1 # CV 교차검증 (1~10 print)\r\n\r\n ###GetMAE()\r\n # CV 반복 마다 정확도 측정 \r\n test_mae = mean_absolute_error(y_test, y_test_pred)\r\n train_mae = mean_absolute_error(y_train, y_train_pred)\r\n\r\n print('\\n#{0} 교차 검증 test MAE :{1}, train MAE :{2}'\r\n .format(n_iter, test_mae, train_mae))\r\n print(\"Learned kernel: %s \\n\" % gpr.kernel_)\r\n \r\n kernel_info.append(gpr.kernel_) \r\n cv_test_mae.append(test_mae)\r\n cv_train_mae.append(train_mae)\r\n\r\n # 개별 iteration별 정확도를 합하여 평균 정확도 계산 \r\n mean_test_mae = np.mean(cv_test_mae)\r\n mean_train_mae = np.mean(cv_train_mae)\r\n \r\n return kernel_info, mean_test_mae, mean_train_mae\r\n\r\n\r\nif __name__ == \"__main__\":\r\n scaled_1abcd, y_target = Preprocess()\r\n\r\n sigma = 21; l_1 = 45; coef = 25; a = 0.4; l_2 = 10 \r\n k = sigma**2 * RBF(length_scale = l_1) + coef*RationalQuadratic(length_scale = l_2, alpha = a) + WhiteKernel()\r\n gpr = GaussianProcessRegressor(kernel = k,random_state = 128, n_restarts_optimizer=10, normalize_y=True)\r\n\r\n kernel_info, mean_test_mae, mean_train_mae = TrainGPR()\r\n print(\"\\n\")\r\n print(\"10-CV Test MAE:\", mean_test_mae)\r\n print(\"10-CV Train MAE:\", mean_train_mae)","repo_name":"miso-choi/BrainAgePrediction","sub_path":"GaussianProcessRegression.py","file_name":"GaussianProcessRegression.py","file_ext":"py","file_size_in_byte":2579,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"14"} +{"seq_id":"41428434567","text":"import torch\nimport torch.nn as nn\nimport torch.nn.functional as F\nimport torch.optim as optim\nfrom torch.utils.data import Dataset, DataLoader\nfrom torch.utils.data.sampler import SubsetRandomSampler\nfrom torchvision.datasets import DatasetFolder, ImageFolder\n\nimport numpy as np\nimport pandas as pd\nimport glob\nimport os\n\nimport matplotlib.pyplot as plt\nfrom matplotlib.pyplot import imread\n\nimport faulthandler\nfaulthandler.enable()\n\n# provides a nice UI element when running in a notebook, otherwise use \"import tqdm\" only\n# from tqdm import tqdm_notebook as tqdm\nfrom tqdm import tqdm\n\n# ============================================================================================== #\n# ============================================================================================== #\n# ============================================================================================== #\n# ======================================= Misc Functions ======================================= #\n# ============================================================================================== #\n# ============================================================================================== #\n# ============================================================================================== #\n\n# https://github.com/pytorch/pytorch/issues/7284\ndef discretize(tensor, boundaries):\n result = torch.zeros_like(tensor, dtype=torch.int32)\n for boundary in boundaries:\n result += (tensor > boundary).int()\n return result\n\ndef convert_to_categorical(regression_labels, num_labels=25):\n min_val = np.min(regression_labels)\n max_val = np.max(regression_labels)\n bins = np.linspace(min_val - 1e-5, max_val + 1e-5, num_labels)\n return np.digitize(regression_labels, bins)\n\ndef calculate_output_impartiality(y_true, y_pred): \n num_classes = len(y_true.unique())\n orig_classes, orig_counts = y_true.unique(return_counts=True) \n \n # calculate maximum possible entropy from y_true\n max_diversity = torch.ones(num_classes) * (1./num_classes)\n max_entropy = torch.distributions.Categorical(probs=max_diversity).entropy().item()\n \n # calculate class counts\n class_counts = []\n for i in orig_classes:\n count = 0\n for pred in y_pred:\n if pred == i:\n count += 1\n class_counts.append(count)\n\n # calculate y_pred entropy\n class_counts = torch.tensor(class_counts, dtype=torch.float) \n class_probs = class_counts / class_counts.sum()\n y_pred_entropy = torch.distributions.Categorical(probs=class_probs).entropy().item()\n \n output_bias = (max_entropy - y_pred_entropy) / max_entropy\n output_impartiality = 1 - output_bias\n return output_impartiality, y_pred_entropy, max_entropy\n\ndef extract_outputs(model, data, module):\n outputs = [] \n def hook(module, input, output):\n outputs.append(output) \n handle = module.register_forward_hook(hook) \n model(data)\n handle.remove()\n return torch.stack(outputs)\n\ndef norm_divergence_by_module(data, model, modules, device, regularizer_weight=None):\n \"\"\"\n returns the kld between the activations of the specified layer and a uniform pdf\n \"\"\"\n\n if not isinstance(modules, list):\n modules = [modules]\n\n data = torch.clamp(data, 0, 1)\n\n total_divergence = 0\n\n for module in modules: \n \n # extract layer activations as numpy array\n # NOTE: torch.relu is added just in case the layer is not actually ReLU'd beforehand\n # This is required for the summation and KL-Divergence calculation, otherwise nan\n layer_activations = torch.relu(torch.squeeze(extract_outputs(model=model, data=data, module=module)))\n \n # normalize over summation (to get a probability density)\n if len(layer_activations.size()) == 1:\n out_norm = (layer_activations / torch.sum(layer_activations)) + 1e-20 \n elif len(layer_activations.size()) == 2:\n out_norm = torch.sum(layer_activations, 0)\n out_norm = (out_norm / torch.sum(out_norm)) + 1e-20\n else:\n out_norm = (layer_activations / torch.sum(layer_activations)) + 1e-20 \n\n # create uniform tensor\n uniform_tensor = torch.ones(out_norm.shape).to(device)\n\n # normalize over summation (to get a probability density)\n uni_norm = uniform_tensor / torch.sum(uniform_tensor)\n \n # measure divergence between normalized layer activations and uniform distribution\n divergence = F.kl_div(input=out_norm.log(), target=uni_norm, reduction='sum')\n # divergence = F.kl_div(input=uni_norm.log(), target=out_norm, reduction='sum') \n \n # default regularizer if not provided\n if regularizer_weight is None:\n regularizer_weight = 0.005 \n \n if divergence < 0:\n print('The divergence was technically less than 0', divergence, layer_activations, out_norm)\n torch.save(data, 'logs/data.pt')\n torch.save(out_norm, 'logs/out_norm.pt')\n torch.save(uni_norm, 'logs/uni_norm.pt')\n # return None\n\n total_divergence += divergence\n \n return regularizer_weight * total_divergence\n\ndef eval_performance(model, originals, adversaries, targets):\n pert_output = model(adversaries)\n orig_output = model(originals)\n\n pert_pred = torch.argmax(pert_output, dim=1)\n orig_pred = torch.argmax(orig_output, dim=1)\n\n pert_correct = pert_pred.eq(targets.data).sum()\n orig_correct = orig_pred.eq(targets.data).sum()\n\n pert_acc = 100. * pert_correct / len(targets)\n orig_acc = 100. * orig_correct / len(targets)\n\n print('Perturbed Accuracy: {}/{} ({:.0f}%)'.format(pert_correct, len(targets), pert_acc))\n print('Original Accuracy: {}/{} ({:.0f}%)'.format(orig_correct, len(targets), orig_acc))\n \n return pert_acc, orig_acc\n\ndef eval_performance_reg(model, originals, adversaries, targets, classes, dataset):\n pert_output = model(adversaries)\n orig_output = model(originals)\n \n # MSE\n \n mse = F.mse_loss(pert_output, targets)\n \n # Accuracy\n\n pert_pred = discretize(pert_output, dataset.boundaries).view(-1)\n orig_pred = discretize(orig_output, dataset.boundaries).view(-1)\n\n pert_correct = pert_pred.eq(classes.data).sum()\n orig_correct = orig_pred.eq(classes.data).sum()\n \n pert_acc = 100. * pert_correct / len(classes)\n orig_acc = 100. * orig_correct / len(classes)\n\n print('MSE:{:.4f}'.format(mse))\n print('Perturbed Accuracy: {}/{} ({:.0f}%)'.format(pert_correct, len(classes), pert_acc))\n print('Original Accuracy: {}/{} ({:.0f}%)'.format(orig_correct, len(classes), orig_acc))\n \n return mse, pert_acc, orig_acc\n\ndef eval_performance_reg2(model, originals, adversaries, targets, binned_targets, num_labels):\n pert_output = model(adversaries)\n orig_output = model(originals)\n \n # MSE\n \n mse = F.mse_loss(pert_output, targets).item()\n \n # Accuracy\n\n pert_pred = torch.tensor(convert_to_categorical(pert_output.detach().cpu().numpy(), num_labels)).long().view(-1).cuda()\n orig_pred = torch.tensor(convert_to_categorical(orig_output.detach().cpu().numpy(), num_labels)).long().view(-1).cuda()\n\n pert_correct = pert_pred.eq(binned_targets.data).sum()\n orig_correct = orig_pred.eq(binned_targets.data).sum()\n \n pert_acc = 100. * pert_correct / len(binned_targets)\n orig_acc = 100. * orig_correct / len(binned_targets)\n\n print('MSE: {:.4f}'.format(mse))\n print('Perturbed Accuracy: {}/{} ({:.0f}%)'.format(pert_correct, len(binned_targets), pert_acc))\n print('Original Accuracy: {}/{} ({:.0f}%)'.format(orig_correct, len(binned_targets), orig_acc))\n \n return mse, pert_acc, orig_acc\n\ndef sample_1D_images(model, originals, adversaries, targets, num_samples = 5):\n orig_inputs = originals.cpu().detach().numpy()\n adv_examples = adversaries.cpu().detach().numpy()\n pert_output = model(adversaries)\n orig_output = model(originals)\n pert_pred = torch.argmax(pert_output, dim=1)\n orig_pred = torch.argmax(orig_output, dim=1)\n plt.figure(figsize=(15,8))\n for i in range(1, num_samples+1):\n plt.subplot(2, num_samples, i)\n plt.imshow(np.squeeze(orig_inputs[i]), cmap='gray') \n plt.title('true: {}'.format(targets[i].item()))\n plt.xticks([])\n plt.yticks([])\n\n plt.subplot(2, num_samples, num_samples+i)\n plt.imshow(np.squeeze(adv_examples[i]), cmap='gray')\n plt.title('adv_pred: {} - orig_pred: {}'.format(pert_pred[i].item(), orig_pred[i].item()))\n plt.xticks([])\n plt.yticks([])\n\n plt.tight_layout()\n plt.show()\n\ndef sample_3D_images(model, originals, adversaries, targets, classes, num_samples = 5):\n orig_inputs = originals.cpu().detach().numpy()\n adv_examples = adversaries.cpu().detach().numpy()\n pert_output = model(adversaries)\n orig_output = model(originals)\n pert_pred = torch.argmax(pert_output, dim=1)\n orig_pred = torch.argmax(orig_output, dim=1)\n plt.figure(figsize=(15,8))\n for i in range(1, num_samples+1):\n plt.subplot(2, num_samples, i)\n plt.imshow(np.transpose(np.squeeze(orig_inputs[i]), (1, 2, 0))) \n true_idx = targets[i].item()\n plt.title('true: {}'.format(classes[true_idx]))\n plt.xticks([])\n plt.yticks([])\n\n plt.subplot(2, num_samples, num_samples+i)\n plt.imshow(np.transpose(np.squeeze(adv_examples[i]), (1, 2, 0))) \n pred_idx = pert_pred[i].item()\n orig_idx = orig_pred[i].item()\n plt.title('adv_pred: {} - orig_pred: {}'.format(classes[pred_idx], classes[orig_idx]))\n plt.xticks([])\n plt.yticks([])\n\n plt.tight_layout()\n plt.show()\n\ndef sample_3D_images_reg(model, originals, adversaries, targets, classes, data_loader, num_samples = 5):\n orig_inputs = originals.cpu().detach().numpy()\n orig_targets = targets.cpu().detach().numpy()\n orig_classes = classes.cpu().detach().numpy()\n adv_examples = adversaries.cpu().detach().numpy()\n pert_output = model(adversaries)\n orig_output = model(originals)\n disc_pert = discretize(pert_output, data_loader.boundaries)\n disc_orig = discretize(orig_output, data_loader.boundaries)\n plt.figure(figsize=(15,8))\n for i in range(1, num_samples+1):\n plt.subplot(2, num_samples, i)\n plt.imshow(np.transpose(np.squeeze(orig_inputs[i]), (1, 2, 0))) \n plt.title('true: %.8f (%i)' % (targets[i], orig_classes[i]))\n plt.xticks([])\n plt.yticks([])\n\n plt.subplot(2, num_samples, num_samples+i)\n plt.imshow(np.transpose(np.squeeze(adv_examples[i]), (1, 2, 0))) \n plt.title('adv_pred: %.8f (%i) \\n orig_pred: %.8f (%i)' % (pert_output[i], disc_pert[i], orig_output[i], disc_orig[i]))\n plt.xticks([])\n plt.yticks([])\n\n plt.tight_layout()\n plt.show()\n\ndef generate_batch(dataset, num_per_class, device):\n '''\n creates a batch of inputs with a customizable number of instances for each class\n dataset : torchvision.dataset\n num_per_class : iterable containing the desired counts of each class\n example: torch.ones(num_classes) * 100\n '''\n \n def get_same_index(targets, label):\n '''\n Returns indices corresponding to the target label\n which the dataloader uses to serve downstream.\n '''\n label_indices = []\n for i in range(len(targets)):\n if targets[i] == label:\n label_indices.append(i)\n return label_indices\n\n data = []\n labels = []\n \n num_classes = len(np.unique(dataset.targets))\n \n for i in range(num_classes):\n \n target_indices = get_same_index(dataset.targets, i)\n class_batch_size = int(num_per_class[i])\n \n data_loader = torch.utils.data.DataLoader(dataset,\n batch_size=class_batch_size, \n sampler=SubsetRandomSampler(target_indices),\n shuffle=False)\n\n inputs, targets = next(iter(data_loader))\n\n data.append(inputs)\n labels.append(targets)\n\n inputs = torch.cat(data, dim=0).to(device)\n targets = torch.cat(labels, dim=0).to(device)\n \n return inputs, targets\n\ndef generate_batch_reg(dataset, num_per_class, device):\n '''\n creates a batch of inputs with a customizable number of instances for each class\n dataset : torchvision.dataset\n num_per_class : iterable containing the desired counts of each class\n example: torch.ones(num_classes) * 100\n '''\n \n def get_same_index(targets, label):\n '''\n Returns indices corresponding to the target label\n which the dataloader uses to serve downstream.\n '''\n label_indices = []\n for i in range(len(targets)):\n if targets[i] == label:\n label_indices.append(i)\n return label_indices\n\n all_data = []\n all_labels = []\n all_cats = []\n \n num_classes = len(np.unique(dataset.discrete_targets.cpu()))\n \n for i in range(num_classes):\n\n target_indices = get_same_index(dataset.discrete_targets, i)\n class_batch_size = int(num_per_class[i])\n \n data_loader = torch.utils.data.DataLoader(dataset,\n batch_size=class_batch_size, \n sampler=SubsetRandomSampler(target_indices),\n shuffle=False)\n\n if len(data_loader) > 0:\n inputs, targets, classes = next(iter(data_loader))\n\n all_data.append(inputs)\n all_labels.append(targets)\n all_cats.append(classes)\n\n inputs = torch.cat(all_data, dim=0).to(device)\n targets = torch.cat(all_labels, dim=0).to(device)\n classes = torch.cat(all_cats, dim=0).to(device)\n \n return inputs, targets, classes\n\ndef step_through_model(model, prefix=''):\n for name, module in model.named_children():\n path = '{}/{}'.format(prefix, name)\n if (isinstance(module, nn.Conv1d)\n or isinstance(module, nn.Conv2d)\n or isinstance(module, nn.Linear)): # test for dataset\n yield (path, name, module)\n else:\n yield from step_through_model(module, path)\n\ndef get_model_layers(model):\n layer_dict = {}\n idx=1\n for (path, name, module) in step_through_model(model):\n layer_dict[path + '-' + str(idx)] = module\n idx += 1\n return layer_dict \n\ndef get_dict_for_layer(dict, layer_name):\n return {k:v for k,v in dict.items() if layer_name in k[0]}\n\ndef get_pretrained_weights(model, device, directory=\"pretrained_models/mnist/\", get_any=False):\n latest_model = None\n if get_any:\n prev_models = glob.glob(directory+'*.*')\n else:\n m_type = model.__class__.__name__\n prev_models = glob.glob(directory+'*'+ m_type +'*.*')\n if prev_models:\n latest_model = max(prev_models, key=os.path.getctime)\n if (latest_model is not None): \n print('loading model', latest_model)\n model.load_state_dict(torch.load(latest_model, map_location=device)) \n return model\n else:\n print('no model found. train a new one.')\n return False\n\n# =============================================================================================== #\n# =============================================================================================== #\n# =============================================================================================== #\n# ========================================= Data Loader ========================================= #\n# =============================================================================================== #\n# =============================================================================================== #\n# =============================================================================================== #\n\nclass car_loader(Dataset):\n\n def __init__(self, \n target_csv_file, \n img_dir, \n device,\n transform=None, \n discretize_classes=True, \n num_classes=50):\n \"\"\"\n Args:\n target_csv_file (string) : Path to the csv file with steering angles.\n img_dir (string) : Directory with all the images.\n Returns:\n images : The images for training / inference.\n angles : The steering angle for each image\n classes : The discretized targets for the number of classes requested\n \"\"\"\n self.targets = torch.tensor(pd.read_csv(target_csv_file)['steering_angle'].values, dtype=torch.float32).to(device)\n self.discretize_classes = discretize_classes\n self.discrete_targets = self.targets.clone()\n self.root_dir = img_dir\n self.img_paths = glob.glob(os.path.join(img_dir) + '/*.png')\n self.transform = transform\n self.num_classes = num_classes\n \n if discretize_classes:\n \n # https://github.com/pytorch/pytorch/issues/7284\n def discretize(tensor, boundaries):\n result = torch.zeros_like(tensor, dtype=torch.int32)\n for boundary in boundaries:\n result += (tensor > boundary).int()\n return result\n \n min_bin = self.targets.min() # -1\n max_bin = self.targets.max() # 1\n self.boundaries = torch.linspace(min_bin, max_bin, num_classes).to(device)\n self.discrete_targets = discretize(self.targets, self.boundaries).int()\n\n def __len__(self):\n return len(self.targets)\n\n def __getitem__(self, idx):\n if torch.is_tensor(idx):\n idx = idx.tolist()\n \n # images\n paths = self.img_paths[idx]\n images = imread(paths)\n \n if self.transform:\n images = self.transform(images)\n \n # angles\n angles = self.targets[idx]\n \n if self.discretize_classes:\n classes = self.discrete_targets[idx]\n sample = (images, angles, classes)\n else:\n sample = (images, angles)\n\n return sample","repo_name":"fabriceyhc/nc_diversity_attacks","sub_path":"utils.py","file_name":"utils.py","file_ext":"py","file_size_in_byte":18259,"program_lang":"python","lang":"en","doc_type":"code","stars":9,"dataset":"github-code","pt":"14"} +{"seq_id":"32911130510","text":"'''\nCreated on Oct 12, 2016\n\n@author: user\n'''\nfrom robot.api.controll.ThreadControll import ThreadControll\nfrom robot.api.controll.EventsManager import EventsManager\nfrom robot.api import Constants\nimport sys\n\nclass SoundRecordController(ThreadControll):\n\n def __init__(self, sound_mgr):\n '''\n Microphone input record controller, starts recording\n SoundMgr2.py is stopping the recording\n '''\n self.sound_mgr = sound_mgr\n\n def wait_for_event_timeout(self, e, t):\n while not e.isSet():\n# print 'Sound Record tick'\n# print 'Demo mode tick' \n demo_mode_count = 0\n event_is_set = e.wait(t)\n \n if EventsManager.conversationListenToUser.isSet():\n self.sound_mgr.record_to_file(Constants.WAW_RECORD_INPUT)\n# print 'Sound Record End'\n sys.exit()\n ","repo_name":"jborovi/mbot","sub_path":"src/robot/api/controll/SoundRecordController.py","file_name":"SoundRecordController.py","file_ext":"py","file_size_in_byte":896,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"14"} +{"seq_id":"2869721710","text":"import numpy as np\nimport matplotlib.pyplot as plt\n\ndef plotPMF(data, bins = 50):\n heights, bins = np.histogram(data,bins=bins)\n heights = heights/sum(heights)\n plt.bar(bins[:-1],heights,width=(max(bins) - min(bins))/len(bins), color=\"blue\", alpha=0.5)\n plt.show()\n\ndef coinTossExperiment(heads, tails, ntrials=1000):\n ntosses = heads + tails\n diffs = []\n for i in range(ntrials):\n tosses_outcome = np.random.randint(0,2,ntosses)\n tosses_heads = np.sum(tosses_outcome)\n tosses_tails = ntosses - tosses_heads\n diff = (tosses_heads-tosses_tails)\n diffs.append(diff)\n\n return diffs\n\ndef pValue(diffs, observed_diff):\n count = 0\n for diff in diffs:\n if abs(diff) >= observed_diff:\n count += 1\n p = count/len(diffs)\n return p\n\ndef main():\n heads = 80\n tails = 110\n ntrials = 1000\n diffs = coinTossExperiment(heads, tails, ntrials)\n print('P value: ', pValue(diffs, abs(heads-tails)))\n\nif __name__ == '__main__':\n main()\n","repo_name":"nkdhruw/CoinTossExperiment","sub_path":"CoinTossExperiment.py","file_name":"CoinTossExperiment.py","file_ext":"py","file_size_in_byte":1022,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"14"} +{"seq_id":"38413218945","text":"from socket import *\nimport sys\nimport random\nimport os\nimport signal\nfrom tools.argparcer import ArgParcer\n#from client.listenerprocess import ListenerProcess\n#from client.listenerthread import ListenerThread\nfrom client.listenermultiprocess import ListenerMultiProcess\nfrom crypto.cryptor import Cryptor\nfrom multiprocessing import Process, Pipe\nimport threading\nfrom tools.commandtype import CommandType\nimport logging\n\n__author__ = 'bensoer'\n\n'''\nPARAMETERS\n\n-h host to connect to\n-p port to connect to host on\n\n-lp port to listen on\n\n-u [optional] set the username of the user. default is a random generated number\n-a set encryption and decrytion algorithm\n'''\n\narguments = sys.argv\n\n'if no arguments passed. print help'\nif len(arguments) <= 1:\n print(\"PyChat. A Console Chat Appliction Using Cryptographic Algorithms\")\n print(\"Parameters:\")\n print(\"\\t -h : The host to connect to\")\n print(\"\\t -p : The port to the host to connect to\")\n print(\"\\t -lp : The port to receive messages over\")\n print(\"\\t -u : Username for this user when sending message (optional. default uses a number)\")\n print(\"\\t -a : Name of the Algorithm to be used in message transmission\")\n print(\"\\t -v: An optional verification hash to be used and sent along with transmission.\")\n exit(0)\n\n'fetch the arguments we need'\nhost = ArgParcer.getValue(arguments, \"-h\")\nport = int(ArgParcer.getValue(arguments, \"-p\"))\nlisteningPort = int(ArgParcer.getValue(arguments, \"-lp\"))\nusername = ArgParcer.getValue(arguments, \"-u\")\nalgorithm = ArgParcer.getValue(arguments, \"-a\")\ndebugMode = ArgParcer.keyExists(arguments, \"--DEBUG\")\nverificationHash = ArgParcer.getValue(arguments, \"-v\")\n\n'configure username if it was defined'\nif username == \"\":\n username = str(random.random())\n\n'configure logging'\nlogger = logging.getLogger('pychat')\nlogger.setLevel(logging.DEBUG)\nformatter = logging.Formatter('%(asctime)s(%(levelname)s) [%(filename)s:%(lineno)s:%(funcName)s()] - %(message)s',\n \"%H:%M:%S\")\n\n#console logging channel\nconsoleChannel = logging.StreamHandler()\nconsoleChannel.setFormatter(formatter)\nif debugMode:\n consoleChannel.setLevel(logging.DEBUG)\nelse:\n consoleChannel.setLevel(logging.INFO)\n\n#file logging channel\nfileChannel = logging.FileHandler(\"debug-\" + str(os.getpid()) + \".log\")\nfileChannel.setFormatter(formatter)\nfileChannel.setLevel(logging.DEBUG)\n\nlogger.addHandler(consoleChannel)\nlogger.addHandler(fileChannel)\n\nlogger.debug(\"Logging Initialized\")\n\n\n'create the socket to communicate over'\nclientSocket = socket(AF_INET, SOCK_DGRAM)\nclientSocket.bind(('localhost', listeningPort))\nclientSocket.setsockopt(SOL_SOCKET, SO_REUSEADDR, 1)\nclientSocket.setsockopt(SOL_SOCKET, SO_REUSEPORT, 1)\nlogger.debug(\"Communication Sockets Initialized\")\n\n'setup cryptor'\ncryptor = Cryptor()\ncryptor.setArguments(arguments)\ncryptor.setAlgorithm(algorithm)\nif cryptor.testAlgorithm():\n cryptor.loadAlgorithm()\nif verificationHash != \"\":\n cryptor.setHash(verificationHash)\n cryptor.loadHash()\nlogger.debug(\"Cryptor Algorithm Setup\")\n\n#listenerMultiProcess = ListenerMultiProcess(clientSocket, cryptor)\nparent_conn, child_conn = Pipe()\n\n'setup the listener multiprocess - passing it the pipe'\ndef bootstrapper(child_conn_pipe):\n components = child_conn_pipe.recv()\n #child_conn_pipe.close()\n listenerMultiProcess = ListenerMultiProcess(components[0], components[1], child_conn_pipe)\n listenerMultiProcess.start()\n # safety measure\n exit(0)\nlogger.debug(\"Bootstrapping Setup For Multiprocessor\")\n\n'''setup handler for pipe commands from the child multiprocess back to us. This is needed so as to keep the crypto\nobject in sync'''\ndef recv_handler():\n while True:\n back_command = parent_conn.recv()\n #print(back_command)\n command_code = back_command[0]\n\n # handler manipulation of cryptor here\n if command_code == CommandType.GiveFirstMessage:\n writeToConsole = cryptor.giveFirstMessage(back_command[1])\n parent_conn.send([writeToConsole])\n elif command_code == CommandType.GetInitializationMessage:\n message = cryptor.getInitializationMessage()\n parent_conn.send([message])\n elif command_code == CommandType.Decrypt:\n message = cryptor.decrypt(back_command[1])\n parent_conn.send([message])\n elif command_code == CommandType.Encrypt:\n message = cryptor.encrypt(back_command[1])\n parent_conn.send([message])\n else:\n print(\"Unknown Command Received\")\nlogger.debug(\"Handler Thread For Listening and Cryptor Synchronization Setup\")\n\n'start the listener'\n#listenerThread = ListenerThread(clientSocket, cryptor)\n#listenerThread.start()\n#multiprocess = Process(target=bootstrapper, args=(listenerMultiProcess))\nmultiprocess = Process(target=bootstrapper, args=(child_conn,))\nmultiprocess.start()\nlogger.debug(\"Started Listening Multiprocess\")\n\n'start the thread to handle pipe commands'\nparent_conn.send([clientSocket, cryptor])\nt = threading.Thread(target=recv_handler)\nt.daemon = True # making it a daemon for some reason automatically deals with killing it once the main thread dies\nt.start()\nlogger.debug(\"Starting Handler Thread\")\n\n\n'now fork to put the listener on a seperate process that won\\'t block us'\n'''pid = os.fork()\nif pid <= 0:\n\n if pid < 0:\n 'in case this is the error condition'\n print(\"SystemError Generating Child Process. Terminating\")\n exit(1)\n elif pid == 0:\n 'else we are in the child then'\n listenerProcess = ListenerProcess(clientSocket, cryptor)\n listenerProcess.start()\n 'although this line will never be hit. its good to have as insurance'\n exit(0)\nelse:\n 'if program makes it here. We must be in the parent'\n'''\n\n'setup Ctrl+C handler'\ndef signal_handler(signo, frame):\n print('Terminating Chat Engine')\n #os.kill(pid, signal.SIGTERM)\n parent_conn.close()\n multiprocess.terminate()\n print('Successfully Terminated Listener Process')\n print('Now Self Terminating')\n exit(0)\n\nsignal.signal(signal.SIGINT, signal_handler)\nlogger.debug(\"Setup Signal Handler For Ctrl+C\")\n\n'get and send the initialization message from the algorithm'\ninitMessage = cryptor.getInitializationMessage()\nif len(initMessage) > 0:\n clientSocket.sendto(initMessage, (host, port))\nlogger.debug(\"Fetched And Sent Initialization Message From Algorithm\")\n\nprint(\"Setup Configured. Chat has Been Configured\")\n\n'now start allowing user to type'\nwhile True:\n message = input()\n\n if message == \"exit\":\n 'honey i killed the kids...'\n print('Terminating Chat Engine')\n #os.kill(pid, signal.SIGTERM)\n #listenerThread.stopThread()\n parent_conn.close()\n multiprocess.terminate()\n print('Successfully Terminated Listener Process')\n print('Now Self Terminating')\n break\n else:\n message = username + \": \" + message\n encryptedMessage = cryptor.encrypt(message)\n clientSocket.sendto(encryptedMessage, (host, port))","repo_name":"bensoer/pychat","sub_path":"pychat.py","file_name":"pychat.py","file_ext":"py","file_size_in_byte":7093,"program_lang":"python","lang":"en","doc_type":"code","stars":2,"dataset":"github-code","pt":"14"} +{"seq_id":"22026753074","text":"def score(game):\n game = game.lower()\n result = 0\n frame = 1\n in_first_half = True\n frame_limit = 10\n for i in range(len(game)):\n if is_spare(game[i]):\n result += get_value(\"x\") - last\n else:\n result += get_value(game[i])\n\n last = get_value(game[i])\n\n if frame < frame_limit and last == get_value(\"x\"):\n next_score = get_value(game[i+1])\n if is_spare(game[i]):\n result += next_score\n elif game[i] == 'x':\n result += next_score\n if is_spare(game[i+2]):\n result += get_value(\"x\") - next_score\n else:\n result += get_value(game[i+2])\n\n if not in_first_half:\n frame += 1\n\n in_first_half = not in_first_half\n\n if game[i] == 'x':\n in_first_half = True\n frame += 1\n return result\n\ndef get_value(char):\n if char in ['x' , '/']:\n return 10\n elif char == '-':\n return 0\n elif int(char) in range(1, 10):\n return int(char)\n\n raise ValueError()\n\ndef is_spare(score):\n return score == '/'\n","repo_name":"CodecoolBP20173/pbwp-4th-si-bowling-refactor-jozsaVilmos","sub_path":"bowling.py","file_name":"bowling.py","file_ext":"py","file_size_in_byte":1167,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"14"} +{"seq_id":"41753125641","text":"\"\"\"\n## url = https://www.codewars.com/kata/55c45be3b2079eccff00010f\n## kata names = Your Order, Please\n### kata level = 6 kyu\n\n### Description:\n\nYour task is to sort a given string. Each word in the string will contain a single number. This number is the position the word should have in the result.\n\nNote: Numbers can be from 1 to 9. So 1 will be the first word (not 0).\n\nIf the input string is empty, return an empty string. The words in the input String will only contain valid consecutive numbers.\n\nExamples\n\n\"is2 Thi1s T4est 3a\" --> \"Thi1s is2 3a T4est\"\n\"4of Fo1r pe6ople g3ood th5e the2\" --> \"Fo1r the2 g3ood 4of th5e pe6ople\"\n\"\" --> \"\"\n\n\"\"\"\ndef order(sentence):\n arr = sentence.split()\n lastOrder = \"\"\n newDict = {\"1\":None, \"2\":None, \"3\":None, \"4\":None,\"5\":None, \"6\":None, \"7\":None, \"8\":None, \"9\":None}\n for i in arr:\n for j in i:\n if j.isdigit() and int(j) <= 9:\n newDict[j] = i\n sortedDict = sorted(newDict.items())\n \n for k in sortedDict:\n if k[1] != None:\n lastOrder = lastOrder + k[1] + \" \"\n \n lastOrder = lastOrder[:-1] \n return lastOrder\n","repo_name":"yunuscanunal/CodeWars","sub_path":"yourOrderPlease.py","file_name":"yourOrderPlease.py","file_ext":"py","file_size_in_byte":1146,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"14"} +{"seq_id":"5623528601","text":"from itertools import product\n\n\ndef parse(filename):\n data = None\n with open(filename, 'r') as infile:\n data = infile.read().strip()\n lines = data.split('\\n')\n\n template = lines[0]\n pairs = {line.split(' -> ')[0]:line.split(' -> ')[1] for line in lines[2:]}\n return (template, pairs)\n\n\ndef verify_sample(actual_vals, expected_vals):\n if isinstance(actual_vals, list):\n if len(actual_vals) != len(expected_vals):\n print('ERROR: Count of actual values != count of expected values:', end=' ')\n print(f'len(actual_vals)={len(actual_vals)}, len(expected_vals)={len(expected_vals)}')\n return False\n else:\n actual_vals = [actual_vals]\n expected_vals = [expected_vals]\n \n for a,e in zip(actual_vals, expected_vals):\n if a != e:\n print(f'FAILED: Expected {e} got {a}')\n return False\n \n print('SUCCESS')\n return True\n\n\ndef part_one(template, pairs, using_sample=False):\n print(f'Running Part 1:')\n \n elem_set = set(pairs.values())\n elem_counts = {elem:template.count(elem) for elem in elem_set}\n \n total_steps = 10\n for __ in range(total_steps):\n new_template = ''\n for i,(elem1,elem2) in enumerate(zip(template[:-1], template[1:])):\n result = pairs[elem1 + elem2]\n new_template += f'{elem1}{result}'\n if i >= len(template) - 2:\n new_template += f'{elem2}'\n elem_counts[result] += 1\n template = new_template\n \n diff = max(count for count in elem_counts.values()) - min(count for count in elem_counts.values())\n\n if using_sample:\n verify_sample(diff, 1588)\n \n print(f' Most common - Least common = {diff}\\n')\n\n\ndef part_two(template, pairs, using_sample=False):\n print(f'Running Part 2:')\n \n elem_set = set(pairs.values())\n elem_pairs = [f'{e1}{e2}' for e1,e2 in list(product(elem_set, repeat=2))]\n pair_counts = {pair:template.count(pair) for pair in elem_pairs}\n\n total_steps = 40\n for __ in range(total_steps):\n for (e1,e2),count in {p:c for p,c in pair_counts.copy().items() if c > 0}.items():\n result = pairs[f'{e1}{e2}']\n pair_counts[f'{e1}{result}'] += count\n pair_counts[f'{result}{e2}'] += count\n pair_counts[f'{e1}{e2}'] -= count\n \n elem_counts = {e:[0,0] for e in elem_set}\n for (e1,e2),count in {p:c for p,c in pair_counts.items() if c > 0}.items():\n elem_counts[e1][0] += count\n elem_counts[e2][1] += count\n \n diff = max(max(counts) for counts in elem_counts.values()) - min(max(counts) for counts in elem_counts.values())\n \n if using_sample:\n verify_sample(diff, 2188189693529)\n \n print(f' Most common - Least common = {diff}\\n')\n\n\nif __name__ == '__main__':\n filename = 'input.in'\n template, pairs = parse(filename)\n\n part_one(template, pairs, filename == 'sample.in')\n\n part_two(template, pairs, filename == 'sample.in')","repo_name":"alexcwarren/AdventOfCode","sub_path":"src/puzzles/2021/Day14/ExtendedPolymerization.py","file_name":"ExtendedPolymerization.py","file_ext":"py","file_size_in_byte":3011,"program_lang":"python","lang":"en","doc_type":"code","stars":2,"dataset":"github-code","pt":"14"} +{"seq_id":"26422850700","text":"## Author: Peizhi\n############################\n## Genereate facenet encodings for all the images\n## Code Used: https://github.com/timesler/facenet-pytorch\n\nimport os\nfrom tqdm import tqdm\nimport cv2\nimport matplotlib.pyplot as plt\nimport numpy as np\nfrom PIL import Image\n\nfrom facenet_pytorch import MTCNN, InceptionResnetV1\n\nimport torch\n\n# Setup PyTorch\nif torch.cuda.is_available():\n device = torch.device(\"cuda:0\")\n torch.cuda.set_device(device)\n print('CUDA is available')\nelse:\n device = torch.device(\"cpu\")\n print('CUDA is not available')\n\n\nresnet = InceptionResnetV1(pretrained='vggface2').eval()\nmtcnn = MTCNN(image_size=224)\n\n##########\n## CelebA\n\ndata_path = '../datasets/CelebA/images224x224/{}.jpg'\nsave_path = '../datasets/CelebA/facenet_encodings/'\ntry:\n os.mkdir(save_path)\nexcept:\n pass\nsave_path += '{}.npy'\n\nf_names = os.listdir(data_path[:-6])\nfor idx in tqdm(range(len(f_names))):\n f_name = f_names[idx]\n if f_name.endswith('.jpg'):\n f_index = f_name[:-4]\n \n # Skip the processed files\n if os.path.isfile(save_path.format(f_index)):\n continue\n \n # Load image\n img = Image.open(data_path.format(f_index))\n\n # Crop image and convert to [1, C, H, W] tensor\n try:\n img_cropped = mtcnn(img)[None]\n \n # Get face embedding\n img_embedding = resnet(img_cropped)\n \n # Save face embedding\n np.save(save_path.format(f_index), img_embedding.detach().numpy())\n \n except:\n print('Bad file ', f_name)\n\n\n##########\n## FFHQ\n\ndata_path = '../datasets/FFHQ/images224x224/{}.png'\nsave_path = '../datasets/FFHQ/facenet_encodings/'\ntry:\n os.mkdir(save_path)\nexcept:\n pass\nsave_path += '{}.npy'\n\nf_names = os.listdir(data_path[:-6])\nfor idx in tqdm(range(len(f_names))):\n f_name = f_names[idx]\n if f_name.endswith('.png'):\n f_index = f_name[:-4]\n \n # Skip the processed files\n if os.path.isfile(save_path.format(f_index)):\n continue\n \n # Load image\n img = Image.open(data_path.format(f_index))\n\n # Crop image and convert to [1, C, H, W] tensor\n try:\n img_cropped = mtcnn(img)[None]\n\n # Get face embedding\n img_embedding = resnet(img_cropped)\n\n # Save face embedding\n np.save(save_path.format(f_index), img_embedding.detach().numpy())\n \n except:\n print('Bad file ', f_name)\n\n\n","repo_name":"Yuhengw/NEO-3DF","sub_path":"data_preparation/facenet_encoding.py","file_name":"facenet_encoding.py","file_ext":"py","file_size_in_byte":2542,"program_lang":"python","lang":"en","doc_type":"code","dataset":"github-code","pt":"14"} +{"seq_id":"3672528087","text":"# Author: Hayden Lao\n# Script Name: get_train_data\n# Created Date: Sep 5th 2019\n# Description: Construct train data for LFM model\n\nimport os\n\n\ndef get_movie_avg_rating(input_path, sep=\",\"):\n \"\"\"\n Extract average rating for each movie\n :param input_path: Movie Rating file path[str]\n :param sep: Separation delimiter[str]\n :return: Dictionary with key as movie id and value as average rating[dict]\n \"\"\"\n if not os.path.exists(input_path):\n print(\"No such file\")\n return {}\n with open(input_path, encoding='UTF-8') as file:\n line_num = 0\n rating_dict = {}\n for line in file:\n if line_num == 0:\n line_num += 1\n continue\n movie_rating = line.strip().split(sep)\n if len(movie_rating) == 4:\n movie_id = movie_rating[1]\n rating = movie_rating[2]\n else:\n continue\n if movie_id not in rating_dict.keys():\n rating_dict[movie_id] = [1, float(rating)]\n else:\n rating_dict[movie_id][0] += 1\n rating_dict[movie_id][1] += float(rating)\n line_num += 1\n for movie in rating_dict.keys():\n rating_dict[movie] = round(rating_dict[movie][1] / rating_dict[movie][0], 2)\n return rating_dict\n\n\ndef get_train_data(input_path, threshold, sep=\",\"):\n \"\"\"\n Make train data based on rating behavior\n :param input_path: Movie rating file path[str]\n :param threshold: Threshold for defining positive data[int/float]\n :param sep: Separation delimiter[str]\n :return: A list contains tuples with users movies and labels[list]\n \"\"\"\n if not os.path.exists(input_path):\n print(\"No such file\")\n return {}\n train_list = []\n rating_dict = get_movie_avg_rating(input_path)\n with open(input_path, encoding=\"UTF-8\") as file:\n pos_dict, neg_dict = {}, {}\n line_num = 0\n for line in file:\n if line_num == 0:\n line_num += 1\n continue\n movie_rating = line.strip().split(sep)\n if len(movie_rating) == 4:\n user_id = movie_rating[0]\n movie_id = movie_rating[1]\n rating = movie_rating[2]\n else:\n continue\n if float(rating) >= threshold:\n if user_id not in pos_dict.keys():\n pos_dict[user_id] = [(movie_id, 1)]\n else:\n pos_dict[user_id].append((movie_id, 1))\n else:\n if user_id not in neg_dict.keys():\n neg_dict[user_id] = [(movie_id, rating_dict.get(movie_id, 0))]\n else:\n neg_dict[user_id].append((movie_id, rating_dict.get(movie_id, 0)))\n for user in pos_dict.keys():\n data_num = min(len(pos_dict[user]), len(neg_dict.get(user, [])))\n if data_num > 0:\n # Construct label proportion to 1:1\n neg_dict[user] = sorted(neg_dict[user], key=lambda element: element[1], reverse=True)[:data_num]\n train_list += [(user, action[0], action[1]) for action in pos_dict[user]]\n train_list += [(user, action[0], 0) for action in neg_dict[user]]\n else:\n continue\n return train_list\n","repo_name":"hayden-lo/recommendation","sub_path":"models/lfm/get_train_data.py","file_name":"get_train_data.py","file_ext":"py","file_size_in_byte":3326,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"14"} +{"seq_id":"31816007394","text":"import torch.nn.functional as F\nimport torch\nimport matplotlib.pyplot as plt\nfrom torchvision import transforms\n\nkernalx = torch.Tensor([\n [-1, 0, 1],\n [-2, 0, 2],\n [-1, 0, 1]\n]).unsqueeze(0).unsqueeze(0)\nkernaly = torch.Tensor([\n [-1, -2, -1],\n [ 0, 0, 0],\n [ 1, 2, 1]\n]).unsqueeze(0).unsqueeze(0)\n\ndef SobelConv(imgs_gray_tensor):\n gx = F.conv2d(input = imgs_gray_tensor, weight = kernalx, padding = 1)\n gy = F.conv2d(input = imgs_gray_tensor, weight = kernaly, padding = 1)\n g = torch.sqrt(gx**2+gy**2)\n plot(imgs_gray_tensor.squeeze(0), g.squeeze(0))\n return g\n\n \ndef plot(*imgs_tensor):\n unloader = transforms.ToPILImage()\n total = len(imgs_tensor)\n fig, ax = plt.subplots(total//3+1,3, figsize=(15, 5*(total//3+1)))\n for i in range(total):\n img = unloader(imgs_tensor[i])\n ax[i].imshow(img, cmap ='gray')\n plt.show()\n\n\n","repo_name":"ivy266/ZJU_IDRB_41","sub_path":"paper_recurrence/ResNet18/tools/Sobel.py","file_name":"Sobel.py","file_ext":"py","file_size_in_byte":897,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"14"} +{"seq_id":"74773789135","text":"n, m, h, k = map(int, input().split())\nS = input()\nXY = set()\nfor _ in range(m):\n x, y = map(int, input().split())\n XY.add((x, y))\n\nnow = [0, 0]\nfor i in range(n):\n if S[i] == \"R\":\n now[0] += 1\n elif S[i] == \"L\":\n now[0] -= 1\n elif S[i] == \"U\":\n now[1] += 1\n elif S[i] == \"D\":\n now[1] -= 1\n\n h -= 1\n if h < 0:\n print(\"No\")\n exit()\n else:\n if tuple(now) in XY:\n if h < k:\n XY.discard(tuple(now))\n h = k\n\nprint(\"Yes\")\n\n","repo_name":"Shunta-Shimizu/AtCoder","sub_path":"ABC/303_c.py","file_name":"303_c.py","file_ext":"py","file_size_in_byte":530,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"14"} +{"seq_id":"24792118895","text":"import numpy as np\nfrom PIL import Image\nfrom matplotlib import pyplot as plt\nimport skfmm\n\n\"\"\"\nintersection\nxmin: 940.8 xmax: 1066.7\nymin: 935.8 ymax: 1035.1\nsize is 931 * 731 (x * y)\ndx, dy is 0.13523093447905488 0.13584131326949378\nintersection fmm downsampled size is (466, 366)\n\"\"\"\n\n# intersection_obs = np.load(\"/home/anjianl/Desktop/project/optimized_dp/data/map/obstacle_map/intersection_obs_map.npy\").T\n# # intersection_curbs = np.load(\"/home/anjianl/Desktop/project/optimized_dp/data/map/obstacle_map/intersection_curbs.npy\")\n# intersection_x_min, intersection_x_max = 940.8, 1066.7\n# intersection_y_min, intersection_y_max = 935.8, 1035.1\n# intersection_dx, intersection_dy = (intersection_x_max - intersection_x_min) / np.shape(intersection_obs)[0], (intersection_y_max - intersection_y_min) / np.shape(intersection_obs)[1]\n#\n# print(\"intersection\")\n# print(\"xmin: \", intersection_x_min, \"xmax: \", intersection_x_max)\n# print(\"ymin: \", intersection_y_min, \"ymax: \", intersection_y_max)\n# print(\"size is \", np.shape(intersection_obs)[0], np.shape(intersection_obs)[1])\n# print(\"dx, dy is\", intersection_dx, intersection_dy)\n#\n# # Compute fmm distance\n# intersection_fmm_prepare = intersection_obs\n# intersection_fmm_prepare[intersection_obs == 0] = - 1\n# intersection_fmm_prepare[intersection_obs == 1] = 1\n# intersection_fmm_map = skfmm.distance(intersection_fmm_prepare, dx=[intersection_dx, intersection_dy])\n# intersection_fmm_map = - intersection_fmm_map\n# # Add buffer area for obstacle map, margin = 1m\n# intersection_obs_buffer = np.zeros(np.shape(intersection_fmm_map))\n# intersection_obs_buffer[intersection_fmm_map <= 1] = 1\n# intersection_obs_buffer[intersection_fmm_map > 1] = -1\n# intersection_buffer_fmm_map = skfmm.distance(intersection_obs_buffer, dx=[intersection_dx, intersection_dy])\n# intersection_buffer_fmm_map = - intersection_buffer_fmm_map\n#\n# #############################\n# # # Without buffer area\n# # np.save(\"/home/anjianl/Desktop/project/optimized_dp/data/map/obstacle_map/intersection_fmm_map.npy\", intersection_fmm_map)\n# #\n# # intersection_fmm_map_downsampled = intersection_fmm_map[::2, ::2]\n# # print(\"intersection fmm downsampled size is\", np.shape(intersection_fmm_map_downsampled))\n# # np.save(\"/home/anjianl/Desktop/project/optimized_dp/data/map/obstacle_map/intersection_fmm_map_downsampled.npy\", intersection_fmm_map_downsampled)\n# #\n# # intersection_valfunc = np.zeros((466, 366, 24, 39))\n# # for i in range(24):\n# # for j in range(39):\n# # intersection_valfunc[:, :, i, j] = intersection_fmm_map_downsampled\n# #\n# # # TODO, reverse y axis, I don't know why\n# # intersection_valfunc_correctify = np.zeros(np.shape(intersection_valfunc))\n# # for i in range(366):\n# # intersection_valfunc_correctify[:, i, :, :] = intersection_valfunc[:, 365 - i, :, :]\n# #\n# # np.save(\"/home/anjianl/Desktop/project/optimized_dp/data/map/value_function/intersection_valfunc.npy\", intersection_valfunc)\n# # np.save(\"/home/anjianl/Desktop/project/optimized_dp/data/map/value_function/intersection_valfunc_correct.npy\", intersection_valfunc_correctify)\n#\n# #############################\n# # With buffer area\n# np.save(\"/home/anjianl/Desktop/project/optimized_dp/data/map/obstacle_map/intersection_fmm_map_buffer_1m.npy\", intersection_buffer_fmm_map)\n#\n# intersection_buffer_fmm_map_downsampled = intersection_buffer_fmm_map[::2, ::2]\n# print(\"intersection fmm buffer downsampled size is\", np.shape(intersection_buffer_fmm_map_downsampled))\n# # np.save(\"/home/anjianl/Desktop/project/optimized_dp/data/map/obstacle_map/intersection_fmm_map_downsampled_buffer_1.5.npy\", intersection_buffer_fmm_map_downsampled)\n#\n# intersection_valfunc_buffer = np.zeros((466, 366, 24, 39))\n# for i in range(24):\n# for j in range(39):\n# intersection_valfunc_buffer[:, :, i, j] = intersection_buffer_fmm_map_downsampled\n#\n# # TODO, reverse y axis, I don't know why\n# intersection_valfunc_buffer_correctify = np.zeros(np.shape(intersection_valfunc_buffer))\n# for i in range(366):\n# intersection_valfunc_buffer_correctify[:, i, :, :] = intersection_valfunc_buffer[:, 365 - i, :, :]\n#\n# np.save(\"/home/anjianl/Desktop/project/optimized_dp/data/map/value_function/intersection_valfunc_correct_buffer_1m.npy\", intersection_valfunc_buffer_correctify)\n\n# plt.imshow(intersection_fmm_map_downsampled.T)\n# plt.show()\n\n##################################################################################################################################\n\n# \"\"\"\n# roundabout\n# xmin: 956.7 xmax: 1073.4\n# ymin: 954.0 ymax: 1046.0\n# size is 929 * 734 (x * y)\n# dx, dy is 0.12561894510226054 0.12534059945504086\n# roundabout fmm downsampled size is (465, 367)\n# \"\"\"\n\nroundabout_obs = np.load(\"/home/anjianl/Desktop/project/optimized_dp/data/map/obstacle_map/roundabout_obs_map.npy\").T\n# roundabout_curbs = np.load(\"/home/anjianl/Desktop/project/optimized_dp/data/map/obstacle_map/roundabout_curbs.npy\")\nroundabout_x_min, roundabout_x_max = 956.7, 1073.4\nroundabout_y_min, roundabout_y_max = 954.0, 1046.0\nroundabout_dx, roundabout_dy = (roundabout_x_max - roundabout_x_min) / np.shape(roundabout_obs)[0], (roundabout_y_max - roundabout_y_min) / np.shape(roundabout_obs)[1]\n\nprint(\"roundabout\")\nprint(\"xmin: \", roundabout_x_min, \"xmax: \", roundabout_x_max)\nprint(\"ymin: \", roundabout_y_min, \"ymax: \", roundabout_y_max)\nprint(\"size is \", np.shape(roundabout_obs)[0], np.shape(roundabout_obs)[1])\nprint(\"dx, dy is\", roundabout_dx, roundabout_dy)\n\nroundabout_fmm_prepare = roundabout_obs\nroundabout_fmm_prepare[roundabout_obs == 0] = - 1\nroundabout_fmm_prepare[roundabout_obs == 1] = 1\nroundabout_fmm_map = skfmm.distance(roundabout_fmm_prepare, dx=[roundabout_dx, roundabout_dy])\nroundabout_fmm_map = - roundabout_fmm_map\n# np.save(\"/home/anjianl/Desktop/project/optimized_dp/data/map/obstacle_map/roundabout_fmm_map.npy\", roundabout_fmm_map)\n# Add buffer area for obstacle map, margin = 1m\nroundabout_obs_buffer = np.zeros(np.shape(roundabout_fmm_map))\nroundabout_obs_buffer[roundabout_fmm_map <= 1] = 1\nroundabout_obs_buffer[roundabout_fmm_map > 1] = -1\nroundabout_buffer_fmm_map = skfmm.distance(roundabout_obs_buffer, dx=[roundabout_dx, roundabout_dy])\nroundabout_buffer_fmm_map = - roundabout_buffer_fmm_map\n\n#############################\n# # Without buffer area\n# roundabout_fmm_map_downsampled = roundabout_fmm_map[::2, ::2]\n# print(\"roundabout fmm downsampled size is\", np.shape(roundabout_fmm_map_downsampled))\n# np.save(\"/home/anjianl/Desktop/project/optimized_dp/data/map/obstacle_map/roundabout_fmm_map_downsampled.npy\", roundabout_fmm_map_downsampled)\n#\n# roundabout_valfunc = np.zeros((465, 367, 24, 39))\n# for i in range(24):\n# for j in range(39):\n# roundabout_valfunc[:, :, i, j] = roundabout_fmm_map_downsampled\n#\n# # TODO, reverse y axis, I don't know why\n# roundabout_valfunc_correctify = np.zeros(np.shape(roundabout_valfunc))\n# for i in range(367):\n# roundabout_valfunc_correctify[:, i, :, :] = roundabout_valfunc[:, 366 - i, :, :]\n#\n# np.save(\"/home/anjianl/Desktop/project/optimized_dp/data/map/value_function/roundabout_valfunc.npy\", roundabout_valfunc)\n# np.save(\"/home/anjianl/Desktop/project/optimized_dp/data/map/value_function/roundabout_valfunc_correct.npy\", roundabout_valfunc_correctify)\n\n#############################\n# With buffer area\nnp.save(\"/home/anjianl/Desktop/project/optimized_dp/data/map/obstacle_map/roundabout_fmm_map_buffer_1m.npy\", roundabout_buffer_fmm_map)\n\nroundabout_buffer_fmm_map_downsampled = roundabout_buffer_fmm_map[::2, ::2]\nprint(\"roundabout fmm buffer downsampled size is\", np.shape(roundabout_buffer_fmm_map_downsampled))\n# np.save(\"/home/anjianl/Desktop/project/optimized_dp/data/map/obstacle_map/roundabout_fmm_map_downsampled_buffer_1.5.npy\", roundabout_buffer_fmm_map_downsampled)\n\nroundabout_valfunc_buffer = np.zeros((465, 367, 24, 39))\nfor i in range(24):\n for j in range(39):\n roundabout_valfunc_buffer[:, :, i, j] = roundabout_buffer_fmm_map_downsampled\n\n# TODO, reverse y axis, I don't know why\nroundabout_valfunc_buffer_correctify = np.zeros(np.shape(roundabout_valfunc_buffer))\nfor i in range(366):\n roundabout_valfunc_buffer_correctify[:, i, :, :] = roundabout_valfunc_buffer[:, 366 - i, :, :]\n\nnp.save(\"/home/anjianl/Desktop/project/optimized_dp/data/map/value_function/roundabout_valfunc_correct_buffer_1m.npy\", roundabout_valfunc_buffer_correctify)\n\n#\n# plt.imshow(roundabout_fmm_map_downsampled.T)\n# plt.show()","repo_name":"anjianli21/prediction_based_reachability","sub_path":"simulation/simulation_helper/fmm_map.py","file_name":"fmm_map.py","file_ext":"py","file_size_in_byte":8451,"program_lang":"python","lang":"en","doc_type":"code","stars":14,"dataset":"github-code","pt":"14"} +{"seq_id":"34183126602","text":"import math\nclass Solution:\n def mySqrt(self, x):\n \"\"\"\n :type x: int\n :rtype: int\n \"\"\"\n if(x == 0):\n return 0\n if(00:\n #print \"mean\", train_series.mean()\n train.loc[train_series.isnull(), train_name] = -1001\n #and Test\n tmp_len = len(test[test_series.isnull()])\n if tmp_len>0:\n test.loc[test_series.isnull(), test_name] = -1001\n\ncross_validation = 0.2\nn_cv = int(nsamples * cross_validation)\nn_train = nsamples - n_cv\n\ncv = train[n_train:nsamples].copy()\nnew_train = train[:n_train].copy()\ntarget_cv = target[n_train:nsamples].copy()\ntarget_train = target[:n_train].copy()\nprint ('cv: ', cv.shape, ' -- cv-target: ', target_cv.shape)\nprint ('train: ', new_train.shape, ' -- train-target: ', target_train.shape)\nxgtrain = xgb.DMatrix(new_train, target_train)\nxgcv = xgb.DMatrix( cv, target_cv ) \nxgtest = xgb.DMatrix(test)\n\n\nprint('Training... ')\n\nnum_round = 500\n\nparams = {\n 'objective':'binary:logistic',\n 'eval_metric':'logloss',\n 'eta' : 0.07,\n 'min_child_weight': 1,\n 'subsample': 0.9,\n 'colsample_bytree': 0.9,\n 'max_depth': 10,\n }\n\nplst = list(params.items())\nwatchlist = [(xgtrain, 'train'),(xgcv, 'val')]\nbst = xgb.train( plst, xgtrain, num_round, watchlist, early_stopping_rounds=50)\n\ny_pred = bst.predict(xgtest)\nprint('Testing... ')\n\npd.DataFrame({\"ID\": id_test, \"PredictedProb\": y_pred}).to_csv('xgboost_test1.csv',index=False)\n\n\n","repo_name":"raynerhmc/KaggleParibasTeam","sub_path":"KaggleParibas/Raynerhmc/Scripts/ClassificationTests/test1.py","file_name":"test1.py","file_ext":"py","file_size_in_byte":3042,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"20"} +{"seq_id":"74115072050","text":"import os\nimport pickle\n\nimport numpy as np\n\nfrom sklearn.tree import DecisionTreeClassifier\nfrom sklearn.ensemble import RandomForestClassifier\nfrom cflearn.constants import INPUT_KEY\nfrom cflearn.constants import LABEL_KEY\nfrom cflearn.dist.ml.runs._utils import get_info\n\n\nif __name__ == \"__main__\":\n info = get_info()\n meta = info.meta\n # data\n data = info.data\n assert data is not None\n loader = data.get_loaders()[0]\n dataset = loader.get_full_batch()\n x, y = dataset[INPUT_KEY], dataset[LABEL_KEY]\n assert isinstance(x, np.ndarray)\n assert isinstance(y, np.ndarray)\n # model\n model = meta[\"model\"]\n if model == \"decision_tree\":\n base = DecisionTreeClassifier\n elif model == \"random_forest\":\n base = RandomForestClassifier\n else:\n raise NotImplementedError\n sk_model = base()\n # train & save\n sk_model.fit(x, y.ravel())\n with open(os.path.join(info.workplace, \"sk_model.pkl\"), \"wb\") as f:\n pickle.dump(sk_model, f)\n","repo_name":"carefree0910/carefree-learn","sub_path":"examples/ml/iris/run_sklearn.py","file_name":"run_sklearn.py","file_ext":"py","file_size_in_byte":1006,"program_lang":"python","lang":"en","doc_type":"code","stars":399,"dataset":"github-code","pt":"20"} +{"seq_id":"36866302351","text":"from PIL import Image , ImageFont, ImageDraw\r\n\r\ndef drawtext():\r\n im = Image.open('addfont.png')\r\n print(im.size)\r\n font = ImageFont.truetype(r'BeaverScratches.ttf',70)\r\n print(font.getsize('xxxxx'))\r\n draw = ImageDraw.Draw(im)\r\n draw.text((100, 470), \"tan90\",font=font,fill=255)\r\n im.show()\r\n im.save('addfont2.png')\r\n\r\n\r\ndrawtext()\r\n","repo_name":"zx576/Crossin-practices","sub_path":"python_weekly_modual/modual_pil/drawtext.py","file_name":"drawtext.py","file_ext":"py","file_size_in_byte":359,"program_lang":"python","lang":"en","doc_type":"code","stars":16,"dataset":"github-code","pt":"20"} +{"seq_id":"3109842049","text":"from marshmallow import Schema, fields, validate, validates_schema, ValidationError\n\nfrom database.models import Product, Category\n\n\nclass ProductCreateValidater(Schema):\n name = fields.String(required=True, validate=validate.Length(max=255))\n description = fields.String(required=False, missing=None, load_only=True)\n price = fields.String(required=True)\n category_id = fields.Integer()\n\n @validates_schema\n def valideter_name(self, data, **kwargs):\n name = data.get('name', None)\n product = Product.query.filter(Product.name == name).first()\n if product:\n raise ValidationError('This is name is bory')\n \n @validates_schema\n def validater_price(self, data, **kwargs):\n price = data.get('price', None)\n if not price or not price.isdigit() or int(price[0]) < 1:\n raise ValidationError('Error price value')\n\n @validates_schema\n def validater_category_id(self, data, **kwargs):\n category_id = data.get('category_id', None)\n category = Category.query.filter(Category.id == category_id).first()\n if not category:\n raise ValidationError('This category ID not found')","repo_name":"IlyaBulatau/RestfulAPi-market-sample","sub_path":"src/market/validators.py","file_name":"validators.py","file_ext":"py","file_size_in_byte":1182,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"20"} +{"seq_id":"16210109771","text":"import argparse\nimport csv\nimport inspect\nimport logging\nfrom num2words import num2words\nfrom pathlib import Path\nimport re\n\nimport mlflow\nimport trainer.trainer as trainer_module\nfrom trainer import Trainer, TrainerArgs\nfrom TTS.tts.configs.shared_configs import BaseDatasetConfig\nfrom TTS.tts.configs.vits_config import VitsConfig\nfrom TTS.tts.datasets import load_tts_samples\nfrom TTS.tts.models.vits import Vits, VitsAudioConfig\nfrom TTS.tts.configs.shared_configs import CharactersConfig\nfrom TTS.tts.utils.text import cleaners\nfrom TTS.tts.utils.text.tokenizer import TTSTokenizer\nfrom TTS.utils.audio import AudioProcessor\n\nfrom custom_formatter import custom_formatter\n\n\nlogging.basicConfig(level=logging.INFO)\n\n\ndef make_command(function):\n parser = argparse.ArgumentParser()\n for parameter_name, parameter in inspect.signature(function).parameters.items():\n parser.add_argument(f\"--{parameter_name}\", type=parameter.annotation if parameter.annotation != inspect._empty else None)\n \n def wrapper():\n args = parser.parse_args()\n return function(**vars(args))\n \n return wrapper\n\n\ndef get_configuration(audio_data: str, output_path: str, epochs: int):\n dataset_config = BaseDatasetConfig(\n meta_file_train=\"eva_transcript.txt\",\n path=audio_data\n )\n\n audio_config = VitsAudioConfig(\n sample_rate=22050, win_length=1024, hop_length=256, num_mels=80, mel_fmin=0, mel_fmax=None\n )\n\n config = VitsConfig(\n audio=audio_config,\n run_name=\"vits_eva\",\n batch_size=4,\n eval_batch_size=4,\n eval_split_size=0.1,\n batch_group_size=5,\n num_loader_workers=1,\n num_eval_loader_workers=1,\n run_eval=True,\n test_delay_epochs=-1,\n epochs=epochs,\n use_phonemes=False,\n compute_input_seq_cache=True,\n print_step=25,\n print_eval=True,\n mixed_precision=False,\n output_path=output_path,\n datasets=[dataset_config],\n cudnn_benchmark=False,\n test_sentences=[\n \"Hola me llamo Eva\",\n \"Soy la clon de su voz. ¿En qué puedo ayudarte?\",\n ],\n characters=CharactersConfig(\n characters=\"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnñopqrstuvwxyzáéíóú\",\n punctuations=\"!'(),-.:;? ¡¿\",\n pad=\"\",\n eos='',\n bos='',\n blank='',\n )\n )\n \n return config\n\n \n@make_command\ndef main(audio_dataset, epochs):\n logging.info(\"Start training\")\n mlflow.autolog()\n \n output_path = \"model_outputs\"\n\n logging.info(\"Define configurations\")\n configuration = get_configuration(audio_dataset, output_path, epochs)\n\n logging.info(\"Create audio processor\")\n audio_processor = AudioProcessor.init_from_config(configuration)\n\n logging.info(\"Create tokenizer\")\n tokenizer, config = TTSTokenizer.init_from_config(configuration)\n\n logging.info(\"Create model\")\n model = Vits(configuration, audio_processor, tokenizer, speaker_manager=None)\n\n logging.info(\"Load samples\")\n train_samples, eval_samples = load_tts_samples(\n configuration.datasets[0],\n formatter=custom_formatter,\n eval_split=True,\n eval_split_max_size=config.eval_split_max_size,\n eval_split_size=config.eval_split_size,\n )\n\n logging.info(\"Create trainer\")\n trainer_module.get_experiment_folder_path = lambda path, run_name: path\n trainer = Trainer(\n TrainerArgs(),\n config,\n output_path,\n model=model,\n train_samples=train_samples,\n eval_samples=eval_samples,\n )\n\n logging.info(\"Train\")\n trainer.fit()\n\n logging.info(f\"Artifacts are in {trainer.output_path}\")\n logging.info(f\"Artifacts list: {list(Path(trainer.output_path).iterdir())}\")\n logging.info(\"Log artifacts\")\n mlflow.log_artifacts(trainer.output_path, artifact_path=output_path)\n\n logging.info(\"Run was finished\")\n \n \nif __name__ == \"__main__\":\n main()\n","repo_name":"rubchume/VoiceCloningFakeAudioDetection","sub_path":"src/eva_VITS_scratch/train_script.py","file_name":"train_script.py","file_ext":"py","file_size_in_byte":4039,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"20"} +{"seq_id":"12463962146","text":"import os\nimport threading\nimport atexit\nimport logging\nfrom gmail.bigQuery.bigquery import BigQ\n\nfrom flask import Flask, make_response, render_template, send_from_directory\n\nfrom gmail.pubsub.pubsub import PubSub\n\nPOOL_TIME = 30 # Seconds\n\n# variables that are accessible from anywhere\ncommonDataStruct = 0\n# lock to control access to variable\ndataLock = threading.RLock()\n# thread handler\nyourThread = threading.Thread()\n\n\ndef create_app():\n app = Flask(__name__)\n angular_folder = os.path.join(app.root_path, 'templates')\n\n @app.route('/')\n def angular(filename):\n return send_from_directory(angular_folder, filename)\n\n @app.route('/')\n def index():\n resp = make_response(render_template('index.html'))\n return resp\n\n @app.errorhandler(404)\n def not_found(error):\n logging.error(\"page not found error: {}\".format(error))\n resp = make_response(render_template('index.html'))\n return resp\n\n def interrupt():\n global yourThread\n yourThread.cancel()\n\n def doStuff():\n global commonDataStruct\n global yourThread\n with dataLock:\n commonDataStruct += 1\n p = PubSub()\n p.send()\n p.readMsgProcess(POOL_TIME - 2)\n # Set the next thread to happen\n yourThread = threading.Timer(POOL_TIME, doStuff, ())\n yourThread.start()\n\n def doStuffStart():\n # Do initialisation stuff here\n global yourThread\n # Create your thread\n yourThread = threading.Timer(POOL_TIME, doStuff, ())\n yourThread.start()\n\n # Initiate\n # doStuffStart()\n # When you kill Flask (SIGTERM), clear the trigger for the next thread\n atexit.register(interrupt)\n return app\n\n\napp = create_app()\n\nif __name__ == \"__main__\":\n app.run(debug=True, host='0.0.0.0', port=int(os.environ.get('PORT', 8080)))\n","repo_name":"mchirico/gmail","sub_path":"app.py","file_name":"app.py","file_ext":"py","file_size_in_byte":1896,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"20"} +{"seq_id":"71768440689","text":"# Definition for singly-linked list.\nclass ListNode(object):\n def __init__(self, val=0, next=None):\n self.val = val\n self.next = next\nclass Solution(object):\n def isPalindrome(self, head):\n \"\"\"\n :type head: ListNode\n :rtype: bool\n \"\"\"\n\n\n head1 = ListNode()\n p = head\n while p is not None:\n h1next = head1.next\n newnode = ListNode(p.val)\n head1.next = newnode\n newnode.next = h1next\n\n p = p.next\n\n p = head\n q = head1.next\n\n while p is not None and q is not None:\n if p.val != q.val:\n return False\n p = p.next\n q = q.next\n\n return True\n","repo_name":"xiaolizihahaha/LeetCode","sub_path":"234.py","file_name":"234.py","file_ext":"py","file_size_in_byte":735,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"20"} +{"seq_id":"49577760162","text":"'''\nGiven an array nums, write a function to move all 0's to the end of it while maintaining the relative order of the non-zero elements.\n\nExample:\n\nInput: [0, 1, 0, 3, 12]\nOutput: [1, 3, 12, 0, 0]\nNote:\n\nYou must do this in-place without making a copy of the array.\nMinimize the total number of operations.\n'''\nimport pytest\nfrom typing import List\n\n@pytest.mark.parametrize('input_and_output', [\n ([0, 1, 0, 3, 12], [1, 3, 12, 0, 0]),\n ([0, 1, 0, 3, 0], [1, 3, 0, 0, 0]),\n ([0, 0, 1], [1, 0, 0])\n ])\ndef test_move_zeroes(input_and_output):\n input_list = input_and_output[0]\n expected_output = input_and_output[1]\n moveZeroes(input_list)\n assert expected_output == input_list\n\ndef moveZeroes(nums: List[int]) -> None:\n \"\"\"\n Do not return anything, modify nums in-place instead.\n \"\"\"\n i = 0\n zero_count = 0\n while i < len(nums):\n if nums[i] == 0:\n zero_count += 1\n del nums[i]\n else:\n i += 1\n while zero_count:\n nums.append(0)\n zero_count -= 1\n","repo_name":"thiagolrpinho/solving-problems","sub_path":"leetcode/283_move_zeroes.py","file_name":"283_move_zeroes.py","file_ext":"py","file_size_in_byte":1050,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"20"} +{"seq_id":"22017244195","text":"class Solution(object):\n def firstUniqChar(self, s):\n \"\"\"\n :type s: str\n :rtype: int\n \"\"\"\n char_count = collections.Counter(s)\n for i in s:\n if char_count[i] == 1:\n return s.index(i)\n else:\n return -1\n","repo_name":"freakkid/leetcodeANDsicily","sub_path":"leetcode/first_unique_char387.py","file_name":"first_unique_char387.py","file_ext":"py","file_size_in_byte":290,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"20"} +{"seq_id":"3982311446","text":"from src.database.repositories.comment_repository import CommentRepository\nfrom src.api.dto import CommentDTO\n\n\nclass CommentNotFound(Exception):\n pass\n\n\nclass CommentService:\n def __init__(self, comment_repository: CommentRepository) -> None:\n self.comment_repository = comment_repository\n\n async def create_comment(\n self, *, author_id: int, post_id: int, text: str, parent_id: int = None\n ) -> CommentDTO:\n comment = await self.comment_repository.add_comment(\n author_id=author_id, post_id=post_id, text=text, parent_id=parent_id\n )\n return CommentDTO.from_orm(comment)\n\n async def get_comment(self, *, comment_id: int) -> CommentDTO:\n comment = await self.comment_repository.get_comment(comment_id=comment_id)\n if comment:\n return CommentDTO.from_orm(comment)\n raise CommentNotFound\n\n async def delete_comment(self, *, author_id: int, comment_id: int) -> None:\n if not await self.comment_repository.delete_comment(\n comment_id=comment_id, author_id=author_id\n ):\n raise CommentNotFound\n\n async def update_comment(\n self, *, author_id: int, comment_id: int, update_data: dict\n ) -> CommentDTO:\n comment = await self.comment_repository.update_comment(\n comment_id=comment_id, author_id=author_id, update_data=update_data\n )\n if comment:\n return CommentDTO.from_orm(comment[0])\n raise CommentNotFound\n","repo_name":"EldarSHkh/BlogTestTask","sub_path":"src/services/comment_service.py","file_name":"comment_service.py","file_ext":"py","file_size_in_byte":1497,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"20"} +{"seq_id":"72693209649","text":"from tensorflow.keras.models import Sequential\nfrom tensorflow.keras.layers import Dense\nimport numpy as np\nfrom sklearn.model_selection import train_test_split\n\n#1.데이터\nx= np.array([1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16,17,18,19,20]) #데이터를 시각화한다. ->scatter, 그래프 그린다는 소리 (예측값에 선을 그어보자)\ny= np.array([1,2,4,3,5,7,9,3,8,12,13,8,14,15,9,6,17,23,21,20]) \n\nx_train, x_test, y_train, y_test = train_test_split(x, y, #x는 x_train과 x_test로 분리되고, y는 y_train과 y_test 순서로! 분리된다.\n train_size=0.7, shuffle=True, random_state= 1234\n)\n\n#2.모델 구성\nmodel=Sequential()\nmodel.add(Dense(6, input_dim=1))\nmodel.add(Dense(4))\nmodel.add(Dense(3))\nmodel.add(Dense(6))\nmodel.add(Dense(4))\nmodel.add(Dense(6))\nmodel.add(Dense(1))\n\n#3. 컴파일 훈련\nmodel.compile(loss='mae', optimizer='adam')\nmodel.fit(x_train,y_train,epochs=2000, batch_size=1)\n\n#4.평가 예측\nloss=model.evaluate(x_test,y_test)\nprint('loss : ', loss)\n\ny_predict=model.predict(x) # 전체 데이터를 넣어보자\n\nimport matplotlib.pyplot as plt #그림그릴때 쓰는 api \n#시각화\nplt.scatter(x,y) #점으로 볼수있음\n#plt.scatter(x, y_predict, color='red')\nplt.plot(x, y_predict, color='red') # plot 선으로 볼수있음\n\nplt.show()\n\n# 수치로 나오는 것 -> 회귀(지금 하고 있는것) , 예를들어 0/1로 나뉜다거나 남자 여자 나뉘는거 -> 분류 \n\n\n\n\n","repo_name":"LeeYeJ/study","sub_path":"keras/keras09_scatter.py","file_name":"keras09_scatter.py","file_ext":"py","file_size_in_byte":1439,"program_lang":"python","lang":"ko","doc_type":"code","stars":0,"dataset":"github-code","pt":"20"} +{"seq_id":"27576683424","text":"# 1\n\nname = input(\"Whats your name? \")\nage = int(input(\"How old are you? \"))\nprint(\"Which are your favourite movies? \")\nmovies = []\nmovies.append(input(\"1: \"))\nmovies.append(input(\"2: \"))\nmovies.append(input(\"3: \"))\npython_skills = float(\n input(\"How do your rate your python skills (0.0-10.0)? \"))\nhasPetsInput = input(\"Do you have pets? (y/n)\")\nif hasPetsInput == \"y\":\n hasPets = True\nelse:\n hasPets = False\n\nprint(name, type(name))\nprint(age, type(age))\nprint(movies, type(movies[0]))\nprint(python_skills, type(python_skills))\nprint(hasPets, type(hasPets))\n\n\n# 2\n# a\nsum = 0\nfor i in range(100+1):\n sum += i\n print(i)\nprint(sum)\n\n# b\nfor i in range(100+1):\n if i % 2 == 0:\n print(i)\n\n# b\nfor i in range(100+1):\n if i % 2 == 0 and i % 4 != 0:\n print(i)\n\n# c\nfor i in range(100+1):\n isPrime = True\n if i < 2:\n isPrime = False\n for j in range(2, i):\n if j != 0 and i % j == 0:\n isPrime = False\n\n if isPrime:\n print(\"prime\", i)\n\n# 3\niterations = 5\nmistakes = 0\ntask_solved = False\nprint(\"Write the following sentence for \" + str(iterations) + \" times:\")\nprint(\"I enjoy learning Python with Jakob\")\n\nwhile not task_solved:\n for i in range(iterations):\n inputString = input(str(i) + \": \")\n\n if inputString != \"I enjoy learning Python with Jakob\":\n mistakes += 1\n print(\"Wrong, try again\")\n print(\"\")\n print(\"\")\n break\n elif i == iterations - 1:\n task_solved = True\n\nprint(\"Congratulations, you made it!\")\nprint(\"You made \" + str(mistakes) + \" mistakes\")\n","repo_name":"jnaurath/learn-python","sub_path":"0-Basics/solutions/exercise-2.py","file_name":"exercise-2.py","file_ext":"py","file_size_in_byte":1620,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"20"} +{"seq_id":"3115805783","text":"#!/usr/bin/python3\n\n\"\"\"\nExample of a script that uses SimSo.\n\"\"\"\n\nimport sys\nfrom simso.core import Model\nfrom simso.configuration import Configuration\n\n\ndef main(argv):\n if len(argv) == 2:\n # Configuration load from a file.\n configuration = Configuration(argv[1])\n else:\n # Manual configuration:\n configuration = Configuration()\n\n configuration.duration = 420 * configuration.cycles_per_ms\n\n # Add tasks:\n configuration.add_task(name=\"T1\", identifier=1, period=7,\n activation_date=0, wcet=3, deadline=7)\n configuration.add_task(name=\"T2\", identifier=2, period=12,\n activation_date=0, wcet=3, deadline=12)\n configuration.add_task(name=\"T3\", identifier=3, period=20,\n activation_date=0, wcet=5, deadline=20)\n\n # Add a processor:\n configuration.add_processor(name=\"CPU 1\", identifier=1)\n\n # Add a scheduler:\n #configuration.scheduler_info.filename = \"../simso/schedulers/RM.py\"\n configuration.scheduler_info.clas = \"simso.schedulers.RM\"\n\n # Check the config before trying to run it.\n configuration.check_all()\n\n # Init a model from the configuration.\n model = Model(configuration)\n\n # Execute the simulation.\n model.run_model()\n\n # Print logs.\n for log in model.logs:\n print(log)\n\nmain(sys.argv)\n","repo_name":"MaximeCheramy/simso","sub_path":"misc/script.py","file_name":"script.py","file_ext":"py","file_size_in_byte":1419,"program_lang":"python","lang":"en","doc_type":"code","stars":76,"dataset":"github-code","pt":"20"} +{"seq_id":"70121099251","text":"from rest_framework import status\r\nfrom rest_framework.response import Response\r\nfrom rest_framework.decorators import api_view, permission_classes\r\nfrom rest_framework.permissions import IsAuthenticated\r\nfrom rest_framework.pagination import PageNumberPagination\r\nfrom rest_framework.generics import ListAPIView\r\nfrom rest_framework.authentication import TokenAuthentication\r\nfrom rest_framework.filters import SearchFilter, OrderingFilter\r\n\r\nfrom users.models import Account\r\nfrom blog.models import BlogPost\r\nfrom blog.api.serializers import BlogPostSerializer\r\n\r\n\r\n@api_view(['GET', ])\r\n@permission_classes((IsAuthenticated,))\r\ndef api_detail_blog_view(request, slug):\r\n \r\n try:\r\n blog_post = BlogPost.objects.get(slug=slug)\r\n except BlogPost.DoesNotExist:\r\n return Response(status=status.HTTP_404_NOT_FOUND)\r\n \r\n if request.method == \"GET\":\r\n serializer = BlogPostSerializer(blog_post)\r\n return Response(serializer.data)\r\n \r\n \r\n@api_view(['PUT', ])\r\n@permission_classes((IsAuthenticated,))\r\ndef api_update_blog_view(request, slug):\r\n \r\n try:\r\n blog_post = BlogPost.objects.get(slug=slug)\r\n except BlogPost.DoesNotExist:\r\n return Response(status=status.HTTP_404_NOT_FOUND)\r\n \r\n if request.method == \"PUT\":\r\n serializer = BlogPostSerializer(blog_post, data=request.data)\r\n data = {}\r\n if serializer.is_valid():\r\n serializer.save()\r\n data[\"success\"] = \"update successful\"\r\n return Response(data=data)\r\n return Response(serializer.errors, status=status.HTTP_400_BAD_REQUEST)\r\n\r\n\r\n@api_view(['DELETE', ])\r\n@permission_classes((IsAuthenticated,))\r\ndef api_delete_blog_view(request, slug):\r\n \r\n try:\r\n blog_post = BlogPost.objects.get(slug=slug)\r\n except BlogPost.DoesNotExist:\r\n return Response(status=status.HTTP_404_NOT_FOUND)\r\n \r\n user = request.user\r\n if blog_post.author != user:\r\n return Response({'response':\"You don't have permission to delete post\"})\r\n \r\n if request.method == \"DELETE\":\r\n operation = blog_post.delete()\r\n data = {}\r\n if operation:\r\n data[\"success\"] = \"delete successful\"\r\n else:\r\n data[\"failure\"] = \"delete failed\"\r\n return Response(data=data)\r\n\r\n@api_view(['POST', ])\r\n@permission_classes((IsAuthenticated,))\r\ndef api_create_blog_view(request):\r\n \r\n account = request.user\r\n blog_post = BlogPost(author=account)\r\n if request.method == \"POST\":\r\n serializer = BlogPostSerializer(blog_post, data=request.data)\r\n if serializer.is_valid():\r\n serializer.save()\r\n return Response(serializer.data, status=status.HTTP_201_CREATED)\r\n return Response(serializer.errors, status=status.HTTP_400_BAD_REQUEST)\r\n\r\n\r\nclass ApiBlogListView(ListAPIView):\r\n queryset = BlogPost.objects.all()\r\n serializer_class = BlogPostSerializer\r\n authentication_classes = (TokenAuthentication,)\r\n permission_classes(IsAuthenticated,)\r\n pagination_class = PageNumberPagination\r\n # Search filtering\r\n filter_backends = (SearchFilter, OrderingFilter)\r\n search_fields = ('title', 'body', 'author__username')","repo_name":"Dannyblazer/social-media-blog","sub_path":"blog/api/views.py","file_name":"views.py","file_ext":"py","file_size_in_byte":3216,"program_lang":"python","lang":"en","doc_type":"code","stars":7,"dataset":"github-code","pt":"20"} +{"seq_id":"31162353898","text":"import os\nimport json\n\nimport boto3\nimport botocore\nimport pytest\nimport requests\n\n\"\"\"\nMake sure env variable AWS_SAM_STACK_NAME exists with the name of the stack we are going to test. \n\"\"\"\n\n\ndef cf_output(key, stack):\n \"\"\"\n Get an output value from CloudFormation stack\n :param key: Output key\n :return: Output value\n \"\"\"\n try:\n return next(filter(lambda x: x['OutputKey'] == key, stack['Outputs']))['OutputValue']\n except IndexError:\n return None\n\n\nclass TestRouter:\n\n @pytest.fixture()\n def stack(self):\n \"\"\" Get the Cloudformation Stack \"\"\"\n stack_name = os.environ.get(\"AWS_SAM_STACK_NAME\")\n\n if stack_name is None:\n raise ValueError(\n 'Please set the AWS_SAM_STACK_NAME environment variable to the name of your stack')\n\n client = boto3.client(\"cloudformation\")\n\n try:\n response = client.describe_stacks(StackName=stack_name)\n except Exception as e:\n raise Exception(\n f\"Cannot find stack {stack_name} \\n\" f'Please make sure a stack with the name \"{stack_name}\" exists'\n ) from e\n\n stack = response[\"Stacks\"][0]\n return stack\n\n @pytest.fixture()\n def queues_url(self, stack):\n \"\"\" Get the SQS queue URL from Cloudformation Stack outputs \"\"\"\n\n input_queue = cf_output(\"InputQueueUrl\", stack)\n store_queues = cf_output(\"OutputQueuesUrl\", stack)\n\n if not input_queue:\n raise KeyError(f\"InputQueueUrl not found in stack {stack_name}\")\n\n if not store_queues:\n raise KeyError(f\"OutputQueuesUrl not found in stack {stack_name}\")\n\n return {\"input_queue\": input_queue, \"store_queues\": json.loads(store_queues)}\n\n @pytest.fixture()\n def purge_queues(self, queues_url):\n \"\"\" Purge queues before each test \"\"\"\n sqs = boto3.client(\"sqs\")\n\n try:\n for queue in [queues_url[\"input_queue\"], *queues_url[\"store_queues\"].values()]:\n sqs.purge_queue(QueueUrl=queue)\n except sqs.exceptions.PurgeQueueInProgress as e:\n print(\"Last purge was less than 60 seconds ago. Skipping purge.\")\n pass\n\n yield\n\n @pytest.fixture()\n def orders_sample(self):\n \"\"\" Get orders sample from orders.json \"\"\"\n orders_file = os.path.join(os.path.dirname(__file__), \"orders.json\")\n\n with open(orders_file, \"r\") as f:\n return json.load(f)\n\n def test_sqs_routing(self, queues_url, orders_sample, purge_queues):\n\n sqs = boto3.client(\"sqs\")\n\n for order in orders_sample:\n\n store = str(order[\"store\"])\n\n # sending order to input queue\n sqs.send_message(\n QueueUrl=queues_url[\"input_queue\"], MessageBody=json.dumps(order))\n\n # receiving order from store queue, try 10 times\n MAX_TRY = 10\n t = 0\n res = {}\n while t < MAX_TRY and 'Messages' not in res:\n res = sqs.receive_message(\n QueueUrl=queues_url[\"store_queues\"][store], MaxNumberOfMessages=1, WaitTimeSeconds=3)\n t += 1\n print(res)\n\n should_be = order\n del should_be[\"store\"]\n\n try:\n assert 'Messages' in res\n assert len(res['Messages']) == 1\n assert 'Body' in res['Messages'][0]\n assert json.loads(res['Messages'][0]['Body']) == should_be\n finally:\n sqs.delete_message(\n QueueUrl=queues_url[\"store_queues\"][store],\n ReceiptHandle=res['Messages'][0]['ReceiptHandle'])\n","repo_name":"sinux-l5d/cloud-archtecture-ca1","sub_path":"tests/integration/test_router.py","file_name":"test_router.py","file_ext":"py","file_size_in_byte":3686,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"20"} +{"seq_id":"13859956477","text":"import win32gui\r\n#import _thread\r\nimport multiprocessing\r\nimport lab\r\n#import vid\r\nimport api\r\nimport time\r\nimport pywintypes\r\nfrom tkinter import filedialog\r\nimport tkinter\r\nimport tt\r\n\r\ndef protect():\r\n pt=multiprocessing.Process(target=protectcallback,args=(pid,))\r\n pt.start()\r\n\r\ndef get_boswore_path():\r\n return filedialog.askopenfilename()\r\n\r\ndef protectcallback(pid):\r\n print(\"233\")\r\n #global pid\r\n global dshandle\r\n dshandle = tt.find_desktop_hwnd()\r\n while 1:#皮一下\r\n thishandle = tt.find_desktop_hwnd()\r\n print(thishandle,dshandle)\r\n #if dshandle != thishandle:\r\n if 1:\r\n for handle in pid:\r\n lab.setson(handle)\r\n dshandle = thishandle\r\n time.sleep(5)\r\n\r\ndef main():\r\n global pid\r\n #_thread.start_new_thread( vid.play, (\"3.mp4\", ) )\r\n\r\n #time.sleep(.5)\r\n while True:\r\n if lab.get_jb_id(\"wallpaperce84aa7d-3cec-4ef8-b6fd-b3d76e56aa20\") is None:\r\n time.sleep(.05)\r\n else:\r\n pid = lab.get_jb_id(\"wallpaperce84aa7d-3cec-4ef8-b6fd-b3d76e56aa20\")\r\n break\r\n\r\n\r\n for handle in lab.get_jb_id(\"wallpaperce84aa7d-3cec-4ef8-b6fd-b3d76e56aa20\"):\r\n lab.setson(handle)\r\n\r\n #protect = multiprocessing.Process(target=protectcallback)\r\n #protect.start()\r\n\r\n# while True:\r\n# time.sleep(999999)\r\n\r\ndef start():\r\n vidpath = get_boswore_path()\r\n #maintrade = multiprocessing.Process(target=main)\r\n #vplayer = multiprocessing.Process(target=api.send_commend, args=(vidpath,))\r\n #maintrade.start()\r\n #vplayer.start()\r\n api.send_commend(vidpath)\r\n main()\r\n\r\nif __name__==\"__main__\":\r\n multiprocessing.freeze_support()\r\n top = tkinter.Tk()\r\n top.geometry(\"400x100\")\r\n B1 = tkinter.Button(top, text =\"启动壁纸\", command = start)\r\n B2 = tkinter.Button(top, text =\"停止壁纸\", command = api.stop)\r\n B3 = tkinter.Button(top, text=\"启动win11多桌面兼容进程(不知道干啥的不要乱按(doge))\" ,command=protect)\r\n B1.pack()\r\n B2.pack()\r\n B3.pack()\r\n top.mainloop()","repo_name":"Quandong-Zhang/desktop-wallpaper-engine-new","sub_path":"main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":2101,"program_lang":"python","lang":"en","doc_type":"code","stars":4,"dataset":"github-code","pt":"20"} +{"seq_id":"2611231717","text":"from dataset_creator_functions import *\nimport pickle\n\ndemand_data_training = pd.read_csv('/Users/ankitsrivastava/Documents/Sales prediction assignment/data_000.csv',header=None,\n\t\tnames=['bookingdate', 'hotelid', 'cityid', 'checkin', 'checkout', 'flavour', 'num_rooms', 'userid'])\ndate_parsing_fn(demand_data_training)\n\ntxn_data_training = pd.read_csv('/Users/ankitsrivastava/Documents/Sales prediction assignment/data_000 2.csv',header=None,\n\tnames=['bookingdate', 'hotelid', 'cityid', 'checkin', 'checkout', 'flavour', 'num_rooms', 'userid'])\n\n######## booking data aggregation commands\n\nhotel_list = list(txn_data_training['hotelid'].unique())\n\nbooking_aggregated = txn_data_aggregator(txn_data_training, hotel_list)\n\n######## demand data aggregation commmands\n\ndemand_data_aggregator(booking_aggregated,demand_data_training)\n\n######## compilation of booking and demand data commands\n\nwith open('agg_city_var.pickle', 'rb') as handle:\n\tcity_df = pickle.load(handle)\n\nwith open('agg_hotel_var.pickle', 'rb') as handle:\n\thotel_df = pickle.load(handle)\n\ntxn_demand_data_compiler(booking_aggregated, city_df, hotel_df)\n","repo_name":"ankits1089/Hotel-sales-prediction","sub_path":"dataset_creation.py","file_name":"dataset_creation.py","file_ext":"py","file_size_in_byte":1119,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"20"} +{"seq_id":"10610423022","text":"#!/usr/bin/python\nimport json\nimport commands\n\n#### setup config\nPORT_PSWD_MAP = {\n 2333: \"12345678\",\n 2334: \"12345678\",\n}\nMETHOD = \"aes-256-cfb\"\nSECURITY_GROUP_NAME = \"auto_ss_sg\"\nLAUNCH_TEMPLATE_NAME = \"auto_ss\"\n\n##### format config data\nss_json = {\n \"server\": \"0.0.0.0\",\n \"timeout\": 300,\n \"method\": METHOD,\n \"port_password\": PORT_PSWD_MAP\n}\n\nuser_data = \"\"\"#!/bin/bash\n\necho '{}' > /etc/shadowsocks.json\ngit clone https://github.com/miojizzy/auto_ssserver.git > /tmp/init_log 2>&1\ncd auto_ssserver && ./setup.sh si \ntouch testfile\n\"\"\".format(json.dumps(ss_json))\n\n\n\ndef main():\n generate_ud()\n generate_sg()\n generate_sgi()\n generate_lt()\n\n\ndef generate_sg():\n data = {\n \"Description\": \"security group for auto ssserver\",\n \"GroupName\": SECURITY_GROUP_NAME\n }\n with open (\"conf/sg.json\", \"w\") as f:\n f.write(json.dumps(data)+'\\n')\n with open (\"conf/dsg.json\", \"w\") as f:\n f.write(json.dumps({\"GroupName\": SECURITY_GROUP_NAME})+'\\n')\n\n\ndef generate_sgi():\n data = {}\n data[\"GroupName\"] = SECURITY_GROUP_NAME\n data[\"IpPermissions\"] = []\n # for ssh\n data[\"IpPermissions\"] = [{\n \"FromPort\": 22, \n \"ToPort\": 22, \n \"IpProtocol\": \"tcp\", \n \"IpRanges\": [{\"CidrIp\": \"0.0.0.0/0\"}]\n }]\n with open(\"conf/sgi/sgi0.json\", \"w\") as f:\n f.write(json.dumps(data)+'\\n')\n # for ping\n data[\"IpPermissions\"] = [{\n \"FromPort\": -1, \n \"ToPort\": -1, \n \"IpProtocol\": \"icmp\", \n \"IpRanges\": [{\"CidrIp\": \"0.0.0.0/0\"}]\n }]\n with open(\"conf/sgi/sgi1.json\", \"w\") as f:\n f.write(json.dumps(data)+'\\n')\n # for app\n for i in range(len(PORT_PSWD_MAP)):\n port = PORT_PSWD_MAP.keys()[i]\n data[\"IpPermissions\"] = [{\n \"FromPort\": port, \n \"ToPort\": port, \n \"IpProtocol\": \"tcp\", \n \"IpRanges\": [{\"CidrIp\": \"0.0.0.0/0\"}]\n }]\n with open(\"conf/sgi/sgi%d.json\"%(i+2), \"w\") as f:\n f.write(json.dumps(data)+'\\n')\n\n\ndef generate_ud():\n with open(\"conf/ud\", \"w\") as f:\n f.write(user_data+'\\n')\n\n\ndef generate_lt():\n data = {}\n data[\"LaunchTemplateName\"] = LAUNCH_TEMPLATE_NAME\n data[\"LaunchTemplateData\"] = {\n \"EbsOptimized\": False,\n \"ImageId\": \"ami-0fe22bffdec36361c\",\n \"InstanceType\": \"t2.nano\",\n \"SecurityGroups\": [SECURITY_GROUP_NAME],\n \"UserData\": commands.getoutput(\"cat conf/ud|base64\")\n }\n with open(\"conf/lt.json\", \"w\") as f: \n f.write(json.dumps(data)+'\\n') \n with open(\"conf/dlt.json\", \"w\") as f: \n f.write(json.dumps({\"LaunchTemplateName\": LAUNCH_TEMPLATE_NAME})+'\\n') \n\n\n\nif __name__ == \"__main__\":\n main()\n","repo_name":"miojizzy/auto_ssserver","sub_path":"src/ssserver/config.py","file_name":"config.py","file_ext":"py","file_size_in_byte":2835,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"20"} +{"seq_id":"17168268940","text":"DJANGO_INSTALLED = False\nDJANGO_CONFIGURED = False\nDJANGO_SETTINGS = None\n\ntry:\n import django\n DJANGO_INSTALLED = True\nexcept ImportError:\n pass\n\nif DJANGO_INSTALLED:\n try:\n from django.core.exceptions import ImproperlyConfigured\n except ImportError:\n DJANGO_INSTALLED = False\n if DJANGO_INSTALLED:\n try:\n from django.conf import settings as DJANGO_SETTINGS\n # Try and raise an ImproperlyConfigured error\n getattr(DJANGO_SETTINGS, 'DEBUG', None)\n DJANGO_CONFIGURED = True\n except ImproperlyConfigured:\n DJANGO_SETTINGS = None","repo_name":"Raniac/NEURO-LEARN","sub_path":"env/lib/python3.6/site-packages/optional_django/env.py","file_name":"env.py","file_ext":"py","file_size_in_byte":627,"program_lang":"python","lang":"en","doc_type":"code","stars":8,"dataset":"github-code","pt":"20"} +{"seq_id":"34639025567","text":"#\n# @lc app=leetcode id=187 lang=python3\n#\n# [187] Repeated DNA Sequences\n#\n# https://leetcode.com/problems/repeated-dna-sequences/description/\n#\n# algorithms\n# Medium (38.21%)\n# Likes: 698\n# Dislikes: 267\n# Total Accepted: 158.3K\n# Total Submissions: 410.8K\n# Testcase Example: '\"AAAAACCCCCAAAAACCCCCCAAAAAGGGTTT\"'\n#\n# All DNA is composed of a series of nucleotides abbreviated as A, C, G, and T,\n# for example: \"ACGAATTCCG\". When studying DNA, it is sometimes useful to\n# identify repeated sequences within the DNA.\n# \n# Write a function to find all the 10-letter-long sequences (substrings) that\n# occur more than once in a DNA molecule.\n# \n# Example:\n# \n# \n# Input: s = \"AAAAACCCCCAAAAACCCCCCAAAAAGGGTTT\"\n# \n# Output: [\"AAAAACCCCC\", \"CCCCCAAAAA\"]\n# \n# \n#\n\n# @lc code=start\nfrom collections import defaultdict\nclass Solution:\n def findRepeatedDnaSequences(self, s: str) -> [str]:\n n, res = len(s), set()\n if n < 10:\n return res\n count = defaultdict(int)\n for i in range(n-9):\n count[s[i:i+10]] += 1\n if count[s[i:i+10]] > 1:\n res.add(s[i:i+10])\n return list(res)\n \n def suffix_prefix(self, s:str) -> [int]:\n res, i = [0], 0\n for j in range(1, len(s)):\n while i > 0 and s[i] != s[j]:\n i = res[i-1]\n if s[j] == s[i]:\n res.append(i+1)\n i += 1\n else:\n res.append(0)\n return res\n# @lc code=end\nif __name__ == '__main__':\n s = Solution()\n s.findRepeatedDnaSequences('AAAAACCCCCAAAAACCCCCCAAAAAGGGTTT')\n s.findRepeatedDnaSequences('AAAAAAAAAAA')\n # s.suffix_prefix('ababcdabc')\n","repo_name":"mic0ud/Leetcode-py3","sub_path":"src/187.repeated-dna-sequences.py","file_name":"187.repeated-dna-sequences.py","file_ext":"py","file_size_in_byte":1703,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"20"} +{"seq_id":"17993582638","text":"###\n### TEAM 80 - OMNIVIDA\n### Functions to compute adherence\n###\nimport pandas as pd\nimport generic_funcions as gf\n\n\n### This function adds previous periods to an observation date. This is necesary to compute features.\n# Returns: dataframe with year_d and month_d, and diference of months in dates.\n# Author: monicarodguev\ndef periods_aderence( base_p ):\n dy = pd.DataFrame.from_dict( {'year_c': list(range(2016,2021))} )\n dm = pd.DataFrame.from_dict({'month_c': list(range(1,13) )})\n\n base_p['key'] = 1\n dy['key'] = 1\n dm['key'] = 1\n\n base_c = base_p.merge(dy, on ='key').merge(dm, on ='key')\n base_c['d_meses'] = ( base_c['year']*12 + base_c['month'] ) - ( base_c['year_c']*12 + base_c['month_c'] )\n base_d = base_c[base_c['d_meses'] > 0 ]\n\n base_d.rename(columns={'year':'year_obs', 'month':'month_obs'}, inplace=True)\n\n return base_d\n\n\n### This function adds future periods to an observation date. This is necesary to compute adherence in the future.\n# Returns: dataframe with year_d and month_d, and diference of months in dates.\n# Author: monicarodguev\ndef periods_aderence_futuro( base_p ):\n dy = pd.DataFrame.from_dict( {'year_c': list(range(2016,2021))} )\n dm = pd.DataFrame.from_dict({'month_c': list(range(1,13) )})\n\n base_p['key'] = 1\n dy['key'] = 1\n dm['key'] = 1\n\n base_c = base_p.merge(dy, on ='key').merge(dm, on ='key')\n base_c['d_meses'] = ( base_c['year']*12 + base_c['month'] ) - ( base_c['year_c']*12 + base_c['month_c'] )\n base_d = base_c[base_c['d_meses'] <= 0 ]\n\n base_d.rename(columns={'year':'year_obs', 'month':'month_obs'}, inplace=True)\n\n return base_d\n\n\n### This function gets the table with patients' adherence observation at month = 0.\n# Returns: dataframe with id, observerd adherence, (observation date) year and month, (join dates) year_d and month_d, and diference of months in dates\n# Author: monicarodguev\ndef base_features_adeherencia0( ruta, diccionario, ids ):\n # Load adherence file\n modulo = 'Adherencia'\n\n base = gf.carga_datos( ruta = ruta, diccionario = diccionario, modulo = modulo )\n base_ = base.dropna()\n\n # If NO adherent: 1, else: 0\n def adhere( x ):\n y = 2\n if x == 'NO ADHERENTE' :\n y = 1\n elif x == 'ADHERENTE' :\n y = 0\n return y\n\n base_['adherencia_cat'] = base_['Cualitativo_ponderado'].apply( adhere )\n base_ = base_[base_['adherencia_cat'] < 2]\n\n base_p = base_.groupby( ids )['adherencia_cat'].max().reset_index( name='adeherencia_0' )\n\n base_d = periods_aderence( base_p )\n\n return base_d, base_p\n\n\n\n### This function gets the table with patients' adherence observation from month = 0 to month=11 (one year).\n# Returns: dataframe with id, observerd adherence, (observation date) year and month, (join dates) year_d and month_d, and diference of months in dates\n# Author: monicarodguev\ndef base_features_adeherencia_meses( ruta, diccionario, ids, n_meses ):\n # Load adherence file\n _ , base_p = base_features_adeherencia0( ruta, diccionario, ids )\n\n base_x = periods_aderence_futuro( base_p )\n base_x = base_x[['id', 'year_obs', 'month_obs','year_c','month_c', 'd_meses']]\n\n base_merge = base_x.merge( base_p , how='left', left_on = ['id', 'year_c', 'month_c'], right_on = ['id', 'year', 'month'] )\n base_merge.dropna(inplace = True)\n base_merge = base_merge[base_merge['d_meses']>=(1-n_meses)]\n\n base_consolidada = base_merge.groupby(['id','year_obs','month_obs'])[['adeherencia_0','key']].sum().reset_index()\n base_consolidada.columns = ['id', 'year', 'month', 'adeherencia_'+str(n_meses), 'cantidad']\n\n base_d = periods_aderence( base_consolidada )\n\n return base_d, base_consolidada\n","repo_name":"monicarodguev/ds4a_team80","sub_path":"data_transformation/adherence_functions.py","file_name":"adherence_functions.py","file_ext":"py","file_size_in_byte":3739,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"20"} +{"seq_id":"18471154477","text":"\"\"\"\nTake as input two files: one with the gold annotations and one with the predictions. \nUse two ists of predefined medical terms defined by Sadhukhan and check for each occurrence if these are negated or not in gold and pred. \nCompute TP, TN, FP, FN and use this to compute F-score (F1). \n\n\"\"\"\n\nfrom argparse import ArgumentParser\nimport json\nimport os\nimport re\nfrom collections import defaultdict, Counter\n\ndef sanity_check(gold_dict, pred_dict): \n for term in gold_dict: \n for sid in gold_dict[term]: \n gold_spans = sorted([s for s,_ in gold_dict[term][sid]])\n pred_spans = sorted([s for s,_ in pred_dict[term][sid]])\n assert gold_spans == pred_spans\n\n for term in pred_dict:\n for sid in pred_dict[term]:\n gold_spans = sorted([s for s,_ in gold_dict[term][sid]])\n pred_spans = sorted([s for s,_ in pred_dict[term][sid]])\n assert gold_spans == pred_spans\n\n print(\"Sanity check passed :-)\")\n\ndef sanity_check_no_sorting(gold_dict, pred_dict): \n for term in gold_dict: \n for sid in gold_dict[term]: \n gold_spans = [s for s,_ in gold_dict[term][sid]]\n pred_spans = [s for s,_ in pred_dict[term][sid]]\n #if gold_spans != []:\n # print(\"gold_spans:\", gold_spans)\n # print(\"pred_spans:\", pred_spans)\n assert gold_spans == pred_spans\n\n for term in pred_dict:\n for sid in pred_dict[term]:\n gold_spans = [s for s,_ in gold_dict[term][sid]]\n pred_spans = [s for s,_ in pred_dict[term][sid]]\n #if gold_spans != []:\n # print(\"gold_spans:\", gold_spans)\n # print(\"pred_spans:\", pred_spans)\n assert gold_spans == pred_spans\n\n print(\"Sanity check (no sorting of lists) passed :-)\")\n\ndef tp(gold_dict, pred_dict):\n counter = 0\n instances = []\n for term in gold_dict: \n for sid in gold_dict[term]: \n for ((span_g,neg_g),(span_p,neg_p)) in zip(gold_dict[term][sid],pred_dict[term][sid]):\n #print(f\"\\n'{term}' in {sid}\")\n #print(\"gold:\", span_g, neg_g)\n #print(\"pred:\", span_p, neg_p)\n if neg_g and neg_p: # both are True, i.e. negated in gold standard and negated in predictions\n counter += 1\n instances.append((term,sid,span_g))\n return counter, instances\n\ndef tn(gold_dict, pred_dict):\n counter = 0\n instances = []\n for term in gold_dict:\n for sid in gold_dict[term]:\n for ((span_g,neg_g),(span_p,neg_p)) in zip(gold_dict[term][sid],pred_dict[term][sid]):\n if not neg_g and not neg_p: \n counter += 1\n instances.append((term,sid,span_g))\n return counter, instances\n\ndef fp(gold_dict, pred_dict):\n counter = 0\n instances = []\n for term in gold_dict:\n for sid in gold_dict[term]:\n for ((span_g,neg_g),(span_p,neg_p)) in zip(gold_dict[term][sid],pred_dict[term][sid]):\n if not neg_g and neg_p: \n counter += 1\n instances.append((term,sid,span_g))\n return counter, instances\n\ndef fn(gold_dict, pred_dict):\n counter = 0\n instances = []\n for term in gold_dict:\n for sid in gold_dict[term]:\n for ((span_g,neg_g),(span_p,neg_p)) in zip(gold_dict[term][sid],pred_dict[term][sid]):\n if neg_g and not neg_p: \n counter += 1\n instances.append((term,sid,span_g))\n return counter, instances\n\ndef precision(tp, fp):\n return tp / (tp + fp)\n\ndef recall(tp, fn):\n return tp / (tp + fn)\n\ndef f1(precision, recall):\n return 2 * ((precision * recall) / (precision + recall))\n\n\ndef get_overlapping_terms(terms_list):\n overlap = defaultdict(lambda: [])\n for t1 in terms_list: \n for t2 in terms_list: \n if t1 in t2 and t1 != t2: \n overlap[t1].append(t2)\n return overlap\n\n\n\nif __name__ == \"__main__\": \n parser = ArgumentParser()\n parser.add_argument(\"--gold\", required=True, help=\"Path to the gold standard (json)\")\n parser.add_argument(\"--pred\", required=True, help=\"Path to the prediction file (sem)\")\n parser.add_argument(\"--terms_in_dev\", default=\"sadhukhan_files/myWords_present_in_dev.txt\", help=\"Path to file with custom list of medical terms, only thos present in dev(train+devtest)\")\n parser.add_argument(\"--terms\", default=\"sadhukhan_files/myWords.txt\", help=\"Path to file with custom list of medical terms\")\n parser.add_argument(\"--normedterms\", default=\"sadhukhan_files/NorMedTermCondition.txt\", help=\"Path to file with predefined terms related to conditions\")\n parser.add_argument(\"--testset_ids\", required=True, help=\"Path to file containing sent_ids of sents in heldout test set, separated by commas\")\n parser.add_argument(\"--testset_type\", required=True, help=\"A short string to add to the output filename, to separate results for different test sets\")\n parser.add_argument(\"--output_file\", default=\"evaluation_sadhukhan_GOLD_marie_NEGATED_SENTS.txt\")\n\n args = parser.parse_args()\n\n g_sents, p_sents, terms, terms_pred = None, None, None, None \n\n with open(args.gold, encoding=\"utf8\") as g, open(args.pred, encoding=\"utf8\") as p, open(args.terms, encoding=\"utf8\") as t, open(args.terms_in_dev, encoding=\"utf8\") as tdev, open(args.normedterms, encoding=\"utf8\") as nmt, open(args.testset_ids, encoding=\"utf8\") as test:\n test_ids = test.read().split(\",\")\n \n g_sents = [s for s in json.load(g) if s[\"sent_id\"] in test_ids]\n #p_sents = [word_line for sent in p.read().split(\"\\n\\n\") for word_line in sent.split(\"\\n\") if sent != '' and word_line.split(\"\\t\")[1] in test_ids]\n p_sents = [[word_line.split(\"\\t\") for word_line in sent.split(\"\\n\") if word_line.split(\"\\t\")[1] in test_ids] for sent in p.read().split(\"\\n\\n\") if sent != '']\n p_sents = [s for s in p_sents if len(s) > 0]\n\n terms = [line.strip().lower() for line in t if line != '']\n normedterms = [line.strip().lower() for line in nmt if line != '']\n\n # All terms, including those custom terms only present in held-out testset\n terms += normedterms # Use both the terms in myWords.txt and those in the large NorMedTermClinical.txt file\n\n # The terms to look for in pred: do not include the custom terms only present in held-out testset\n terms_pred = [line.strip().lower() for line in tdev if line != ''] + normedterms\n\n\n print(\"Terms:\", len(terms))\n terms += [t.replace(\",\", \"\") for t in terms if t.replace(\",\", \"\") not in terms] # Sadhukhan does this\n print(\"Terms after adding terms with commas removed:\", len(terms))\n\n print(\"Terms available for recognition:\", len(terms_pred))\n terms_pred += [t.replace(\",\", \"\") for t in terms_pred if t.replace(\",\", \"\") not in terms_pred]\n print(\"Terms available for recognition, after adding terms with commas removed::\", len(terms_pred))\n\n print(\"GOLD:\", len(g_sents))\n print(g_sents[:10])\n\n print(\"PRED:\", len(p_sents))\n for s in p_sents[:10]: \n print(s)\n print()\n\n terms = sorted(list(set(terms))) # one term occurs twice in the original list\n terms_pred = sorted(list(set(terms_pred)))\n print(\"Terms after removing duplicates:\", len(terms))\n #print(\"set(terms), lowercased:\", len(set([t.lower() for t in terms])))\n print(terms[:10])\n print(\"Terms available for recognition, after removing duplicates:\", len(terms_pred))\n print(\"len(test_ids):\", len(test_ids))\n \n overlapping_terms = get_overlapping_terms(terms)\n\n all_occurrences_boolean_map = defaultdict(lambda: defaultdict(lambda: []))\n\n # Count terms (negated and non negated) in gold \n for term in terms: \n re_term = term.replace(\"-\", \"\\-\")\n re_term = re_term.replace(\"*\", \"\\*\")\n\n for sent in g_sents: # json \n matches = re.finditer(rf'\\b(? sent_id -> list((span, bool) for each occurrence)\n # Count terms (negated and non negated) in pred\n for term in all_occurrences_boolean_map: # loop through the instances in gold corpus and check if they are predicted as negated or not in pred\n re_term = term.replace(\"-\", \"\\-\")\n re_term = re_term.replace(\"*\", \"\\*\")\n \n for i in range(len(p_sents)): \n sent_id = p_sents[i][0][1]\n #print(\"sent_id:\", sent_id)\n\n # Find cue indices\n cue_indices = [j for j in range(7, len(p_sents[i][0])) if len(p_sents[i][0]) > 8 and (j-7) % 3 == 0]\n #print(cue_indices)\n\n #full_sent = \" \".join([p_sents[i][j][3] for j in range(len(p_sents[i]))])\n full_sent = g_sents[i]['text'] # Something wrong with the number of spaces when joining on a single space? \n\n reg = r'\\S+'\n\n matches = re.finditer(reg, full_sent)\n word_idx_to_span = {wi:ws for wi,ws in zip([w_i for w_i in range(len(full_sent.split()))],[(m.span(0)[0],m.span(0)[1]) for m in matches])}\n\n start_i_to_word_idx = {v[0]:k for k,v in word_idx_to_span.items()} #word start index to word index \n\n #print(full_sent)\n\n pred_scopes = []\n #...\n for c_i in cue_indices: \n scope_idx = c_i+1 \n pred_scopes.append([p_sents[i][j][scope_idx] for j in range(len(p_sents[i]))])\n #print(pred_scopes) \n\n\n for span, is_neg in all_occurrences_boolean_map[term][sent_id]: \n\n NOT_PRESENT = -1\n start_w_idx = start_i_to_word_idx.get(span[0], NOT_PRESENT) \n print(\"DEBUG\", full_sent[span[0]:span[1]])\n print(full_sent)\n assert start_w_idx != NOT_PRESENT # Should not happen when we look at full words only \n\n not_matching_any_scope = True\n is_match = None # debug\n for pred_scope in pred_scopes: \n # TODO: Only count once if term is inside multiple scopes\n term_len = len(term.split()) # number of words in term \n \n is_match = True\n for p_i in range(len(pred_scope[start_w_idx:(start_w_idx)+term_len])): \n if not pred_scope[start_w_idx:(start_w_idx)+term_len][p_i].lower() == term.split()[p_i].lower():\n is_match = False\n break\n if is_match:\n if not term in terms_pred: # The model can only discover custom terms present in dev (train+devtest)\n all_pred_terms_boolean_map[term][sent_id].append((span, False))\n else: # the term is in terms_pred\n all_pred_terms_boolean_map[term][sent_id].append((span, True))\n not_matching_any_scope = False\n break\n \n if not_matching_any_scope: \n\n all_pred_terms_boolean_map[term][sent_id].append((span, False))\n\n print(\"\\nNumber of terms before greedy - GOLD:\")\n c_before_g = 0\n for t in all_occurrences_boolean_map:\n for sid in all_occurrences_boolean_map[t]: \n c_before_g += len(all_occurrences_boolean_map[t][sid])\n print(c_before_g)\n print(\"\\nNumber of terms before greedy - PRED:\")\n c_before_p = 0\n for t in all_pred_terms_boolean_map:\n for sid in all_pred_terms_boolean_map[t]: \n c_before_p += len(all_pred_terms_boolean_map[t][sid])\n print(c_before_p)\n\n\n # Take a greedy approach when multiple terms are matched in the same location - e.g. \"bivirkninger\" and \"økte bivirkninger\" -> only count the longest one \n print(\"\\nGREEDY APPROACH - GOLD\")\n for term in overlapping_terms: \n # For gold: \n for sid in all_occurrences_boolean_map[term]:\n term_occurrences = all_occurrences_boolean_map[term][sid]\n idx_to_pop = []\n term_spans = [s for s,_ in term_occurrences]\n for o_term in overlapping_terms[term]:\n o_term_occurrences = all_occurrences_boolean_map[o_term][sid]\n o_term_spans = [s for s,_ in o_term_occurrences]\n # If a span in o_term_spans overlaps with a span in term_spans: remove corresponding element in term_occurrences\n for start, end in o_term_spans:\n for i in range(len(term_spans)): \n ts_start, ts_end = term_spans[i][0], term_spans[i][1]\n if ts_start >= start and ts_end <= end: \n idx_to_pop.append(i)\n #print(\"term:\", term, \"o_term:\", o_term)\n\n all_occurrences_boolean_map[term][sid] = [term_occurrences[i] for i in range(len(term_occurrences)) if i not in idx_to_pop]\n\n print(\"\\nGREEDY APPROACH - PRED\")\n for term in overlapping_terms:\n # Do the same as above for preds: \n for sid in all_pred_terms_boolean_map[term]:\n term_occurrences = all_pred_terms_boolean_map[term][sid]\n idx_to_pop = []\n term_spans = [s for s,_ in term_occurrences]\n for o_term in overlapping_terms[term]:\n o_term_occurrences = all_pred_terms_boolean_map[o_term][sid]\n o_term_spans = [s for s,_ in o_term_occurrences]\n # If a span in o_term_spans overlaps with a span in term_spans: remove corresponding element in term_occurrences\n for start, end in o_term_spans:\n for i in range(len(term_spans)): \n ts_start, ts_end = term_spans[i][0], term_spans[i][1]\n if ts_start >= start and ts_end <= end: \n idx_to_pop.append(i)\n #print(\"term:\", term, \"o_term:\", o_term)\n\n \n all_pred_terms_boolean_map[term][sid] = [term_occurrences[i] for i in range(len(term_occurrences)) if i not in idx_to_pop]\n\n print(\"\\nNumber of terms after greedy - GOLD:\")\n c_after_g = 0\n for t in all_occurrences_boolean_map:\n for sid in all_occurrences_boolean_map[t]: \n c_after_g += len(all_occurrences_boolean_map[t][sid])\n print(c_after_g)\n print(\"\\nNumber of terms after greedy - PRED:\")\n c_after_p = 0\n for t in all_pred_terms_boolean_map:\n for sid in all_pred_terms_boolean_map[t]: \n c_after_p += len(all_pred_terms_boolean_map[t][sid])\n print(c_after_p)\n\n\n # PRINT RESULT FOR GOLD\n print(\"\\n----- GOLD -----\")\n print(\"\\nBEFORE REMOVAL OF DUPLICATES\")\n all_occurrences = []\n for k in all_occurrences_boolean_map:\n for sid in all_occurrences_boolean_map[k]:\n for occ in all_occurrences_boolean_map[k][sid]:\n all_occurrences.append(occ)\n print(len(all_occurrences))\n print()\n\n\n for k in all_occurrences_boolean_map: \n for sid in all_occurrences_boolean_map[k]: \n all_occurrences_boolean_map[k][sid] = sorted(list(set([occ for occ in all_occurrences_boolean_map[k][sid]])))\n\n\n print(\"\\nAFTER REMOVAL OF DUPLICATES\")\n all_occurrences = []\n for k in all_occurrences_boolean_map:\n for sid in all_occurrences_boolean_map[k]:\n for occ in all_occurrences_boolean_map[k][sid]:\n all_occurrences.append(occ)\n print(len(all_occurrences))\n print()\n\n\n ########################################\n # Write gold standard terms to file: \n c = 0\n with open(args.output_file, 'w', encoding='utf8') as f:\n for t in all_occurrences_boolean_map: \n for sent_id in all_occurrences_boolean_map[t]:\n for span, inscope in all_occurrences_boolean_map[t][sent_id]:\n if inscope: \n f.write(f\"\\nt: {t}, SPAN: {span}\\n\")\n sentence = [s['text'] for s in g_sents if s['sent_id'] == sent_id]\n assert len(sentence) == 1\n f.write(f\"{sent_id}: {sentence[0]}\\n\")\n c += 1\n \n f.write(f\"\\n\\nTOTAL TERMS INSIDE GOLD NEGATION SCOPES: {c}\\n\")\n\n print(f\"GOLD TERMS WRITTEN TO FILE {args.output_file}\")\n\n ########################################\n\n\n # PRINT RESULT FOR PRED\n print(\"\\n----- PREDS -----\")\n print(\"\\nBEFORE REMOVAL OF DUPLICATES\")\n all_occurrences = []\n for k in all_pred_terms_boolean_map:\n for sid in all_pred_terms_boolean_map[k]:\n for occ in all_pred_terms_boolean_map[k][sid]:\n all_occurrences.append(occ)\n print(len(all_occurrences))\n print()\n\n\n for k in all_pred_terms_boolean_map: \n for sid in all_pred_terms_boolean_map[k]: \n all_pred_terms_boolean_map[k][sid] = sorted(list(set([occ for occ in all_pred_terms_boolean_map[k][sid]])))\n\n\n print(\"\\nAFTER REMOVAL OF DUPLICATES\")\n all_occurrences = []\n for k in all_pred_terms_boolean_map:\n for sid in all_pred_terms_boolean_map[k]:\n for occ in all_pred_terms_boolean_map[k][sid]:\n all_occurrences.append(occ)\n print(len(all_occurrences))\n print()\n\n\n sanity_check(all_occurrences_boolean_map, all_pred_terms_boolean_map)\n #sanity_check_no_sorting(all_occurrences_boolean_map, all_pred_terms_boolean_map)\n\n # COMPUTE F1\n true_pos, tp_instances = tp(all_occurrences_boolean_map, all_pred_terms_boolean_map)\n true_neg, tn_instances = tn(all_occurrences_boolean_map, all_pred_terms_boolean_map)\n false_pos, fp_instances = fp(all_occurrences_boolean_map, all_pred_terms_boolean_map)\n false_neg, fn_instances = fn(all_occurrences_boolean_map, all_pred_terms_boolean_map)\n print()\n print(\"TP:\", true_pos)\n print(\"TN:\", true_neg)\n print(\"FP:\", false_pos)\n print(\"FN:\", false_neg)\n\n prec = precision(true_pos, false_pos)\n rec = recall(true_pos, false_neg)\n print(\"Precision:\", prec)\n print(\"Recall:\", rec)\n\n f1_score = f1(prec, rec)\n\n print(\"F1 score:\", f1_score)\n\n with open(f'{args.pred[:-4]}_RESULTS_marie_gold_{args.testset_type}.txt', 'w', encoding=\"utf8\") as res:\n res.write(f\"----- ALL TP -----\\n\")\n res.write(\"\\n\".join([str(i) for i in tp_instances]))\n res.write(\"\\n\\n\")\n res.write(f\"----- ALL TN -----\\n\")\n res.write(\"\\n\".join([str(i) for i in tn_instances]))\n res.write(\"\\n\\n\")\n res.write(f\"----- ALL FP -----\\n\")\n res.write(\"\\n\".join([str(i) for i in fp_instances]))\n res.write(\"\\n\\n\")\n res.write(f\"----- ALL FN -----\\n\")\n res.write(\"\\n\".join([str(i) for i in fn_instances]))\n res.write(\"\\n\\n\")\n res.write(f\"Gold: {args.gold}\\n\")\n res.write(f\"Pred: {args.pred}\\n\")\n res.write(f\"Test ids: {args.testset_ids}\\n\")\n res.write(f\"TP: {true_pos}\\n\")\n res.write(f\"TN: {true_neg}\\n\")\n res.write(f\"FP: {false_pos}\\n\")\n res.write(f\"FN: {false_neg}\\n\")\n res.write(f\"Precision: {prec}\\n\")\n res.write(f\"Recall: {rec}\\n\")\n res.write(f\"F1: {f1_score}\\n\")\n\n\n","repo_name":"marieef/master-thesis_code","sub_path":"compare_to_norwegian_negex/evaluation_sadhukhan_GOLD_marie.py","file_name":"evaluation_sadhukhan_GOLD_marie.py","file_ext":"py","file_size_in_byte":21411,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"20"} +{"seq_id":"28511781228","text":"import streamlit as st\nimport pydeck as pdk\n\nUK_ACCIDENTS_DATA = 'https://raw.githubusercontent.com/visgl/deck.gl-data/master/examples/3d-heatmap/heatmap-data.csv'\n\nlayer = pdk.Layer(\n 'HexagonLayer', # `type` positional argument is here\n UK_ACCIDENTS_DATA,\n get_position=['lng', 'lat'],\n auto_highlight=True,\n elevation_scale=50,\n pickable=True,\n elevation_range=[0, 3000],\n extruded=True,\n coverage=1)\n\n# Set the viewport location\nview_state = pdk.ViewState(\n longitude=-1.415,\n latitude=52.2323,\n zoom=6,\n min_zoom=5,\n max_zoom=15,\n pitch=40.5,\n bearing=-27.36)\n\nst.pydeck_chart(pdk.Deck(\n map_style='mapbox://styles/mapbox/light-v9',\n initial_view_state=view_state,\n layers=[\n layer\n ]\n))","repo_name":"neibla/streamlit-map-performance-comparison","sub_path":"app.py","file_name":"app.py","file_ext":"py","file_size_in_byte":760,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"20"} +{"seq_id":"72567880689","text":"arr=list(map(int,input().split()))\n\nn=len(arr)\nprint(arr)\np=int(input())\nele=int(input(\"Enter a number to be inserted\"))\narr.append(0)\nfor i in range(n,p-1,-1):\n\tarr[i]=arr[i-1]\n\tprint(arr)\n\tprint(i)\narr[i]=ele\n\nprint(arr)\n\t\n","repo_name":"anukaal/python_practice","sub_path":"1.py","file_name":"1.py","file_ext":"py","file_size_in_byte":225,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"20"} +{"seq_id":"25847930718","text":"#!/usr/bin/env python\nfrom time import sleep\nimport dbus\nimport sys\n\nrx_name = \"org.openmokast.Receiver\"\nrx_object_path = \"/org/openmokast/Receiver\"\nsrg_ensemble_freq = \"223936\"\n\nclass ProgrammeNotInEnsembleError(Exception):\n pass\n\nclass OpenmokastReceiverRemote(object):\n\n def __init__(self):\n self.o = self._getControlObject()\n\n def _getControlObject(self):\n \"\"\"Connect to dbus and initialise object to talk with\n openmokast\"\"\"\n bus = dbus.SessionBus()\n obj = bus.get_object(rx_name, rx_object_path)\n\n return obj\n\n def tune(self, frequency):\n \"\"\"Tune to the specified frequency given in kHz\"\"\"\n mode = 0\n self.o.Tune(dbus.UInt32(frequency), dbus.UInt32(mode))\n\n def getstatus(self):\n print(str(self.o.GetStatus()))\n\n def showensemble(self):\n services = self.o.GetServiceArray()\n print(\"services\")\n print(\"\\n\".join([str(i) + \" \" + str(j) for i,j in zip(*services[0:2])]))\n\n print(\"components\")\n for s, name in zip(services[0], services[1]):\n print(str(name))\n components = self.o.GetComponentArray(s)\n for chan, comp_name in zip(*components[0:2]):\n print(\"{0}\".format(chan))\n print(\"\")\n\n def get_programme_data(self, programme):\n \"\"\"Get the service id, the component id for the specified programme\"\"\"\n services = self.o.GetServiceArray()\n servicenames = [s.strip() for s in services[1]]\n if programme not in servicenames:\n raise ProgrammeNotInEnsembleError(\"Programme '{0}' not found in ensemble '{1}'\".format(\n programme, self.o.GetStatus()))\n\n serviceid = services[0][servicenames.index(programme)]\n\n components = self.o.GetComponentArray(serviceid)\n\n return serviceid, components[0][0] #default channel\n\n def print_programme_transport_mode(self, programme):\n sid, compid = self.get_programme_data(programme)\n\n tm, _ = self.o.GetTransportMode(sid, compid)\n\n tmodes = {0: \"AUDIO STREAM\",\n 1: \"DATA STREAM\",\n 2: \"FIDC SERVICE\",\n 3: \"DATA PACKET SERVICE\"}\n\n if tm in tmodes:\n print(tmodes[tm])\n else:\n print(\"Unknown transport mode \" + str(tm))\n\n def set_destination(self, programme, destination_ip, destination_port):\n #setdestination 16449 17313 10 239.10.10.1 2720 udp\n # EId SId subch\n eid = self.o.GetEnsemble()[0]\n sid, subch = self.get_programme_data(programme)\n\n self.o.SetDestination(eid, sid, subch, destination_ip, dbus.UInt32(destination_port))\n\n\n\n def start_decoding_programme(self, programme):\n destination = self.o.StartDecoding(*self.get_programme_data(programme))[0]\n\n return str(destination)\n\n def stop_decoding_programme(self, programme):\n success = self.o.StopDecoding(*self.get_programme_data(programme))\n\n return success\n\n\n\n\nif __name__ == \"__main__\":\n import time\n rc = OpenmokastReceiverRemote()\n if len(sys.argv) > 1 and sys.argv[1] == \"tune\":\n print(\"tuning\")\n rc.tune(srg_ensemble_freq)\n #sleep(1)\n rc.showensemble()\n try:\n print(rc.stop_decoding_programme(\"COULEUR 3\"))\n time.sleep(1)\n print(rc.set_destination(\"COULEUR 3\", \"239.10.10.1\", 2720))\n time.sleep(1)\n print(rc.start_decoding_programme(\"COULEUR 3\"))\n except ProgrammeNotInEnsembleError:\n print(\"COULEUR 3 not found\")\n","repo_name":"ebu/ebu-broadcast-hotspot","sub_path":"dbus/openmokast_dbus_client.py","file_name":"openmokast_dbus_client.py","file_ext":"py","file_size_in_byte":3536,"program_lang":"python","lang":"en","doc_type":"code","stars":2,"dataset":"github-code","pt":"20"} +{"seq_id":"44543231656","text":"pattern=\"ABACBBACEEEEEE\"\ndict={}\nfor ch in pattern:\n if ch not in dict:\n dict[ch]=1\n else:\n dict[ch]+=1\nfor key,value in dict.items():\n print(key,\",\",value)\n\nprint(dict) \nsrtd=sorted(dict,key=dict.get)\nprint(srtd)\nresult=sorted(dict,key=dict.get,reverse=True)\nprint(\"Maximum occuring character\",result[0])","repo_name":"FeminaAnsar/luminarpython","sub_path":"pythoncollection/dictionary/highfreqword.py","file_name":"highfreqword.py","file_ext":"py","file_size_in_byte":328,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"20"} +{"seq_id":"32265393598","text":"import io\n\nfrom hamcrest import all_of\nfrom hamcrest import assert_that\nfrom hamcrest import contains_inanyorder\nfrom hamcrest import ends_with\nfrom hamcrest import equal_to\nfrom hamcrest import equal_to_ignoring_whitespace\nfrom hamcrest import has_items\nfrom hamcrest import starts_with\n\n\ndef assert_generates_config(generator, expected):\n output = io.StringIO()\n generator.generate(output)\n\n assert_config_equal(output.getvalue(), expected)\n\n\ndef assert_config_equal(config, expected):\n actual_lines = _clean_lines(config)\n expected_lines = _clean_lines(expected)\n\n assert_that('\\n'.join(actual_lines), equal_to('\\n'.join(expected_lines)))\n\n\ndef assert_section_equal(config, expected):\n config = _clean_lines(config)\n expected = _clean_lines(expected)\n assert_lines_equal(config, expected)\n\n\ndef assert_lines_equal(config, expected):\n assert_that(config[0], _equal_to_section_name(expected[0]))\n assert_that(config[1:], contains_inanyorder(*_section_body_matchers(expected[1:])))\n\n\ndef assert_lines_contain(config, expected):\n assert_that(config[0], _equal_to_section_name(expected[0]))\n assert_that(config[1:], has_items(*_section_body_matchers(expected[1:])))\n\n\ndef _equal_to_section_name(expected):\n return all_of(\n starts_with('['), ends_with(']'), equal_to_ignoring_whitespace(expected)\n )\n\n\ndef _section_body_matchers(expected):\n return [equal_to_ignoring_whitespace(line) for line in expected]\n\n\ndef _clean_lines(lines):\n result = []\n for line in lines.split('\\n'):\n line = line.lstrip()\n if line:\n result.append(line)\n return result\n","repo_name":"wazo-platform/wazo-confgend","sub_path":"wazo_confgend/generators/tests/util.py","file_name":"util.py","file_ext":"py","file_size_in_byte":1632,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"20"} +{"seq_id":"6985672142","text":"from django.core.management.base import BaseCommand, CommandError\n\nfrom roll.models import *\n\nfrom collections import namedtuple\nfrom datetime import datetime\nimport csv\nimport django\n\nfrom functools import partial\n\nfrom django.db import transaction\n\nROW_HEADER = [\n 'registry_number',\n 'name',\n 'location',\n 'establishment_type',\n 'rating',\n 'operator',\n 'owner',\n 'license',\n 'fee_paid',\n 'payment_date',\n 'telephone',\n 'fax',\n 'email',\n 'electoral_group_code',\n 'electoral_group_name',\n 'prefecture',\n 'region',\n 'island',\n 'street_number',\n 'zip_code',\n 'city',\n]\n\nclass Command(BaseCommand):\n args = ''\n help = 'Initialises the database'\n \n @transaction.commit_on_success\n def initialize_roll(self, datafile):\n if django.get_version() >= '1.5':\n write = partial(self.stdout.write, ending = '')\n else:\n write = self.stdout.write\n RollRow = namedtuple('RollRow', ROW_HEADER)\n for line, row in enumerate(\n map(lambda r: RollRow._make([s.decode('utf-8') for s in r]),\n csv.reader(open(datafile, 'rb')))):\n registry_number = row.registry_number\n name = row.name\n location, c = Location.objects.get_or_create(name=row.location)\n establishment_type, c = EstablishmentType.objects.get_or_create(\n name=row.establishment_type)\n rating, c = Rating.objects.get_or_create(name=row.rating,\n position=0)\n operator, c = Operator.objects.get_or_create(name=row.operator)\n owner, c = Owner.objects.get_or_create(name=row.owner)\n license = row.license\n if len(row.payment_date) > 0:\n payment_date = datetime.strptime(row.payment_date, '%m/%d/%Y')\n fee_payment, c = FeePayment.objects.get_or_create(\n fee_paid=row.fee_paid,\n payment_date=payment_date)\n else :\n fee_payment, c = FeePayment.objects.get_or_create(\n fee_paid=row.fee_paid)\n telephone = row.telephone\n fax = row.fax\n email = row.email\n electoral_group, c = ElectoralGroup.objects.get_or_create(\n code=row.electoral_group_code,\n name=row.electoral_group_name)\n region, c = Region.objects.get_or_create(name=row.region)\n prefecture, c = Prefecture.objects.get_or_create(\n name=row.prefecture,\n region=region)\n city, c = City.objects.get_or_create(name=row.city,\n prefecture=prefecture)\n island, c = Island.objects.get_or_create(name=row.island)\n address, c = Address.objects.get_or_create(\n street_number=row.street_number,\n zip_code=row.zip_code,\n city=city,\n island=island,\n location=location)\n establishment, c = Establishment.objects.get_or_create(\n registry_number=registry_number,\n name=name,\n establishment_type=establishment_type,\n address=address,\n rating=rating,\n operator=operator,\n owner=owner,\n license=license,\n fee_payment=fee_payment,\n telephone=telephone,\n fax=fax,\n email=email,\n electoral_group=electoral_group,\n )\n if c:\n establishment.unique_id = Establishment.generate_unique_id()\n establishment.save()\n write(\"\\r{0}\".format(line+1))\n self.stdout.flush() \n write(\"\\n\")\n\n def handle(self, *args, **options):\n if len(args) != 1:\n raise CommandError(\"No input data file\")\n else:\n self.initialize_roll(args[0])\n\n","repo_name":"grnet/hch-roll","sub_path":"roll/management/commands/initialize_roll.py","file_name":"initialize_roll.py","file_ext":"py","file_size_in_byte":4067,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"20"} +{"seq_id":"19224860104","text":"\nfrom tkinter import *\nfrom time import *\n\nfnameList = [\"jeju1.gif\", \"jeju2.gif\", \"jeju3.gif\", \"jeju4.gif\", \"jeju5.gif\", \"jeju6.gif\", \"jeju7.gif\", \"jeju8.gif\", \"jeju9.gif\"]\n\nphotoList = [None] * 9\nnum = 0\nname = fnameList[0]\n\ndef clickNext():\n global num\n num += 1\n if num > 8:\n num = 0\n photo = PhotoImage(file=\"GIF/\"+ fnameList[num])\n pLabel.configure(image = photo)\n pLabel.image = photoList\n nameImage.config(text=fnameList[num]) \n\ndef clickPrev():\n global num\n num -= 1\n if num < 0:\n num = 8\n photo = PhotoImage(file= \"GIF/\"+ fnameList[num])\n pLabel.configure(image = photo)\n pLabel.image = photo\n nameImage.config(text=fnameList[num]) \n\nwindow = Tk()\nwindow.geometry(\"700x500\")\nwindow.title(\"View Photo Album\")\n\nbtnPrev = Button(window, text=\"<>\", command=clickNext)\n\n\nphoto = PhotoImage(file =\"GIF/\"+fnameList[0])\npLabel = Label(window, image= photo)\n\nbtnPrev.place(x = 250, y = 10)\nnameImage.place(x = 335, y = 10) # widget label name location\nbtnNext.place(x = 400, y = 10)\npLabel.place(x = 15, y = 50)\n\nwindow.mainloop()","repo_name":"adnkamil/lecture","sub_path":"1/10-12.py","file_name":"10-12.py","file_ext":"py","file_size_in_byte":1223,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"20"} +{"seq_id":"1662450062","text":"import random\nimport math\nimport numpy as np\n\nimport pygame\nfrom pygame.color import THECOLORS\n\nimport pymunk\nfrom pymunk.vec2d import Vec2d\nfrom pymunk.pygame_util import draw\n\n# PyGame init\nwidth = 256\nheight = 256\nnum_obstacles = 0\nradio = 3\nradio_obs = 20\n_crash_reward = -0.001\n_goal_reward = 1\n_normal_reward = -.00001\n_goal = Vec2d(0,0)\n_old_position = Vec2d(0,0)\nterminal = False\n_initial_position_agent_x = width/2\n_initial_position_agent_y = height/2 - 80\n_initial_position_goal_x = width/2\n_initial_position_goal_y = height/2 + 80\n\n\npygame.init()\nscreen = pygame.display.set_mode((width, height))\nclock = pygame.time.Clock()\n\n# Turn off alpha since we don't use it.\nscreen.set_alpha(None)\n\n# Showing sensors and redrawing slows things down.\nshow_sensors = True\ndraw_screen = True\n\n\nclass GameState:\n def __init__(self):\n\n # Global-ish.\n self.crashed = False\n self.goal_hit = False\n\n # Physics stuff.\n self.space = pymunk.Space()\n self.space.gravity = pymunk.Vec2d(0., 0.)\n\n # Create the car.\n #self.create_car(random.randint(5, (width - 5)), random.randint(5, (height-5)), radio)\n self.create_car(_initial_position_agent_x, _initial_position_agent_y, radio)\n _old_position[0] = self.car_body.position.x\n _old_position[1] = self.car_body.position.y\n print(\"old position\")\n print(_old_position)\n\n\n # Record steps.\n self.num_steps = 0\n\n # Create walls.\n static = [\n pymunk.Segment(\n self.space.static_body,\n (0, 1), (0, height), 1),\n pymunk.Segment(\n self.space.static_body,\n (1, height), (width, height), 1),\n pymunk.Segment(\n self.space.static_body,\n (width-1, height), (width-1, 1), 1),\n pymunk.Segment(\n self.space.static_body,\n (1, 1), (width, 1), 1),\n ]\n for s in static:\n s.friction = 1.\n s.group = 1\n s.collision_type = 1\n s.color = THECOLORS['red']\n self.space.add(static)\n\n # Create agents-obstacles, semi-randomly.\n self.obstacles = []\n for i in range(num_obstacles):\n self.obstacles.append(self.create_obstacle(width / 2, height / 2, radio_obs))\n #self.obstacles.append(self.create_obstacle(random.randint(5, (width - 5)), random.randint(5, (height-5)), radio))\n\n self.create_goal()\n\n\n def create_goal(self):\n if _goal[0] != 0:\n self.space.remove(self.goal_mark)\n\n _goal[0] = _initial_position_goal_x #(random.randint(60, (width - 60)) )\n _goal[1] = _initial_position_goal_y #(random.randint(60, (height - 60)) )\n print(\"Goal coordinates:\")\n print(_goal)\n self.goal_mark = pymunk.Segment(\n self.space.static_body,\n (_goal[0] - 10, _goal[1] - 10), (_goal[0] + 10, _goal[1] + 10), 10)\n self.goal_mark.group = 2\n self.goal_mark.color = THECOLORS['green']\n self.space.add(self.goal_mark)\n\n def background(self, image_file, location):\n self.image = pygame.image.load(image_file)\n self.rect = self.image.get_rect()\n self.rect.left, self.rect.top = location\n\n def create_obstacle(self, x, y, r):\n c_body = pymunk.Body(pymunk.inf, pymunk.inf)\n c_shape = pymunk.Circle(c_body, r)\n\n c_shape.elasticity = 1.0\n c_body.position = x, y\n c_body.group = 2\n c_shape.group= 2\n c_shape.color = THECOLORS[\"orange\"]\n self.space.add(c_body, c_shape)\n return c_body\n\n def create_car(self, x, y, r):\n inertia = pymunk.moment_for_circle(1, 0, 14, (0, 0))\n self.car_body = pymunk.Body(1, inertia)\n self.car_body.position = x, y\n self.car_body.group = 2\n self.car_shape = pymunk.Circle(self.car_body, r)\n self.car_shape.color = THECOLORS[\"red\"]\n self.car_shape.elasticity = 1.0\n self.car_body.angle = r\n driving_direction = Vec2d(1, 0).rotated(self.car_body.angle)\n self.car_body.apply_impulse(driving_direction)\n self.space.add(self.car_body, self.car_shape)\n\n def frame_step(self, input_actions):\n\n terminal = False\n #print(\"input_actions: \", input_actions)\n #print(\"input_actions[2]: \", input_actions[2])\n if sum(input_actions) != 1:\n raise ValueError('Multiple input actions!')\n\n #Actions: 0 do nothing, 1 turn left, 2 turn right\n if input_actions[1] == 1:\n self.car_body.angle -= .2\n elif input_actions[2] == 1: # Turn right.\n self.car_body.angle += .2\n\n # Move obstacles.\n #if self.num_steps % 50 == 0:\n #self.move_obstacles()\n\n driving_direction = Vec2d(1, 0).rotated(self.car_body.angle)\n self.car_body.velocity = 100 * driving_direction\n\n # Update the screen and stuff.\n screen.fill(THECOLORS[\"white\"])\n #load the map\n #self.background('scrSht.png', [0,0])\n #screen.blit(self.image, self.rect)\n draw(screen, self.space)\n self.space.step(1./10)\n if draw_screen:\n pygame.display.flip()\n clock.tick()\n\n # Get the current location and the readings there.\n x, y = self.car_body.position\n readings = self.get_sonar_readings(x, y, self.car_body.angle)\n #readings.append(self.car_body.position.get_dist_sqrd(_goal)/10000)\n #state = np.array([readings])\n state = np.array([[self.car_body.position[0]/width, self.car_body.position[1]/height]])\n '''\n print(\"============= State: ===================\")\n print(state)\n print(\"calculando distancia\")\n print(self.car_body.position.get_dist_sqrd(_goal)/10000)\n '''\n\n # Set the reward.\n # Car crashed when any reading == 1\n if self.car_is_crashed(readings):\n self.crashed = True\n reward = _crash_reward\n #terminal = True\n self.recover_from_crash(driving_direction)\n #print(\"=================== Craaaaasssshhhhhhhh!!! ==================\")\n elif ( (_goal[0] - 10) <= self.car_body.position[0] <= (_goal[0] + 10) ) and (_goal[1] - 10) <= self.car_body.position[1] <= (_goal[1] + 10):\n self.goal_hit = True\n reward = _goal_reward\n #print(\"*********************************************** It got the Goal!!! ************************************************************\")\n self.recover_from_goal(driving_direction)\n terminal = True\n #elif self.car_body.position.get_dist_sqrd(_goal) < _old_position.get_dist_sqrd(_goal):\n #reward = 100 / (self.car_body.position.get_dist_sqrd(_goal)/100000)\n #print(\"Reward comp 2:\")\n #print( 100 / (self.car_body.position.get_dist_sqrd(_goal)/100000) )\n else:\n #reward = - (self.car_body.position.get_dist_sqrd(_goal)/50000)\n reward = _normal_reward #( (200 - int(self.sum_readings(readings)) ) /50) - 2\n\n #print(\"Reward Total\")\n #print(reward)\n #print(state)\n\n _old_position[0] = self.car_body.position.x\n _old_position[1] = self.car_body.position.y\n #print(self.car_body.position)\n\n image_data = pygame.surfarray.array3d(pygame.display.get_surface())\n\n self.num_steps += 1\n\n #x_t, r_0, terminal = game_state.frame_step(do_nothing)\n\n return image_data, reward, terminal\n\n def move_obstacles(self):\n # Randomly move obstacles around.\n for obstacle in self.obstacles:\n speed = random.randint(5, 30)\n direction = Vec2d(1, 0).rotated(self.car_body.angle + random.randint(-2, 2))\n obstacle.velocity = speed * direction\n\n def car_is_crashed(self, readings):\n if readings[0] == 1 or readings[1] == 1 or readings[2] == 1 or readings[3] == 1 or readings[4] == 1:\n return True\n else:\n return False\n\n def recover_from_crash(self, driving_direction):\n \"\"\"\n We hit something, so recover.\n \"\"\"\n while self.crashed:\n # Go backwards.\n self.car_body.velocity = -100 * driving_direction\n self.crashed = False\n #Return to initial position\n self.car_body.position.x = _initial_position_agent_x\n self.car_body.position.y = _initial_position_agent_y\n draw(screen, self.space)\n self.space.step(1./10)\n if draw_screen:\n pygame.display.flip()\n clock.tick()\n\n '''for i in range(3):\n self.car_body.angle += .2 # Turn a little.\n #screen.fill(THECOLORS[\"red\"]) # Red is scary!\n draw(screen, self.space)\n self.space.step(1./10)\n if draw_screen:\n pygame.display.flip()\n clock.tick()'''\n\n\n def recover_from_goal(self, driving_direction):\n \"\"\"\n We get the goal something, so re-init.\n \"\"\"\n while self.goal_hit:\n #self.create_goal()\n # Go backwards.\n self.car_body.velocity = -100 * driving_direction\n self.goal_hit = False\n #Return to initial position\n self.car_body.position.x = _initial_position_agent_x\n self.car_body.position.y = _initial_position_agent_y\n draw(screen, self.space)\n self.space.step(1./10)\n if draw_screen:\n pygame.display.flip()\n clock.tick()\n\n '''for i in range(3):\n self.car_body.angle += .2 # Turn a little.\n #screen.fill(THECOLORS[\"red\"]) # Red is scary!\n draw(screen, self.space)\n self.space.step(1./10)\n if draw_screen:\n pygame.display.flip()\n clock.tick()'''\n\n def sum_readings(self, readings):\n \"\"\"Sum the number of non-zero readings.\"\"\"\n tot = 0\n for i in readings:\n tot += i\n return tot\n\n def get_sonar_readings(self, x, y, angle):\n readings = []\n \"\"\"\n Instead of using a grid of boolean(ish) sensors, sonar readings\n simply return N \"distance\" readings, one for each sonar\n we're simulating. The distance is a count of the first non-zero\n reading starting at the object. For instance, if the fifth sensor\n in a sonar \"arm\" is non-zero, then that arm returns a distance of 5.\n \"\"\"\n # Make our arms.\n arm_left_1 = self.make_sonar_arm(x, y)\n arm_left_2 = arm_left_1\n arm_middle = arm_left_1\n arm_right_1 = arm_left_1\n arm_right_2 = arm_left_1\n\n\n # Rotate them and get readings.\n readings.append(self.get_arm_distance(arm_left_1, x, y, angle, 0.35))\n readings.append(self.get_arm_distance(arm_left_2, x, y, angle, 0.75))\n readings.append(self.get_arm_distance(arm_middle, x, y, angle, 0))\n readings.append(self.get_arm_distance(arm_right_1, x, y, angle, -0.35))\n readings.append(self.get_arm_distance(arm_right_2, x, y, angle, -0.75))\n\n\n if show_sensors:\n pygame.display.update()\n\n return readings\n\n def get_arm_distance(self, arm, x, y, angle, offset):\n # Used to count the distance.\n i = 0\n\n # Look at each point and see if we've hit something.\n for point in arm:\n i += 1\n\n # Move the point to the right spot.\n rotated_p = self.get_rotated_point(\n x, y, point[0], point[1], angle + offset\n )\n\n # Check if we've hit something. Return the current i (distance)\n # if we did.\n if rotated_p[0] <= 20 or rotated_p[1] <= 20 \\\n or rotated_p[0] >= (width - 20) or rotated_p[1] >= (height - 20):\n return i # Sensor is off the screen.\n else:\n obs = screen.get_at(rotated_p)\n if self.get_track_or_not(obs) != 0:\n return i\n\n if show_sensors:\n pygame.draw.circle(screen, (255, 0, 0), (rotated_p), 1, 1)\n\n # Return the distance for the arm.\n return i\n\n def make_sonar_arm(self, x, y):\n spread = 5 # Default spread.\n distance = 3 # Gap before first sensor.\n arm_points = []\n # Make an arm. We build it flat because we'll rotate it about the\n # center later.\n for i in range(1, 40):\n arm_points.append((distance + x + (spread * i), y))\n\n return arm_points\n\n def get_rotated_point(self, x_1, y_1, x_2, y_2, radians):\n # Rotate x_2, y_2 around x_1, y_1 by angle.\n x_change = (x_2 - x_1) * math.cos(radians) + \\\n (y_2 - y_1) * math.sin(radians)\n y_change = (y_1 - y_2) * math.cos(radians) - \\\n (x_1 - x_2) * math.sin(radians)\n new_x = x_change + x_1\n new_y = height - (y_change + y_1)\n return int(new_x), int(new_y)\n\n def get_track_or_not(self, reading):\n if reading == THECOLORS['white'] or reading == THECOLORS['green']:\n return 0\n else:\n return 1\n\nif __name__ == \"__main__\":\n game_state = GameState()\n while True:\n game_state.frame_step((random.randint(0, 2)))\n","repo_name":"vhpvmx/deeprl","sub_path":"flat_game/carmunk.py","file_name":"carmunk.py","file_ext":"py","file_size_in_byte":13447,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"20"} +{"seq_id":"3115864961","text":"import robin_stocks\nimport time\n\nfrom config import settings\nfrom app.stock import infomation, analysis, trade\nfrom app.logger import logger\nfrom app.notification import email\n\n\ndef run_service():\n email.send_on_start()\n robin_stocks.login(settings.USER_EMAIL, settings.USER_PASSWORD)\n symbols = list(settings.MANAGED_STOCKS.keys())\n while True:\n holdings = None\n sleep_time = settings.OPEN_HOUR_SLEEP\n market_info = infomation.market_open_time(settings.MARKETS[0])\n if not market_info['is_open_today']:\n logger.debug(\"sleep during holiday\")\n analysis.clear_daily_storage()\n sleep_time = 60 * 60\n elif market_info['is_open_now']:\n logger.debug(\"work during open hours\")\n holdings = infomation.build_holdings(symbols)\n elif market_info['end - utcnow'] <= 0:\n logger.debug(\"sleep after market closed\")\n analysis.clear_daily_storage()\n sleep_time = 60 * 60\n elif market_info['utcnow - start'] > -60 * 5:\n logger.debug(\"work when market is about to open\")\n holdings = infomation.build_holdings(symbols)\n else:\n logger.debug(\"sleep when market has not opened yet\")\n analysis.clear_daily_storage()\n sleep_time = - int(market_info['utcnow - start']) - 60 * 3\n if holdings is not None:\n for holding in holdings:\n suggestion = analysis.analyze(holding)\n if suggestion:\n details = trade.trade(holding, **suggestion)\n if details is not None:\n logger.debug(details)\n logger.debug(holdings)\n time.sleep(sleep_time)\n","repo_name":"kaiwensun/pystock","sub_path":"app/stock/__init__.py","file_name":"__init__.py","file_ext":"py","file_size_in_byte":1740,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"20"} +{"seq_id":"30082681954","text":"import torch\nimport torch.nn as nn\nimport torch.nn.functional as F\n\n\nclass Model(nn.Module):\n def __init__(self, latent_dim, device):\n super(Model, self).__init__()\n self.device = device\n self.latent_dim = latent_dim\n self.encoder = nn.Sequential(\n nn.Conv2d(1, 32, 4, 1, 2), # B, 32, 28, 28\n nn.ReLU(True),\n nn.Conv2d(32, 32, 4, 2, 1), # B, 32, 14, 14\n nn.ReLU(True),\n nn.Conv2d(32, 64, 4, 2, 1), # B, 64, 7, 7\n )\n\n self.mu = nn.Linear(64 * 7 * 7, latent_dim)\n self.logvar = nn.Linear(64 * 7 * 7, latent_dim)\n\n self.upsample = nn.Linear(latent_dim, 64 * 7 * 7)\n self.decoder = nn.Sequential(\n nn.ConvTranspose2d(64, 32, 4, 2, 1), # B, 64, 14, 14\n nn.ReLU(True),\n nn.ConvTranspose2d(32, 32, 4, 2, 1, 1), # B, 32, 28, 28\n nn.ReLU(True),\n nn.ConvTranspose2d(32, 1, 4, 1, 2), # B, 1, 28, 28\n nn.Sigmoid()\n )\n\n def sample(self, sample_size):\n with torch.no_grad():\n sampled_x = torch.rand((sample_size, self.latent_dim)).to(self.device)\n reconstructed_x = self.decoder(self.upsample(sampled_x).view(-1, 64, 7, 7))\n return reconstructed_x\n\n def z_sample(self, mu, logvar):\n std = torch.exp(logvar / 2)\n eps = torch.rand_like(std).to(self.device)\n return mu + eps * std\n\n @staticmethod\n def loss(x, recon, mu, logvar):\n kl_divergence = -0.5 * torch.sum(1 + logvar - mu.pow(2) - logvar.exp())\n binary_cross_entropy_loss = F.binary_cross_entropy(recon, x, reduction='sum')\n return kl_divergence + binary_cross_entropy_loss\n\n def forward(self, x):\n x_latent = self.encoder(x).view(-1, 64 * 7 * 7)\n mu = self.mu(x_latent)\n logvar = self.logvar(x_latent)\n z = self.z_sample(mu=mu, logvar=logvar)\n res = self.decoder(self.upsample(z).view(-1, 64, 7, 7))\n return res, mu, logvar\n","repo_name":"davidlevinwork/VAE","sub_path":"VAE.py","file_name":"VAE.py","file_ext":"py","file_size_in_byte":2013,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"20"} +{"seq_id":"41487628289","text":"import datetime\n\nfrom django.core.exceptions import ValidationError\nfrom django.forms import ModelForm, Form, MultipleChoiceField\n\nfrom .models import Card, Product, Category\n\n \n\nclass CardCreationForm(ModelForm):\n \"\"\" Form for creation Card instance\"\"\"\n\n class Meta:\n model = Card\n exclude = ['user']\n \n \n def clean(self):\n super(CardCreationForm, self).clean()\n \n card_number = self.cleaned_data.get('number')\n \n validity_period = self.cleaned_data.get('validity_period')\n date = datetime.datetime.strptime(validity_period, \"%m/%y\").date()\n \n if datetime.date.today() > date or len(validity_period) != 5:\n self._errors['validity_period'] = self.error_class(['Invalid validity period'])\n \n if len(card_number) != 16:\n self._errors['number'] = self.error_class(['Invalid card number'])\n \n return self.cleaned_data\n\n\n\n def __init__(self, *args, **kwargs):\n super(CardCreationForm, self).__init__(*args, **kwargs)\n for visible in self.visible_fields():\n visible.field.widget.attrs['class'] = 'form-control'\n\n\n\nclass CategoryCreationForm(Form):\n # CHOISES = tuple((num, category) for num, category in enumerate(Category.objects.all()))\n\n #categories = MultipleChoiceField(choices=CHOISES)\n\n \n def __init__(self, *args, **kwargs) -> None:\n # self.categories = tuple((num, category) for num, category in enumerate(Category.objects.all()))\n super().__init__(*args, **kwargs)\n\n\nclass ProductCreationForm(ModelForm):\n \"\"\" Form for creation Publication instance\"\"\"\n\n class Meta:\n model = Product\n exclude = ['image_url', 'category']\n\n def __init__(self, *args, **kwargs):\n super(ProductCreationForm, self).__init__(*args, **kwargs)\n for visible in self.visible_fields():\n visible.field.widget.attrs['class'] = 'form-control'\n","repo_name":"EgorRPikulik/Shop","sub_path":"shop/products/forms.py","file_name":"forms.py","file_ext":"py","file_size_in_byte":1966,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"20"} +{"seq_id":"2353274171","text":"\"\"\"Module to handle connexions to FFCAM extranet.\n\"\"\"\nimport traceback\nfrom datetime import datetime, date\nfrom flask import current_app\n\nfrom zeep import Client\nfrom zeep.exceptions import Error as ZeepError\n\nfrom collectives.models import Gender, Configuration\nfrom collectives.utils.time import current_time\n\n\nLICENSE_RENEWAL_MONTH = 9\n\"\"\" Month of license start.\n\nIf a license has been renewed after RENEWAL_MONTH of year Y,\nthen it is valid until EXPIRY_MONTH of year Y+1; else it is\nonly valid until EXPITY_MONTH of year Y.\n\n:type: int\n\"\"\"\nLICENSE_EXPIRY_MONTH = 10\n\"\"\" Month of license end.\n\n:type: int\n\"\"\"\n\n\nclass LicenseInfo:\n \"\"\"Licence information as retrieved from FFCAM servers.\"\"\"\n\n exists = False\n \"\"\" If licence exists.\n :type: boolean\n \"\"\"\n renewal_date = None\n \"\"\" Date of renewal of the licence.\n\n :type: :py:class:`datetime.date`\n \"\"\"\n\n def expiry_date(self):\n \"\"\"Get licence expiration date.\n\n Licence expire at the start of the month `LICENSE_EXPIRY_MONTH` which follow\n the renewal date.\n\n :return: License expiration date. `None` if renewal_date is `None`\n :rtype: :py:class:`datetime.date`\n\n \"\"\"\n if self.renewal_date is None:\n return None\n\n year = self.renewal_date.year\n if self.renewal_date.month >= LICENSE_RENEWAL_MONTH:\n year = year + 1\n return date(year, LICENSE_EXPIRY_MONTH, 1)\n\n def is_valid_at_time(self, time):\n \"\"\"Check if license is valid at a given date.\n\n :param time: Date to test license validity.\n :type time: :py:class:`datetime.date`\n :return: True if license is valid\n :rtype: boolean\n \"\"\"\n if not self.exists:\n return False\n expiry = self.expiry_date()\n return expiry is None or expiry > time.date()\n\n\nclass UserInfo:\n \"\"\"User information as retrieved from FFCAM servers.\"\"\"\n\n is_valid = False\n \"\"\" True if user exists on servers.\n\n :type: boolean \"\"\"\n\n first_name = \"\"\n \"\"\" User first name.\n\n :type: String \"\"\"\n\n last_name = \"\"\n \"\"\" User last name.\n\n :type: String \"\"\"\n\n email = \"\"\n \"\"\" User email.\n\n :type: String \"\"\"\n\n phone = \"\"\n \"\"\" User phone.\n\n :type: String \"\"\"\n\n qualite = \"\"\n \"\"\" User title. \"titre de civilité\".\n\n Can be `M` `Mme` `Mlle`. Is used to guess gender.\n\n :type: String \"\"\"\n\n date_of_birth = None\n \"\"\" User date of birth.\n\n :type: :py:class:`datetime.date`\n \"\"\"\n\n emergency_contact_name = \"\"\n \"\"\" User Emergency contact name.\n\n :type: string\n \"\"\"\n\n emergency_contact_phone = \"\"\n \"\"\" User Emergency contact phone.\n\n :type: string\n \"\"\"\n\n license_category = \"\"\n \"\"\" User license category.\n\n :type: string\n \"\"\"\n\n is_test = False\n \"\"\" Indicates whether this object represents a test user or contains actual\n data from the FFCAM server.\n\n :type: boolean \"\"\"\n\n\ndef sync_user(user, user_info, license_info):\n \"\"\"Populate a user object with user and license info from FFCAM servers.\n\n :param user: User to populate.\n :type user: :py:class:`collectives.models.user.User`\n :param user_info: User info from FFCAM server used to populate `user`.\n :type user_info: :py:class:`UserInfo`\n :param license_info: License info from FFCAM server used to populate `user`.\n :type license_info: :py:class:`UserInfo`\n \"\"\"\n\n user.mail = user_info.email\n user.date_of_birth = user_info.date_of_birth\n user.first_name = user_info.first_name\n user.last_name = user_info.last_name\n user.phone = user_info.phone\n user.emergency_contact_name = user_info.emergency_contact_name\n user.emergency_contact_phone = user_info.emergency_contact_phone\n user.license_expiry_date = license_info.expiry_date()\n user.license_category = user_info.license_category\n user.last_extranet_sync_time = current_time()\n user.gender = Gender.Man if user_info.qualite == \"M\" else Gender.Woman\n user.is_test = user_info.is_test\n\n\nclass ExtranetError(Exception):\n \"\"\"An exception indicating that something has gone wrong with extranet API\"\"\"\n\n pass\n\n\nclass ExtranetApi:\n \"\"\"SOAP Client to retrieve information from FFCAM servers.\"\"\"\n\n soap_client = None\n \"\"\" SOAP client object user to connect to FFCAM client.\n\n :type: :py:class:`zeep.Client`\n \"\"\"\n\n auth_info = None\n \"\"\" Authentication information to connect to SOAP server.\n\n :type: dictionnary\n \"\"\"\n\n app = None\n \"\"\" Current flask application.\n\n :type: :py:class:`flask.Flask`\n \"\"\"\n\n def init_app(self, app):\n \"\"\"Initialize the extranet with the app.\n\n :param app: Current app.\n :type app: :py:class:`flask.Flask`\n \"\"\"\n self.app = app\n\n def init(self):\n \"\"\"Initialize the SOAP Client using `app` config\"\"\"\n if not self.soap_client is None:\n # Already initialized\n return\n\n config = self.app.config\n if config[\"EXTRANET_DISABLE\"]:\n current_app.logger.warning(\"extranet API disabled, using mock API\")\n return\n\n try:\n soap_client = Client(wsdl=config[\"EXTRANET_WSDL\"])\n self.auth_info = soap_client.service.auth()\n except (IOError, ZeepError) as err:\n current_app.logger.error(f\"Error loading extranet WSDL: {err}\")\n current_app.logger.error(traceback.format_stack())\n raise ExtranetError() from err\n\n self.auth_info[\"utilisateur\"] = Configuration.EXTRANET_ACCOUNT_ID\n self.auth_info[\"motdepasse\"] = Configuration.EXTRANET_ACCOUNT_PWD\n self.soap_client = soap_client.service\n\n def disabled(self):\n \"\"\"Check if soap client has been initialized.\n\n If soap client has not been initialized, it means we are in dev mode.\n\n :return: True if ExtranetApi is disabled.\n :rtype: boolean\n \"\"\"\n return self.soap_client is None\n\n def check_license(self, license_number):\n \"\"\"Get information on a license from FFCAM server.\n\n :param license_number: License to get information about.\n :type license_number: string\n :return: Licence information\n :rtype: :py:class:`LicenseInfo`\n \"\"\"\n\n self.init()\n info = LicenseInfo()\n\n if self.disabled():\n # Dev mode, every license is valid\n info.exists = True\n info.renewal_date = datetime.now()\n return info\n\n try:\n result = self.soap_client.verifierUnAdherent(\n connect=self.auth_info, id=license_number\n )\n except (IOError, AttributeError, ZeepError) as err:\n current_app.logger.error(\n f\"Error calling extranet 'verifierUnAdherent' : {err}\"\n )\n current_app.logger.error(traceback.format_stack())\n raise ExtranetError() from err\n\n if result[\"existe\"] == 1:\n try:\n info.renewal_date = datetime.strptime(\n result[\"inscription\"], \"%Y-%m-%d\"\n ).date()\n info.exists = True\n except ValueError:\n # Date parsing as failed, this happens for exprired licenses\n # which return '0000-00-00' as date\n # In that case simply return an invalid license\n pass\n\n return info\n\n def fetch_user_info(self, license_number):\n \"\"\"Get user information on a license from FFCAM server.\n\n :param license_number: User license to get information about.\n :type license_number: string\n :return: Licence information, or None in case of API error\n :rtype: :py:class:`UserInfo`\n \"\"\"\n self.init()\n info = UserInfo()\n\n if self.disabled():\n # Dev mode, cannot fetch user info, return test data\n info.is_valid = True\n info.first_name = \"User\"\n info.last_name = license_number\n info.email = license_number + \"@cafannecy.fr\"\n info.date_of_birth = date(1970, 1, 1)\n return info\n\n try:\n result = self.soap_client.extractionAdherent(\n connect=self.auth_info, id=license_number\n )\n except (IOError, AttributeError, ZeepError) as err:\n current_app.logger.error(\n f\"Error calling extranet 'extractionAdherent' : {err}\"\n )\n current_app.logger.error(traceback.format_stack())\n raise ExtranetError() from err\n\n info.first_name = result[\"prenom\"]\n info.last_name = result[\"nom\"]\n info.phone = result[\"portable\"]\n info.email = result[\"email\"]\n info.emergency_contact_name = result[\"accident_qui\"] or \"Non renseigné\"\n info.emergency_contact_phone = result[\"accident_tel\"] or \"Non renseigné\"\n info.license_category = result[\"categorie\"]\n info.date_of_birth = datetime.strptime(\n result[\"date_naissance\"], \"%Y-%m-%d\"\n ).date()\n info.qualite = result[\"qualite\"]\n info.is_valid = True\n\n return info\n\n\napi = ExtranetApi()\n\"\"\" ExtranetApi object that will handle request to FFCAM servers.\n\n`api` requires to be initialized with :py:meth:`ExtranetApi.init_app` to be used.\n\n:type: :py:class:`ExtranetApi`\n\"\"\"\n","repo_name":"Club-Alpin-Annecy/collectives","sub_path":"collectives/utils/extranet.py","file_name":"extranet.py","file_ext":"py","file_size_in_byte":9337,"program_lang":"python","lang":"en","doc_type":"code","stars":13,"dataset":"github-code","pt":"20"} +{"seq_id":"38027704556","text":"from . import operasi\n\nDB_NAMA = \"data.txt\"\nTEMPLATE = {\n \"pk\":\"XXXXXX\",\n \"date\":\"yyyy-mm-dd\",\n \"judul\":255*\" \",\n \"penulis\":255*\" \",\n \"tahun\":\"yyyy\"\n}\n\n\ndef init_console():\n try:\n with open(DB_NAMA,\"r\") as file:\n print(\"database tersedia, init selesai\")\n \n except:\n print(\"database tidak ditemukan, silakan membuat database baru\")\n operasi.create_fist_data()","repo_name":"rizkikurni/latihanpython","sub_path":"latihan62-crud-versi-kelas-terbuka/CRUD/database.py","file_name":"database.py","file_ext":"py","file_size_in_byte":414,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"20"} +{"seq_id":"22315802009","text":"FILE_PATH = \"books/frank.txt\"\n\n\ndef count_words(text):\n return len(text.split())\n\n\ndef count_letters(text):\n letters_map = {}\n\n for letter in text.lower():\n if letter in letters_map:\n letters_map[letter] += 1\n else:\n letters_map[letter] = 1\n\n return letters_map\n\n\ndef print_report(file_path, words_count, letters_map):\n print(f\"\\n--- Begin report of {file_path} ---\\n\")\n\n print(f\"{words_count} words found in the document\\n\")\n\n letters = list(letters_map)\n letters.sort()\n for letter in letters:\n if not letter.isalpha():\n continue\n\n print(f\"The {letter} character was found {letters_map[letter]} times\")\n\n print(\"\\n--- End report ---\")\n\n\nwith open(FILE_PATH) as f:\n file_contents = f.read()\n\nprint_report(FILE_PATH, count_words(file_contents), count_letters(file_contents))\n","repo_name":"brutalv4/bookbot","sub_path":"main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":869,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"20"} +{"seq_id":"22607518962","text":"import garlicsim\n\nfrom .state import State\n\nENDABLE = False\nPROBLEM = None\nVALID = True\nCONSTANT_CLOCK_INTERVAL = None\nHISTORY_DEPENDENT = True\nN_STEP_FUNCTIONS = 1\nDEFAULT_STEP_FUNCTION = State.history_step\nDEFAULT_STEP_FUNCTION_TYPE = \\\n garlicsim.misc.simpack_grokker.step_types.HistoryStep\nCRUNCHERS_LIST = [garlicsim.asynchronous_crunching.crunchers.ThreadCruncher]","repo_name":"cool-RR/GarlicSim","sub_path":"garlicsim/test_garlicsim/test_asynchronous_crunching/simpacks/history_dependent_simpack/_test_settings.py","file_name":"_test_settings.py","file_ext":"py","file_size_in_byte":373,"program_lang":"python","lang":"en","doc_type":"code","stars":68,"dataset":"github-code","pt":"20"} +{"seq_id":"3151900378","text":"#!/usr/bin/python3\n\"\"\"\n Search 5 twits\n\"\"\"\n\nimport requests\nfrom sys import argv\nimport base64\n\nif __name__ == \"__main__\":\n c_key = argv[1]\n c_secret = argv[2]\n str_search = argv[3]\n headers = {}\n url = 'https://api.twitter.com/1.1/search/tweets.json?q='\n url += '{}&count=5'.format(str_search)\n header = {}\n r = requests.get(url, headers=header)\n for c in r.json():\n print(\"[{}] {} by {}\".format(c.get(\"id\"\n ), c.get(\"text\"\n ), c.get(\"user\"\n ).get(\"name\"\n )))\n","repo_name":"muhabeid/alx-higher_level_programming","sub_path":"0x11-python-network_1/103-search_twitter.py","file_name":"103-search_twitter.py","file_ext":"py","file_size_in_byte":717,"program_lang":"python","lang":"en","doc_type":"code","stars":3,"dataset":"github-code","pt":"20"} +{"seq_id":"40774434052","text":"import numpy as np\nimport pandas as pd\nfrom pandas import DataFrame\n\n\ndef load_data(path: str) -> DataFrame:\n \"\"\"Loads the dataset as a pandas DataFrame\n\n Args:\n path (str): Path to the dataset CSV file\n config (DatasetConfiguration): Configuration for the loading step\n\n Returns:\n pd.DataFrame: Dataframe of the dataset\n \"\"\"\n dtype = {\n \"Host Since\": \"datetime64[ns]\",\n \"Host Response Time\": \"category\",\n \"Host Response Rate\": float,\n \"Is Superhost\": float,\n \"neighbourhood\": \"category\",\n \"Neighborhood Group\": \"category\",\n \"Postal Code\": float,\n \"Latitude\": float,\n \"Longitude\": float,\n \"Is Exact Location\": float,\n \"Property Type\": \"category\",\n \"Room Type\": \"category\",\n \"Accomodates\": float,\n \"Bathrooms\": float,\n \"Bedrooms\": float,\n \"Beds\": float,\n \"Square Feet\": float,\n \"Guests Included\": float,\n \"Min Nights\": float,\n \"Reviews\": float,\n \"First Review\": \"datetime64[ns]\",\n \"Last Review\": \"datetime64[ns]\",\n \"Overall Rating\": float,\n \"Accuracy Rating\": float,\n \"Cleanliness Rating\": float,\n \"Checkin Rating\": float,\n \"Communication Rating\": float,\n \"Location Rating\": float,\n \"Value Rating\": float,\n \"Instant Bookable\": float,\n \"Price\": float,\n }\n\n parse_dates = {\"Host Since\", \"First Review\", \"Last Review\"}\n\n na_values = [\"*\", \"\", \" \"]\n\n def percentage_parser(x):\n if x in na_values:\n return np.NaN\n return x.rstrip(\"%\")\n\n df = pd.read_csv(\n path,\n usecols=dtype.keys(),\n na_values=na_values,\n true_values=[\"t\"],\n false_values=[\"f\"],\n parse_dates=list(parse_dates.intersection(dtype)),\n converters={\"Host Response Rate\": percentage_parser},\n dayfirst=True,\n )\n\n for col in df:\n df[col] = df[col].astype(dtype[col])\n return df\n","repo_name":"Seon82/projet_appr_auto","sub_path":"airbnb_prices/data/dataset.py","file_name":"dataset.py","file_ext":"py","file_size_in_byte":1999,"program_lang":"python","lang":"en","doc_type":"code","stars":2,"dataset":"github-code","pt":"20"} +{"seq_id":"40032410913","text":"# coding=utf-8\n\"\"\"\n@license\nThis work is licensed under the Creative Commons\nAttribution-NonCommercial-ShareAlike 4.0 International\nLicense. To view a copy of this license, visit\nhttp://creativecommons.org/licenses/by-nc-sa/4.0/.\n\n@author Yannick Félix\n\"\"\"\n\n\nclass ActionHandler(object):\n globalvars = {}\n\n def __init__(self, globalvars):\n \"\"\"\n This class handles action\n\n @param globalvars: The typical globalvars dict\n @type globalvars: dict\n \"\"\"\n self.globalvars = globalvars\n\n def handleAction(self, action, args):\n \"\"\"\n This magic method decides which function should be called\n @param action: a string with the Action type\n @param args: all the other args\n\n @type action: str\n @type args: dict\n \"\"\"\n if action == \"print\":\n self.ac_print(args)\n elif action == \"setVar\":\n self.ac_setVar(args)\n elif action == \"invVar\":\n self.ac_invVar(args)\n elif action == \"conditionVar\":\n self.ac_condition_Var(args)\n\n def valueof(self, value, args):\n \"\"\"\n This method returns the value of a var if it is one\n @param value: String to check\n @type value: str\n\n @return: The value\n @rtype: str\n \"\"\"\n if isinstance(value, str):\n if value.startswith(\"$\"):\n return self.globalvars.get(value[1:], False)\n elif value.startswith(\"@\"):\n return args.get(value[1:], False)\n else: return value\n else: return value\n\n def ac_print(self, args):\n \"\"\"\n This Action simply prints text\n @param args: The action args dict\n @type args: dict\n \"\"\"\n text = args['text']\n arg0 = args['args'][0]\n arg1 = args['args'][1]\n arg2 = args['args'][2]\n arg3 = args['args'][3]\n self.globalvars['class_gconsole'].printMessage(text, arg0, arg1, arg2, arg3)\n\n def ac_setVar(self, args):\n \"\"\"\n This Action set a var onto a specific value or another vars value\n @param args: The action args dict\n @type args: dict\n \"\"\"\n self.globalvars[args['var']] = self.valueof(args['value'], args)\n\n def ac_invVar(self, args):\n \"\"\"\n This Action invertes a boolean var\n @param args: The action args dict\n @type args: dict\n \"\"\"\n if isinstance(self.globalvars[args['var']], bool):\n self.globalvars[args['var']] = not self.globalvars[args['var']]\n\n def ac_condition_Var(self, args):\n \"\"\"\n This is a more complex action.\n It checks whether is than .\n var1 and var2 can be a value or a var.\n The operator can either be a char(=,!,<,>) or a text(\"equal\").\n If true it starts action_true,\n else it will start action_false.\n @param args: The action args dict\n @type args: dict\n \"\"\"\n result = False\n if args['operation'] == \"equal\" or args['operation'] == \"==\" or args['operation'] == \"=\":\n result = self.valueof(args['var1'], args) == self.valueof(args['var2'], args)\n elif args['operation'] == \"bigger\" or args['operation'] == \">\":\n result = self.valueof(args['var1'], args) > self.valueof(args['var2'], args)\n elif args['operation'] == \"smaller\" or args['operation'] == \"<\":\n result = self.valueof(args['var1'], args) < self.valueof(args['var2'], args)\n elif args['operation'] == \"not equal\" or args['operation'] == \"!=\" or args['operation'] == \"!\":\n result = self.valueof(args['var1'], args) != self.valueof(args['var2'], args)\n\n if result:\n self.handleAction(args['action_true']['action'], args['action_true'])\n else:\n self.handleAction(args['action_false']['action'], args['action_false'])\n","repo_name":"yannick9906/dronespace-python","sub_path":"src/tk/yannickfelix/dronespace16/actions/cActionHandler.py","file_name":"cActionHandler.py","file_ext":"py","file_size_in_byte":3917,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"20"} +{"seq_id":"72829756530","text":"\nimport os\nfrom datetime import datetime, timedelta\nimport logging\nfrom github import Github\n\nfrom conan_community_tools.environment import GITHUB_TOKEN\n\nlog = logging.getLogger(__name__)\n\n\ndef get_client():\n token = os.getenv(GITHUB_TOKEN)\n if not token:\n raise EnvironmentError(f\"Provide env variable '{GITHUB_TOKEN}'\")\n\n gh = Github(token)\n return gh\n\n\ndef get_rate_limit(client, raise_at=500):\n rates = client.rate_limiting\n reset_in = datetime.fromtimestamp(client.rate_limiting_resettime) - datetime.now()\n reset_in = reset_in - timedelta(microseconds=reset_in.microseconds)\n log.debug(f\"Rate limit: {rates[0]}/{rates[1]} (reset in {reset_in})\")\n if raise_at and rates[0] <= raise_at:\n raise RuntimeError(f\"Rate limit under {raise_at}!\")\n return rates[0]\n\n\nif __name__ == '__main__':\n import os\n import argparse\n\n parser = argparse.ArgumentParser(description='Run Appveyor example')\n #parser.add_argument('--repo', help='Repo name')\n #parser.add_argument('--branch', action='append', help='Branches to work over')\n parser.add_argument(\"-v\", \"--verbose\", dest=\"verbose_count\",\n action=\"count\", default=0,\n help=\"increases log verbosity for each occurence.\")\n args = parser.parse_args()\n\n #repo = args.repo or 'conan-community/conan-zlib'\n #branches = args.branch or ['release/1.2.11', 'testing/1.2.11', 'release/1.2.8']\n log_level = max(3 - args.verbose_count, 0) * 10\n\n # Configure login\n logging.basicConfig(level=log_level)\n logging.getLogger('urllib3').setLevel(level=logging.ERROR)\n logging.getLogger('github').setLevel(level=logging.ERROR)\n\n r = get_rate_limit()\n print(f\"Rate limit: {r}\")\n\n","repo_name":"jgsogo/conan-community-utils","sub_path":"conan_community_tools/github/api.py","file_name":"api.py","file_ext":"py","file_size_in_byte":1740,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"20"} +{"seq_id":"8962588111","text":"import json\nimport unittest\nfrom slackbuild.config import Config\nfrom slackbuild.slack import Slack\n\n\nclass TestSlack(unittest.TestCase):\n\n config_override = {\n 'slack': {\n 'channel': '#test',\n 'token': 'test',\n 'signing_secret': '8f742231b10e8888abcd99yyyzzz85a5',\n 'webhook': {\n 'max_content_length': 2\n }\n }\n }\n\n def test_render_message_default(self):\n config = Config(config_override=self.config_override)\n\n variables = {\n \"build_color\": \"#FFFFFF\",\n \"build_id\": \"1234567890\",\n \"build_id_short\": \"1234\",\n \"build_log_url\": \"http://google.com\",\n \"build_status\": \"In Progress\",\n \"build_duration\": \"3 seconds\",\n \"project_id\": \"my-project\",\n \"repo_name\": \"testrepo\",\n \"revision_url\": \"github.com/test/testrepo/commits/123\",\n \"revision\": \"123\",\n \"revision_sha_short\": \"123\"\n }\n\n expected = {\n \"attachments\": [\n {\n \"text\": \"*testrepo* \\nIn Progress | \",\n \"fallback\": \"In Progress | \",\n \"color\": \"#FFFFFF\",\n \"footer\": \"ID: 1234 3 seconds\",\n \"mrkdwn_in\": [\"text\"]\n }\n ],\n \"channel\": \"#test\"\n }\n\n mock_client = Mock_SlackClient(\"\", \"\", {})\n slack = Slack(config, client=mock_client)\n actual = slack.render_message(variables)\n\n self.assertEqual(actual, expected)\n\n def test_post_message_success(self):\n config = Config(config_override=self.config_override)\n\n expected_args = {\n \"attachments\": [\n {\n \"title\": \"this is a title\",\n \"fallback\": \"this is text\",\n \"text\": \"this is text\",\n \"color\": \"red\",\n \"footer\": \"ID: 123\"\n }\n ],\n \"channel\": \"#test\"\n }\n mock_client = Mock_SlackClient(\"chat.postMessage\", {\"ok\": True}, expected_args)\n\n slack = Slack(config, client=mock_client)\n\n success = slack.post_message(expected_args)\n self.assertTrue(success)\n\n def test_verify_webhook_valid(self):\n config = Config(config_override=self.config_override)\n # Assert Slack.verify_webhook doesn't make an API call\n mock_client = Mock_SlackClient(\"\", \"\", {})\n slack = Slack(config, client=mock_client)\n\n headers = {\n 'X-Slack-Request-Timestamp': '1531420618',\n 'X-Slack-Signature': 'v0=a2114d57b48eac39b9ad189dd8316235a7b4a8d21a10bd27519666489c69b503'\n }\n\n body = 'token=xyzz0WbapA4vBCDEFasx0q6G&team_id=T1DC2JH3J&team_domain=testteamnow&channel_id=G8PSS9T3V&channel_name=foobar&user_id=U2CERLKJA&user_name=roadrunner&command=%2Fwebhook-collect&text=&response_url=https%3A%2F%2Fhooks.slack.com%2Fcommands%2FT1DC2JH3J%2F397700885554%2F96rGlfmibIGlgcZRskXaIFfN&trigger_id=398738663015.47445629121.803a0bc887a14d10d2c447fce8b6703c'\n\n req = Mock_Request(headers, body, 1)\n\n is_valid, err = slack.verify_webhook(req)\n self.assertTrue(is_valid)\n\n def test_verify_webhook_invalid(self):\n config = Config(config_override=self.config_override)\n # Assert Slack.verify_webhook doesn't make an API call\n mock_client = Mock_SlackClient(\"\", \"\", {})\n slack = Slack(config, client=mock_client)\n\n headers = {\n 'X-Slack-Request-Timestamp': '1531420619',\n 'X-Slack-Signature': 'v0=a2114d57b48eac39b9ad189dd8316235a7b4a8d21a10bd27519666489c69b503'\n }\n\n body = 'token=xyzz0WbapA4vBCDEFasx0q6G&team_id=T1DC2JH3J&team_domain=testteamnow&channel_id=G8PSS9T3V&channel_name=foobar&user_id=U2CERLKJA&user_name=roadrunner&command=%2Fwebhook-collect&text=&response_url=https%3A%2F%2Fhooks.slack.com%2Fcommands%2FT1DC2JH3J%2F397700885554%2F96rGlfmibIGlgcZRskXaIFfN&trigger_id=398738663015.47445629121.803a0bc887a14d10d2c447fce8b6703c'\n\n req = Mock_Request(headers, body, 1)\n\n is_valid, err = slack.verify_webhook(req)\n self.assertFalse(is_valid)\n\n def test_verify_webhook_max_content_length(self):\n config = Config(config_override=self.config_override)\n # Assert Slack.verify_webhook doesn't make an API call\n mock_client = Mock_SlackClient(\"\", \"\", {})\n slack = Slack(config, client=mock_client)\n\n headers = {\n 'X-Slack-Request-Timestamp': '1531420618',\n 'X-Slack-Signature': 'v0=a2114d57b48eac39b9ad189dd8316235a7b4a8d21a10bd27519666489c69b503'\n }\n\n req = Mock_Request(headers, '', config.get('slack').get('webhook').get('max_content_length') + 1)\n\n is_valid, err = slack.verify_webhook(req)\n self.assertFalse(is_valid)\n\n def test_is_interactive_message(self):\n self.assertTrue(Slack.is_interactive_message({\"type\": \"interactive_message\"}))\n self.assertFalse(Slack.is_interactive_message({\"type\": \"interactive-message\"}))\n self.assertFalse(Slack.is_interactive_message({\"type\": \"\"}))\n self.assertFalse(Slack.is_interactive_message({}))\n\n def test_parse_command(self):\n cases = [\n (\"retry e36544dc-82a1-cc63-bac7-a6b2d18d7ea6\", [\"retry\", \"e36544dc-82a1-cc63-bac7-a6b2d18d7ea6\"]),\n (\" \", []),\n (\" a b c \", [\"a\", \"b\", \"c\"])\n ]\n\n actual = Slack.parse_command({})\n\n self.assertEqual([], actual)\n\n for case in cases:\n text, expected = case\n # try as a /slash command input\n input = {\"text\": text}\n actual = Slack.parse_command(input)\n self.assertEqual(expected, actual)\n # try as an interactive message input\n input = {\"type\": \"interactive_message\", \"actions\": [{\"value\": text}]}\n actual = Slack.parse_command(input)\n self.assertEqual(expected, actual)\n\n def test_parse_request(self):\n f = open('mocks/webhook/interactive_message.json')\n payload = json.load(f)\n f.close()\n f = open('mocks/webhook/interactive_message_payload.json')\n expected = json.load(f)\n f.close()\n f = open('mocks/webhook/form.json')\n form = json.load(f)\n f.close()\n\n req = Mock_Request('', payload, 1)\n self.assertEqual(expected, Slack.parse_request(req))\n\n req = Mock_Request('', form, 1)\n self.assertEqual(form, Slack.parse_request(req))\n\n req = Mock_Request('', {}, 1)\n self.assertEqual({}, Slack.parse_request(req))\n\n def test_render_interactive_message(self):\n self.maxDiff = None\n\n f = open('mocks/webhook/interactive_message_payload.json')\n data = json.load(f)\n f.close()\n\n expected = {'type': 'message', 'subtype': 'bot_message', 'text': '', 'ts': '1549843673.001900', 'username': 'slackbuild', 'bot_id': 'BZAB1CDE3', 'attachments': [{'callback_id': 'placeholder', 'fallback': 'Queued | ', 'text': '*testrepo* \\nQueued | ', 'title': 'Build in my-project-id', 'footer': 'ID: ec52f443 ', 'id': 1, 'color': 'd3d3d3', 'actions': [], 'mrkdwn_in': ['text']}], 'replace_original': True}\n\n expected['attachments'][-1]['fields'] = [{'value': '<@UAB1C2DE3> cancelled build', 'short': False}]\n\n self.assertEqual(expected, Slack.render_interactive_message(data, True, 'cancelled build'))\n\n expected['attachments'][-1]['fields'] = [{'value': ':warning: failed to cancel build', 'short': False}]\n\n self.assertEqual(expected, Slack.render_interactive_message(data, False, 'failed to cancel build'))\n\n\nclass Mock_SlackClient():\n\n def __init__(self, call, response, call_args={}):\n self.__call = call\n self.__response = response\n self.__call_args = call_args\n\n def api_call(self, call, **args):\n assert self.__call == call\n assert self.__call_args == args\n return self.__response\n\n\nclass Mock_Request():\n\n def __init__(self, headers, body, content_length):\n self.headers = headers\n self.__body = body\n self.content_length = content_length\n self.form = self\n\n def get_data(self, as_text=True):\n return self.__body\n\n def to_dict(self):\n return self.__body\n\n\nif __name__ == '__main__':\n unittest.main()\n","repo_name":"mmercedes/slackbuild","sub_path":"tests/test_slack.py","file_name":"test_slack.py","file_ext":"py","file_size_in_byte":8788,"program_lang":"python","lang":"en","doc_type":"code","stars":6,"dataset":"github-code","pt":"20"} +{"seq_id":"25131481407","text":"from __future__ import absolute_import\n\nimport pytest\nfrom mock import MagicMock, Mock, patch, PropertyMock\nfrom sagemaker.session_settings import SessionSettings\n\nfrom sagemaker.transformer import _TransformJob, Transformer\nfrom sagemaker.workflow.pipeline_context import PipelineSession, _PipelineConfig\nfrom sagemaker.inputs import BatchDataCaptureConfig\nfrom sagemaker.workflow.pipeline_definition_config import PipelineDefinitionConfig\n\nfrom tests.integ import test_local_mode\nfrom tests.unit import SAGEMAKER_CONFIG_TRANSFORM_JOB\n\nROLE = \"DummyRole\"\nREGION = \"us-west-2\"\n\nMODEL_NAME = \"model\"\nIMAGE_URI = \"image-for-model\"\nJOB_NAME = \"job\"\n\nINSTANCE_COUNT = 1\nINSTANCE_TYPE = \"ml.m4.xlarge\"\nKMS_KEY_ID = \"kms-key-id\"\n\nS3_DATA_TYPE = \"S3Prefix\"\nS3_BUCKET = \"bucket\"\nDATA = \"s3://{}/input-data\".format(S3_BUCKET)\nOUTPUT_PATH = \"s3://{}/output\".format(S3_BUCKET)\n\nTIMESTAMP = \"2018-07-12\"\n\nINIT_PARAMS = {\n \"model_name\": MODEL_NAME,\n \"instance_count\": INSTANCE_COUNT,\n \"instance_type\": INSTANCE_TYPE,\n \"base_transform_job_name\": JOB_NAME,\n}\n\nMODEL_DESC_PRIMARY_CONTAINER = {\"PrimaryContainer\": {\"Image\": IMAGE_URI}}\n\nMODEL_DESC_CONTAINERS_ONLY = {\"Containers\": [{\"Image\": IMAGE_URI}]}\n\n_DEFINITION_CONFIG = PipelineDefinitionConfig(use_custom_job_prefix=False)\nMOCKED_PIPELINE_CONFIG = _PipelineConfig(\n \"test-pipeline\",\n \"test-training-step\",\n None,\n \"code-hash-0123456789\",\n \"config-hash-0123456789\",\n _DEFINITION_CONFIG,\n)\n\n\n@pytest.fixture(autouse=True)\ndef mock_create_tar_file():\n with patch(\"sagemaker.utils.create_tar_file\", MagicMock()) as create_tar_file:\n yield create_tar_file\n\n\n@pytest.fixture()\ndef sagemaker_session():\n boto_mock = Mock(name=\"boto_session\")\n session = Mock(\n name=\"sagemaker_session\",\n boto_session=boto_mock,\n local_mode=False,\n default_bucket_prefix=None,\n )\n # For tests which doesn't verify config file injection, operate with empty config\n session.sagemaker_config = {}\n return session\n\n\n@pytest.fixture()\ndef pipeline_session():\n client_mock = Mock()\n client_mock._client_config.user_agent = (\n \"Boto3/1.14.24 Python/3.8.5 Linux/5.4.0-42-generic Botocore/1.17.24 Resource\"\n )\n client_mock.describe_model.return_value = {\"PrimaryContainer\": {\"Image\": IMAGE_URI}}\n role_mock = Mock()\n type(role_mock).arn = PropertyMock(return_value=ROLE)\n resource_mock = Mock()\n resource_mock.Role.return_value = role_mock\n session_mock = Mock(region_name=REGION)\n session_mock.resource.return_value = resource_mock\n session_mock.client.return_value = client_mock\n return PipelineSession(\n boto_session=session_mock, sagemaker_client=client_mock, default_bucket=S3_BUCKET\n )\n\n\n@pytest.fixture()\ndef transformer(sagemaker_session):\n return Transformer(\n MODEL_NAME,\n INSTANCE_COUNT,\n INSTANCE_TYPE,\n output_path=OUTPUT_PATH,\n sagemaker_session=sagemaker_session,\n volume_kms_key=KMS_KEY_ID,\n )\n\n\n@patch(\"sagemaker.transformer._TransformJob.start_new\")\ndef test_transform_with_sagemaker_config_injection(start_new_job, sagemaker_session):\n sagemaker_session.sagemaker_config = SAGEMAKER_CONFIG_TRANSFORM_JOB\n\n sagemaker_session.settings = SessionSettings()\n\n transformer = Transformer(\n MODEL_NAME,\n INSTANCE_COUNT,\n INSTANCE_TYPE,\n output_path=OUTPUT_PATH,\n sagemaker_session=sagemaker_session,\n )\n # volume kms key and output kms key are inserted from the config\n assert (\n transformer.volume_kms_key\n == SAGEMAKER_CONFIG_TRANSFORM_JOB[\"SageMaker\"][\"TransformJob\"][\"TransformResources\"][\n \"VolumeKmsKeyId\"\n ]\n )\n assert (\n transformer.output_kms_key\n == SAGEMAKER_CONFIG_TRANSFORM_JOB[\"SageMaker\"][\"TransformJob\"][\"TransformOutput\"][\n \"KmsKeyId\"\n ]\n )\n assert (\n transformer.env\n == SAGEMAKER_CONFIG_TRANSFORM_JOB[\"SageMaker\"][\"TransformJob\"][\"Environment\"]\n )\n\n content_type = \"text/csv\"\n compression = \"Gzip\"\n split = \"Line\"\n input_filter = \"$.feature\"\n output_filter = \"$['sagemaker_output', 'id']\"\n join_source = \"Input\"\n experiment_config = {\n \"ExperimentName\": \"exp\",\n \"TrialName\": \"t\",\n \"TrialComponentDisplayName\": \"tc\",\n }\n model_client_config = {\"InvocationsTimeoutInSeconds\": 60, \"InvocationsMaxRetries\": 2}\n batch_data_capture_config = BatchDataCaptureConfig(\n destination_s3_uri=OUTPUT_PATH, generate_inference_id=False\n )\n transformer.transform(\n DATA,\n S3_DATA_TYPE,\n content_type=content_type,\n compression_type=compression,\n split_type=split,\n job_name=JOB_NAME,\n input_filter=input_filter,\n output_filter=output_filter,\n join_source=join_source,\n experiment_config=experiment_config,\n model_client_config=model_client_config,\n batch_data_capture_config=batch_data_capture_config,\n )\n\n assert transformer._current_job_name == JOB_NAME\n assert transformer.output_path == OUTPUT_PATH\n start_new_job.assert_called_once_with(\n transformer,\n DATA,\n S3_DATA_TYPE,\n content_type,\n compression,\n split,\n input_filter,\n output_filter,\n join_source,\n experiment_config,\n model_client_config,\n batch_data_capture_config,\n )\n # KmsKeyId in BatchDataCapture will be inserted from the config\n assert (\n batch_data_capture_config.kms_key_id\n == SAGEMAKER_CONFIG_TRANSFORM_JOB[\"SageMaker\"][\"TransformJob\"][\"DataCaptureConfig\"][\n \"KmsKeyId\"\n ]\n )\n\n\ndef test_delete_model(sagemaker_session):\n transformer = Transformer(\n MODEL_NAME, INSTANCE_COUNT, INSTANCE_TYPE, sagemaker_session=sagemaker_session\n )\n transformer.delete_model()\n sagemaker_session.delete_model.assert_called_with(MODEL_NAME)\n\n\ndef test_transformer_fails_without_model():\n transformer = Transformer(\n model_name=\"remote-model\",\n sagemaker_session=test_local_mode.LocalNoS3Session(),\n instance_type=\"local\",\n instance_count=1,\n )\n\n with pytest.raises(ValueError) as error:\n\n transformer.transform(\"empty-data\")\n\n assert (\n str(error.value) == \"Failed to fetch model information for remote-model. \"\n \"Please ensure that the model exists. \"\n \"Local instance types require locally created models.\"\n )\n\n\ndef test_transformer_init(sagemaker_session):\n transformer = Transformer(\n MODEL_NAME, INSTANCE_COUNT, INSTANCE_TYPE, sagemaker_session=sagemaker_session\n )\n\n assert transformer.model_name == MODEL_NAME\n assert transformer.instance_count == INSTANCE_COUNT\n assert transformer.instance_type == INSTANCE_TYPE\n assert transformer.sagemaker_session == sagemaker_session\n\n assert transformer._current_job_name is None\n assert transformer.latest_transform_job is None\n assert transformer._reset_output_path is False\n\n\ndef test_transformer_init_optional_params(sagemaker_session):\n strategy = \"MultiRecord\"\n assemble_with = \"Line\"\n accept = \"text/csv\"\n max_concurrent_transforms = 100\n max_payload = 100\n tags = {\"Key\": \"foo\", \"Value\": \"bar\"}\n env = {\"FOO\": \"BAR\"}\n\n transformer = Transformer(\n MODEL_NAME,\n INSTANCE_COUNT,\n INSTANCE_TYPE,\n strategy=strategy,\n assemble_with=assemble_with,\n output_path=OUTPUT_PATH,\n output_kms_key=KMS_KEY_ID,\n accept=accept,\n max_concurrent_transforms=max_concurrent_transforms,\n max_payload=max_payload,\n tags=tags,\n env=env,\n base_transform_job_name=JOB_NAME,\n sagemaker_session=sagemaker_session,\n volume_kms_key=KMS_KEY_ID,\n )\n\n assert transformer.model_name == MODEL_NAME\n assert transformer.strategy == strategy\n assert transformer.env == env\n assert transformer.output_path == OUTPUT_PATH\n assert transformer.output_kms_key == KMS_KEY_ID\n assert transformer.accept == accept\n assert transformer.assemble_with == assemble_with\n assert transformer.instance_count == INSTANCE_COUNT\n assert transformer.instance_type == INSTANCE_TYPE\n assert transformer.volume_kms_key == KMS_KEY_ID\n assert transformer.max_concurrent_transforms == max_concurrent_transforms\n assert transformer.max_payload == max_payload\n assert transformer.tags == tags\n assert transformer.base_transform_job_name == JOB_NAME\n\n\n@patch(\"sagemaker.transformer._TransformJob.start_new\")\ndef test_transform_with_all_params(start_new_job, transformer):\n content_type = \"text/csv\"\n compression = \"Gzip\"\n split = \"Line\"\n input_filter = \"$.feature\"\n output_filter = \"$['sagemaker_output', 'id']\"\n join_source = \"Input\"\n experiment_config = {\n \"ExperimentName\": \"exp\",\n \"TrialName\": \"t\",\n \"TrialComponentDisplayName\": \"tc\",\n }\n model_client_config = {\"InvocationsTimeoutInSeconds\": 60, \"InvocationsMaxRetries\": 2}\n batch_data_capture_config = BatchDataCaptureConfig(\n destination_s3_uri=OUTPUT_PATH, kms_key_id=KMS_KEY_ID, generate_inference_id=False\n )\n\n transformer.transform(\n DATA,\n S3_DATA_TYPE,\n content_type=content_type,\n compression_type=compression,\n split_type=split,\n job_name=JOB_NAME,\n input_filter=input_filter,\n output_filter=output_filter,\n join_source=join_source,\n experiment_config=experiment_config,\n model_client_config=model_client_config,\n batch_data_capture_config=batch_data_capture_config,\n )\n\n assert transformer._current_job_name == JOB_NAME\n assert transformer.output_path == OUTPUT_PATH\n start_new_job.assert_called_once_with(\n transformer,\n DATA,\n S3_DATA_TYPE,\n content_type,\n compression,\n split,\n input_filter,\n output_filter,\n join_source,\n experiment_config,\n model_client_config,\n batch_data_capture_config,\n )\n\n\n@patch(\"sagemaker.transformer.name_from_base\")\n@patch(\"sagemaker.transformer._TransformJob.start_new\")\ndef test_transform_with_base_job_name_provided(start_new_job, name_from_base, transformer):\n base_name = \"base-job-name\"\n full_name = \"{}-{}\".format(base_name, TIMESTAMP)\n\n transformer.base_transform_job_name = base_name\n name_from_base.return_value = full_name\n\n transformer.transform(DATA)\n\n name_from_base.assert_called_once_with(base_name)\n assert transformer._current_job_name == full_name\n\n\n@patch(\"sagemaker.transformer.Transformer._retrieve_base_name\", return_value=IMAGE_URI)\n@patch(\"sagemaker.transformer.name_from_base\")\n@patch(\"sagemaker.transformer._TransformJob.start_new\")\ndef test_transform_with_base_name(start_new_job, name_from_base, retrieve_base_name, transformer):\n full_name = \"{}-{}\".format(IMAGE_URI, TIMESTAMP)\n name_from_base.return_value = full_name\n\n transformer.transform(DATA)\n\n retrieve_base_name.assert_called_once_with()\n name_from_base.assert_called_once_with(IMAGE_URI)\n assert transformer._current_job_name == full_name\n\n\n@patch(\"sagemaker.transformer.Transformer._retrieve_image_uri\", return_value=IMAGE_URI)\n@patch(\"sagemaker.transformer.name_from_base\")\n@patch(\"sagemaker.transformer._TransformJob.start_new\")\ndef test_transform_with_job_name_based_on_image(\n start_new_job, name_from_base, retrieve_image_uri, transformer\n):\n full_name = \"{}-{}\".format(IMAGE_URI, TIMESTAMP)\n name_from_base.return_value = full_name\n\n transformer.transform(DATA)\n\n retrieve_image_uri.assert_called_once_with()\n name_from_base.assert_called_once_with(IMAGE_URI)\n assert transformer._current_job_name == full_name\n\n\n@pytest.mark.parametrize(\"model_desc\", [MODEL_DESC_PRIMARY_CONTAINER, MODEL_DESC_CONTAINERS_ONLY])\n@patch(\"sagemaker.transformer.name_from_base\")\n@patch(\"sagemaker.transformer._TransformJob.start_new\")\ndef test_transform_with_job_name_based_on_containers(\n start_new_job, name_from_base, model_desc, transformer\n):\n transformer.sagemaker_session.sagemaker_client.describe_model.return_value = model_desc\n\n full_name = \"{}-{}\".format(IMAGE_URI, TIMESTAMP)\n name_from_base.return_value = full_name\n\n transformer.transform(DATA)\n\n transformer.sagemaker_session.sagemaker_client.describe_model.assert_called_once_with(\n ModelName=MODEL_NAME\n )\n name_from_base.assert_called_once_with(IMAGE_URI)\n assert transformer._current_job_name == full_name\n\n\n@pytest.mark.parametrize(\n \"model_desc\", [{\"PrimaryContainer\": dict()}, {\"Containers\": [dict()]}, dict()]\n)\n@patch(\"sagemaker.transformer.name_from_base\")\n@patch(\"sagemaker.transformer._TransformJob.start_new\")\ndef test_transform_with_job_name_based_on_model_name(\n start_new_job, name_from_base, model_desc, transformer\n):\n transformer.sagemaker_session.sagemaker_client.describe_model.return_value = model_desc\n\n full_name = \"{}-{}\".format(MODEL_NAME, TIMESTAMP)\n name_from_base.return_value = full_name\n\n transformer.transform(DATA)\n\n transformer.sagemaker_session.sagemaker_client.describe_model.assert_called_once_with(\n ModelName=MODEL_NAME\n )\n name_from_base.assert_called_once_with(MODEL_NAME)\n assert transformer._current_job_name == full_name\n\n\n@patch(\"sagemaker.transformer._TransformJob.start_new\")\ndef test_transform_with_generated_output_path(start_new_job, transformer, sagemaker_session):\n transformer.output_path = None\n sagemaker_session.default_bucket.return_value = S3_BUCKET\n\n transformer.transform(DATA, job_name=JOB_NAME)\n assert transformer.output_path == \"s3://{}/{}\".format(S3_BUCKET, JOB_NAME)\n\n\n@patch(\"sagemaker.workflow.utilities._pipeline_config\", MOCKED_PIPELINE_CONFIG)\ndef test_transform_with_generated_output_path_pipeline_config(pipeline_session):\n transformer = Transformer(\n MODEL_NAME,\n INSTANCE_COUNT,\n INSTANCE_TYPE,\n sagemaker_session=pipeline_session,\n volume_kms_key=KMS_KEY_ID,\n )\n step_args = transformer.transform(DATA)\n # execute transform.transform() and generate args, S3 paths\n step_args.func(*step_args.func_args, **step_args.func_kwargs)\n expected_path = {\n \"Std:Join\": {\n \"On\": \"/\",\n \"Values\": [\n \"s3:/\",\n S3_BUCKET,\n \"test-pipeline\",\n {\"Get\": \"Execution.PipelineExecutionId\"},\n \"test-training-step\",\n ],\n }\n }\n assert expected_path == transformer.output_path.expr\n\n\ndef test_transform_with_invalid_s3_uri(transformer):\n with pytest.raises(ValueError) as e:\n transformer.transform(\"not-an-s3-uri\")\n\n assert \"Invalid S3 URI\" in str(e)\n\n\ndef test_retrieve_image_uri(sagemaker_session, transformer):\n sage_mock = Mock(name=\"sagemaker_client\")\n sage_mock.describe_model.return_value = {\"PrimaryContainer\": {\"Image\": IMAGE_URI}}\n\n sagemaker_session.sagemaker_client = sage_mock\n\n assert transformer._retrieve_image_uri() == IMAGE_URI\n\n\n@patch(\"sagemaker.transformer.Transformer._ensure_last_transform_job\")\ndef test_wait(ensure_last_transform_job, transformer):\n transformer.latest_transform_job = Mock(name=\"latest_transform_job\")\n\n transformer.wait()\n\n assert ensure_last_transform_job.called_once\n assert transformer.latest_transform_job.wait.called_once\n\n\ndef test_ensure_last_transform_job_exists(transformer, sagemaker_session):\n transformer.latest_transform_job = _TransformJob(sagemaker_session, \"some-transform-job\")\n transformer._ensure_last_transform_job()\n\n\ndef test_ensure_last_transform_job_none(transformer):\n transformer.latest_transform_job = None\n with pytest.raises(ValueError) as e:\n transformer._ensure_last_transform_job()\n\n assert \"No transform job available\" in str(e)\n\n\n@patch(\n \"sagemaker.transformer.Transformer._prepare_init_params_from_job_description\",\n return_value=INIT_PARAMS,\n)\ndef test_attach(prepare_init_params, transformer, sagemaker_session):\n sagemaker_session.sagemaker_client.describe_transform_job = Mock(name=\"describe_transform_job\")\n attached = Transformer.attach(JOB_NAME, sagemaker_session)\n\n assert prepare_init_params.called_once\n assert attached.latest_transform_job.job_name == JOB_NAME\n assert attached.model_name == MODEL_NAME\n assert attached.instance_count == INSTANCE_COUNT\n assert attached.instance_type == INSTANCE_TYPE\n\n\ndef test_prepare_init_params_from_job_description_missing_keys(transformer):\n job_details = {\n \"ModelName\": MODEL_NAME,\n \"TransformResources\": {\"InstanceCount\": INSTANCE_COUNT, \"InstanceType\": INSTANCE_TYPE},\n \"TransformOutput\": {\"S3OutputPath\": None},\n \"TransformJobName\": JOB_NAME,\n }\n\n init_params = transformer._prepare_init_params_from_job_description(job_details)\n\n assert init_params[\"model_name\"] == MODEL_NAME\n assert init_params[\"instance_count\"] == INSTANCE_COUNT\n assert init_params[\"instance_type\"] == INSTANCE_TYPE\n\n\ndef test_prepare_init_params_from_job_description_all_keys(transformer):\n job_details = {\n \"ModelName\": MODEL_NAME,\n \"TransformResources\": {\n \"InstanceCount\": INSTANCE_COUNT,\n \"InstanceType\": INSTANCE_TYPE,\n \"VolumeKmsKeyId\": KMS_KEY_ID,\n },\n \"BatchStrategy\": None,\n \"TransformOutput\": {\n \"AssembleWith\": None,\n \"S3OutputPath\": None,\n \"KmsKeyId\": None,\n \"Accept\": None,\n },\n \"MaxConcurrentTransforms\": None,\n \"MaxPayloadInMB\": None,\n \"TransformJobName\": JOB_NAME,\n }\n\n init_params = transformer._prepare_init_params_from_job_description(job_details)\n\n assert init_params[\"model_name\"] == MODEL_NAME\n assert init_params[\"instance_count\"] == INSTANCE_COUNT\n assert init_params[\"instance_type\"] == INSTANCE_TYPE\n assert init_params[\"volume_kms_key\"] == KMS_KEY_ID\n\n\n# _TransformJob tests\n@patch(\"sagemaker.transformer._TransformJob._load_config\")\n@patch(\"sagemaker.transformer._TransformJob._prepare_data_processing\")\ndef test_start_new(prepare_data_processing, load_config, sagemaker_session):\n input_config = \"input\"\n output_config = \"output\"\n resource_config = \"resource\"\n load_config.return_value = {\n \"input_config\": input_config,\n \"output_config\": output_config,\n \"resource_config\": resource_config,\n }\n\n strategy = \"MultiRecord\"\n max_concurrent_transforms = 100\n max_payload = 100\n tags = {\"Key\": \"foo\", \"Value\": \"bar\"}\n env = {\"FOO\": \"BAR\"}\n\n transformer = Transformer(\n MODEL_NAME,\n INSTANCE_COUNT,\n INSTANCE_TYPE,\n strategy=strategy,\n output_path=OUTPUT_PATH,\n max_concurrent_transforms=max_concurrent_transforms,\n max_payload=max_payload,\n tags=tags,\n env=env,\n sagemaker_session=sagemaker_session,\n )\n transformer._current_job_name = JOB_NAME\n\n content_type = \"text/csv\"\n compression_type = \"Gzip\"\n split_type = \"Line\"\n io_filter = \"$\"\n join_source = \"Input\"\n model_client_config = {\"InvocationsTimeoutInSeconds\": 60, \"InvocationsMaxRetries\": 2}\n\n batch_data_capture_config = BatchDataCaptureConfig(\n destination_s3_uri=OUTPUT_PATH, kms_key_id=KMS_KEY_ID, generate_inference_id=False\n )\n\n job = _TransformJob.start_new(\n transformer=transformer,\n data=DATA,\n data_type=S3_DATA_TYPE,\n content_type=content_type,\n compression_type=compression_type,\n split_type=split_type,\n input_filter=io_filter,\n output_filter=io_filter,\n join_source=join_source,\n experiment_config={\"ExperimentName\": \"exp\"},\n model_client_config=model_client_config,\n batch_data_capture_config=batch_data_capture_config,\n )\n\n assert job.sagemaker_session == sagemaker_session\n assert job.job_name == JOB_NAME\n\n load_config.assert_called_with(\n DATA, S3_DATA_TYPE, content_type, compression_type, split_type, transformer\n )\n prepare_data_processing.assert_called_with(io_filter, io_filter, join_source)\n\n sagemaker_session.transform.assert_called_with(\n job_name=JOB_NAME,\n model_name=MODEL_NAME,\n strategy=strategy,\n max_concurrent_transforms=max_concurrent_transforms,\n max_payload=max_payload,\n env=env,\n input_config=input_config,\n output_config=output_config,\n resource_config=resource_config,\n experiment_config={\"ExperimentName\": \"exp\"},\n model_client_config=model_client_config,\n tags=tags,\n data_processing=prepare_data_processing.return_value,\n batch_data_capture_config=batch_data_capture_config,\n )\n\n\ndef test_load_config(transformer):\n expected_config = {\n \"input_config\": {\n \"DataSource\": {\"S3DataSource\": {\"S3DataType\": S3_DATA_TYPE, \"S3Uri\": DATA}}\n },\n \"output_config\": {\"S3OutputPath\": OUTPUT_PATH},\n \"resource_config\": {\n \"InstanceCount\": INSTANCE_COUNT,\n \"InstanceType\": INSTANCE_TYPE,\n \"VolumeKmsKeyId\": KMS_KEY_ID,\n },\n }\n\n actual_config = _TransformJob._load_config(DATA, S3_DATA_TYPE, None, None, None, transformer)\n assert actual_config == expected_config\n\n\ndef test_format_inputs_to_input_config():\n expected_config = {\"DataSource\": {\"S3DataSource\": {\"S3DataType\": S3_DATA_TYPE, \"S3Uri\": DATA}}}\n\n actual_config = _TransformJob._format_inputs_to_input_config(\n DATA, S3_DATA_TYPE, None, None, None\n )\n assert actual_config == expected_config\n\n\ndef test_format_inputs_to_input_config_with_optional_params():\n compression = \"Gzip\"\n content_type = \"text/csv\"\n split = \"Line\"\n\n expected_config = {\n \"DataSource\": {\"S3DataSource\": {\"S3DataType\": S3_DATA_TYPE, \"S3Uri\": DATA}},\n \"CompressionType\": compression,\n \"ContentType\": content_type,\n \"SplitType\": split,\n }\n\n actual_config = _TransformJob._format_inputs_to_input_config(\n DATA, S3_DATA_TYPE, content_type, compression, split\n )\n assert actual_config == expected_config\n\n\ndef test_prepare_output_config():\n config = _TransformJob._prepare_output_config(OUTPUT_PATH, None, None, None)\n\n assert config == {\"S3OutputPath\": OUTPUT_PATH}\n\n\ndef test_prepare_output_config_with_optional_params():\n kms_key = \"key\"\n assemble_with = \"Line\"\n accept = \"text/csv\"\n\n expected_config = {\n \"S3OutputPath\": OUTPUT_PATH,\n \"KmsKeyId\": kms_key,\n \"AssembleWith\": assemble_with,\n \"Accept\": accept,\n }\n\n actual_config = _TransformJob._prepare_output_config(\n OUTPUT_PATH, kms_key, assemble_with, accept\n )\n assert actual_config == expected_config\n\n\ndef test_prepare_resource_config():\n config = _TransformJob._prepare_resource_config(INSTANCE_COUNT, INSTANCE_TYPE, KMS_KEY_ID)\n assert config == {\n \"InstanceCount\": INSTANCE_COUNT,\n \"InstanceType\": INSTANCE_TYPE,\n \"VolumeKmsKeyId\": KMS_KEY_ID,\n }\n\n\ndef test_data_processing_config():\n actual_config = _TransformJob._prepare_data_processing(\"$\", None, None)\n assert actual_config == {\"InputFilter\": \"$\"}\n\n actual_config = _TransformJob._prepare_data_processing(None, \"$\", None)\n assert actual_config == {\"OutputFilter\": \"$\"}\n\n actual_config = _TransformJob._prepare_data_processing(None, None, \"Input\")\n assert actual_config == {\"JoinSource\": \"Input\"}\n\n actual_config = _TransformJob._prepare_data_processing(\"$[0]\", \"$[1]\", \"Input\")\n assert actual_config == {\"InputFilter\": \"$[0]\", \"OutputFilter\": \"$[1]\", \"JoinSource\": \"Input\"}\n\n actual_config = _TransformJob._prepare_data_processing(None, None, None)\n assert actual_config is None\n\n\ndef test_transform_job_wait(sagemaker_session):\n job = _TransformJob(sagemaker_session, JOB_NAME)\n job.wait()\n\n assert sagemaker_session.wait_for_transform_job.called_once\n\n\n@patch(\"sagemaker.transformer._TransformJob.start_new\")\ndef test_restart_output_path(start_new_job, transformer, sagemaker_session):\n transformer.output_path = None\n sagemaker_session.default_bucket.return_value = S3_BUCKET\n\n transformer.transform(DATA, job_name=\"job-1\")\n assert transformer.output_path == \"s3://{}/{}\".format(S3_BUCKET, \"job-1\")\n\n transformer.transform(DATA, job_name=\"job-2\")\n assert transformer.output_path == \"s3://{}/{}\".format(S3_BUCKET, \"job-2\")\n\n\ndef test_stop_transform_job(sagemaker_session, transformer):\n sagemaker_session.stop_transform_job = Mock(name=\"stop_transform_job\")\n transformer.latest_transform_job = _TransformJob(sagemaker_session, JOB_NAME)\n\n transformer.stop_transform_job()\n\n sagemaker_session.stop_transform_job.assert_called_once_with(name=JOB_NAME)\n\n\ndef test_stop_transform_job_no_transform_job(transformer):\n with pytest.raises(ValueError) as e:\n transformer.stop_transform_job()\n assert \"No transform job available\" in str(e)\n","repo_name":"aws/sagemaker-python-sdk","sub_path":"tests/unit/test_transformer.py","file_name":"test_transformer.py","file_ext":"py","file_size_in_byte":25052,"program_lang":"python","lang":"en","doc_type":"code","stars":1962,"dataset":"github-code","pt":"20"} +{"seq_id":"74296911408","text":"#!/usr/bin/env python\n# -*- coding: utf-8 -*-\n# @Time : 2020/4/30 13:42\n# @Author : zengsm\n# @File : finddler\n# https://cloud.tencent.com/developer/article/1592955\nimport requests\nimport re\nimport html\nimport json\nimport demjson\n\nclass WxCrawler(object):\n\n # 复制出来的 Headers,注意这个 x-wechat-key,有时间限制,会过期。当返回的内容出现 验证 的情况,就需要换 x-wechat-key 了\n headers = \"\"\"Connection: keep-alive\n x-wechat-uin: MTY4MTI3NDIxNg%3D%3D\n x-wechat-key: 5ab2dd82e79bc5343ac5fb7fd20d72509db0ee1772b1043c894b24d441af288ae942feb4cfb4d234f00a4a5ab88c5b625d415b83df4b536d99befc096448d80cfd5a7fcd33380341aa592d070b1399a1\n Upgrade-Insecure-Requests: 1\n User-Agent: Mozilla/5.0 (Linux; Android 10; GM1900 Build/QKQ1.190716.003; wv) AppleWebKit/537.36 (KHTML, like Gecko) Version/4.0 Chrome/67.0.3396.87 XWEB/992 MMWEBSDK/191102 Mobile Safari/537.36 MMWEBID/7220 MicroMessenger/7.0.9.1560(0x27000933) Process/toolsmp NetType/WIFI Language/zh_CN ABI/arm64\n Accept: text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,image/wxpic,image/apng,*/*;q=0.8\n Accept-Encoding: gzip, deflate\n Accept-Language: zh-CN,en-US;q=0.9\n Cookie: wxuin=1681274216; devicetype=android-29; version=27000933; lang=zh_CN; pass_ticket=JvAJfzySl6uLWYdYwzyQ+4OqrqiZ2zfaI4F2OCVR7omYOmTjYNKalCFbr75X+T6K; rewardsn=; wxtokenkey=777; wap_sid2=COjq2KEGElxBTmotQWtVY2Iwb3BZRkIzd0Y0SnpaUG1HNTQ0SDA4UGJOZi1kaFdFbkl1MHUyYkRKX2xiWFU5VVhDNXBkQlY0U0pRXzlCZW9qZ29oYW9DWmZYOTdmQTBFQUFBfjD+hInvBTgNQJVO\n X-Requested-With: com.tencent.mm\"\"\"\n\n url = \"https://mp.weixin.qq .com/mp/profile_ext?action=home&__biz=MjEwNDI4NTA2MQ==&scene=123&devicetype=android-29&version=27000933&lang=zh_CN&nettype=WIFI&a8scene=7&session_us=wxid_2574365742721&pass_ticket=JvAJfzySl6uLWYdYwzyQ%2B4OqrqiZ2zfaI4F2OCVR7omYOmTjYNKalCFbr75X%2BT6K&wx_header=1\"\n\n\n # 将 Headers 转换为 字典\n def header_to_dict(self):\n headers = self.headers.split(\"\\n\")\n headers_dict = dict()\n for h in headers:\n k,v = h.split(\":\")\n headers_dict[k.strip()] = v.strip()\n return headers_dict;\n\n\n def run(self):\n headers = self.header_to_dict()\n response = requests.get(self.url, headers=headers, verify=False)\n\n print(response.text)\n\ndef article_list(self, context):\n rex = \"msgList = '({.*?})'\"\n pattern = re.compile(pattern=rex, flags=re.S)\n match = pattern.search(context)\n if match:\n data = match.group(1)\n data = html.unescape(data)\n data = json.loads(data)\n articles = data.get(\"list\")\n return articles\n\n########## 解析单个文章\n# 获取单个文章的URL\ncontent_url_array = []\n\ndef content_url(self, articles):\n content_url = []\n for a in articles:\n a = str(a).replace(\"\\/\", \"/\")\n a = demjson.decode(a)\n content_url_array.append(a['app_msg_ext_info'][\"content_url\"])\n # 取更多的\n for multi in a['app_msg_ext_info'][\"multi_app_msg_item_list\"]:\n self.content_url_array.append(multi['content_url'])\n return content_url\n# 解析单个文章\ndef parse_article(self, headers, content_url):\n for i in content_url:\n content_response = requests.get(i, headers=headers, verify=False)\n with open(\"wx.html\", \"wb\") as f:\n f.write(content_response.content)\n html = open(\"wx.html\", encoding=\"utf-8\").read()\n soup_body = BeautifulSoup(html, \"html.parser\")\n context = soup_body.find('div', id = 'js_content').text.strip()\n print(context)\ndef page(self, headers):\n response = requests.get(self.page_url, headers=headers, verify=False)\n result = response.json()\n if result.get(\"ret\") == 0:\n msg_list = result.get(\"general_msg_list\")\n msg_list = demjson.decode(msg_list)\n self.content_url(msg_list[\"list\"])\n #递归\n self.page(headers)\n else:\n print(\"无法获取内容\")\n\n#############\n\nif __name__ == \"__main__\":\n\n wx = WxCrawler()\n wx.run()","repo_name":"lovelifeming/ai-studies-road","sub_path":"web-crawler/spider-wechat/finddler.py","file_name":"finddler.py","file_ext":"py","file_size_in_byte":4090,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"20"} +{"seq_id":"23326348839","text":"\"\"\"\nGet the ids of all developers that have more than 9 followers\n\"\"\"\nimport json\nimport os\nfrom concurrent.futures import ThreadPoolExecutor, as_completed\nfrom typing import List\nfrom pathlib import Path\n\nN_JOBS = 10\nINTERVALS = [(0, 100), (100, 500), (500, 1000), (1000, 2000), (2000, float('inf'))]\ninterval2ids = {i: [] for i in INTERVALS}\nNUM_PER_INTERVAL = 100\n\n\ndef find_interval(val: int):\n ret = None\n for interval in interval2ids.keys():\n if interval[0] < val < interval[1]:\n ret = interval\n return ret\n\n\ndef filter_dev_ids(files: List[Path]):\n for file in files:\n data = json.load(open(file, encoding='utf-8'))\n\n interval = find_interval(data['followers'])\n if interval is not None and len(interval2ids[interval]) < NUM_PER_INTERVAL:\n interval2ids[interval].append(data['id'])\n\n\ndef main():\n all_files: List[Path] = []\n with os.scandir('cleaned') as it:\n for file in it: # type: Path\n if file.is_file() and file.name.endswith('.json'):\n all_files.append(file)\n\n batch_size = 100\n n_batches = int(len(all_files) / batch_size)\n batches = [all_files[i * batch_size:(i + 1) * batch_size] for i in range(n_batches)]\n with ThreadPoolExecutor(max_workers=N_JOBS) as executor:\n for b in range(0, n_batches, N_JOBS):\n finished = True\n for ids in interval2ids.values():\n if len(ids) < NUM_PER_INTERVAL:\n finished = False\n break\n if finished:\n break\n\n futures = [\n executor.submit(filter_dev_ids, batches[i]) for i in range(b, b + N_JOBS) if i < n_batches\n ]\n\n # wait for threads to complete\n for _ in as_completed(futures):\n continue\n\n all_ids = []\n for ids in interval2ids.values():\n all_ids += ids\n json.dump(all_ids, open('all_ids.json', 'w', encoding='utf-8'))\n\n\nif __name__ == '__main__':\n main()\n","repo_name":"haitonglin/stats401_github_developers","sub_path":"get_all_developer_ids.py","file_name":"get_all_developer_ids.py","file_ext":"py","file_size_in_byte":2018,"program_lang":"python","lang":"en","doc_type":"code","stars":2,"dataset":"github-code","pt":"20"} +{"seq_id":"40038837413","text":"#-*- coding:utf-8 -*-\n\nfrom django.conf.urls.defaults import patterns, include, url\nfrom piston.resource import Resource\nfrom piston.authentication import NoAuthentication\n\nfrom handlers import PackageListHandler, DetailPackageHandler\nfrom emitters import *\n\nfrom doc4.models import File, Package, Repository, Changelog\n\nclass TunedRessource(Resource):\n def determine_emitter(self, request, *args, **kwargs):\n \"\"\"\n sublassing Resource in order to have default emitter falling back to xml instead of json\n \"\"\"\n em = kwargs.pop('emitter_format', None)\n if not em:\n em = request.GET.get('format', 'xml')\n return em\n\n\nauth = NoAuthentication()\nad = {\n 'authentication' : auth,\n}\n\nlist_packages = TunedRessource(handler=PackageListHandler, **ad)\ndetail_package = TunedRessource(handler=DetailPackageHandler, **ad)\n\nurlpatterns = patterns('',\n url(r'^(packages/)?$', list_packages, name='package_list_api'),\n url(r'^(?P\\d+)/$', detail_package, name='package_detail_api'),\n url(r'^package/(?P[+\\w./-]+)/$', detail_package, name='fullname_package_detail_api'),\n #url(r'^packages/repository/(?P[+\\w.-]+)(/(?P[+\\w.-]+))?(/(?P[+\\w.-]+))?(/(?P[+\\w.-]+))?(/(?P
[+\\w.-]+))?/+$',\n url(r'^packages/repository/(?P[+\\w.-]+)?/?((?P[+\\w.-]+))?/?((?P[+\\w.-]+))?/?((?P[+\\w.-]+))?/?((?P
[+\\w.-]+))?/+$',\n list_packages, {'Model' : Repository}, name='repository_packages_api'),\n url(r'^packages/file/(?P[+\\w.-]+)/$', list_packages, {'Model' : File, 'field' : 'name' } ,name='file_search_api'),\n url(r'^packages/path/(?P[+\\w./-]+)/$', list_packages, {'Model' : File, 'field' : 'path' } ,name='file_path_search_api'),\n url(r'(?u)^packages/changelog/(?P[+ @*<>:\\w./-]+)/$', list_packages, {'Model' : Changelog, 'field' : 'log' } ,name='changelog_search_api'),\n url(r'^packages/fullname/(?P[+\\w.-]+)/$', list_packages, {'Model' : Package, 'field' : 'fullname' }, name='package_search_api'),\n url(r'^packages/(name/)?(?P[+\\w.-]+)/$', list_packages, {'Model' : Package, 'field' : 'name' }, name='package_name_search_api'),\n url(r'^packages/category/(?P[+ \\w./-]+)/$', list_packages, {'Model' : Package, 'field' : 'category' } ,name='category_search_api'),\n url(r'(?u)^packages/summary/(?P[+ \\w./-]+)/$', list_packages, {'Model' : Package, 'field' : 'summary' } ,name='summary_search_api'),\n url(r'(?u)^packages/description/(?P[+ \\w./-]+)/$', list_packages, {'Model' : Package, 'field' : 'description' } ,name='description_search_api'),\n url(r'(?u)^packages/author/(?P[+ \\w./-]+)/$', list_packages, {'Model' : Package, 'field' : 'author' } ,name='author_search_api'),\n url(r'(?u)^packages/author_email/(?P[+@\\w./-]+)/$', list_packages, {'Model' : Package, 'field' : 'author_email' } ,name='author_email_search_api'),\n)\n","repo_name":"ygbourhis/django_doc4","sub_path":"doc4/api/urls.py","file_name":"urls.py","file_ext":"py","file_size_in_byte":3007,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"20"} +{"seq_id":"18312183451","text":"import turtle\n\n# title\nturtle.title (\"26.py\")\npen = turtle.Turtle ()\n\nclass point:\n\tdef __init__ (self, x, y):\n\t\tself.x = x\n\t\tself.y = y\nclass length:\n\tdef __init__ (self, height, width):\n\t\tself.h = height\n\t\tself.w = width\n\ndef move (man, x, y):\n\tman.penup ()\n\tman.goto (x, y)\n\tman.pendown ()\n\ndef drawStar (man, center, lengths, color, filled = 0):\n\tmove (man, center.x, center.y)\n\tman.color (color)\n\tman.fillcolor (color)\n\tif (filled == 1):\n\t\tman.begin_fill ()\n\tfor i in range (5):\n\t\tman.forward (40)\n\t\tman.right (180 - 36)\n\tif (filled == 1):\n\t\tman.end_fill ()\n\n\ndef drawRectangle (pants, center, lengths, color, filled = 0):\n\tmove (pants, center.x + lengths.w / 2, center.y + lengths.h / 2)\n\t\n\tif (filled == 1):\n\t\tpants.begin_fill ()\n\tpants.color (color)\n\t#pants.pensize (3)\n\tpants.goto (center.x + lengths.w / 2, center.y - lengths.h / 2)\n\tpants.goto (center.x - lengths.w / 2, center.y - lengths.h / 2)\n\tpants.goto (center.x - lengths.w / 2, center.y + lengths.h / 2)\n\tpants.goto (center.x + lengths.w / 2, center.y + lengths.h / 2)\n\tif (filled == 1):\n\t\tpants.end_fill ()\n\tpants.hideturtle ()\n\t\n\n\n# driver code\norig = length (200, 300)\ncenter = point (0, 0)\npen.pensize (2)\ndrawRectangle (pen, center, orig, \"black\", filled=0)\norig.h, orig.w = 100, 150\npen.pensize (1)\ncenter.x, center.y = center.x - orig.w/2, center.y - orig.h/2\ndrawRectangle (pen, center, orig, \"black\", filled=1)\ncenter.x, center.y = center.x + orig.w, center.y + orig.h\ndrawRectangle (pen, center, orig, \"red\", filled=1)\ncenter.x, center.y = center.x - orig.w - 20, center.y\ndrawStar (pen, center, orig, \"black\", filled=1)\nmove (pen, center.x + 20, center.y - 6.5)\npen.dot (15, \"black\")\ncenter.x, center.y = center.x + orig.w , center.y - orig.h\ndrawStar (pen, center, 30, \"red\", filled=1)\nmove (pen, center.x + 20, center.y - 6.5)\npen.dot (15, \"red\")\n\n\n\n\n\n\n\n# pause\nturtle.hideturtle ()\ninput (\"Press enter to continue...\")\n","repo_name":"pedestrianlove/10901_Python_THU","sub_path":"HW/HW10/6.3/26.py","file_name":"26.py","file_ext":"py","file_size_in_byte":1902,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"20"} +{"seq_id":"30342815397","text":"# Definition for a binary tree node.\r\nclass TreeNode(object):\r\n def __init__(self, val=0, left=None, right=None):\r\n self.val = val\r\n self.left = left\r\n self.right = right\r\n\r\nclass Solution(object):\r\n def mysumRootToLeaf(self, root):\r\n \"\"\"\r\n :type root: TreeNode\r\n :rtype: int\r\n Runtime: 26 ms, faster than 78.32% of Python online submissions for Sum of Root To Leaf Binary Numbers.\r\n Memory Usage: 14.1 MB, less than 36.36% of Python online submissions for Sum of Root To Leaf Binary Numbers.\r\n \"\"\"\r\n ans = []\r\n def read(root,curr):\r\n if not root:\r\n return\r\n if root.left is None and root.right is None:\r\n ans.append(curr+str(root.val))\r\n return\r\n curr += str(root.val)\r\n read(root.left,curr)\r\n read(root.right,curr)\r\n read(root,\"\")\r\n return sum([int('0b'+i,0) for i in ans])\r\n \r\n def sumRootToLeaf1(self, root, sum_= 0):\r\n \"\"\"\r\n :type root: TreeNode\r\n :rtype: int\r\n \"\"\"\r\n\r\n if not root:\r\n return 0\r\n \r\n sum_ = sum_ * 2 + root.val\r\n if root.left or root.right:\r\n x = self.sumRootToLeaf(root.left, sum_)\r\n y = self.sumRootToLeaf(root.right, sum_)\r\n return x + y\r\n else:\r\n return sum_\r\n \r\n\r\n\r\nif __name__==\"__main__\":\r\n # root = TreeNode(1,TreeNode(0,TreeNode(0),TreeNode(1)),TreeNode(1,TreeNode(0),TreeNode(1)))\r\n root = TreeNode(1,right=TreeNode(1))\r\n a = Solution()\r\n print(a.mysumRootToLeaf(root))\r\n ","repo_name":"LinaC404/silly-guy-try-Leetcode","sub_path":"Daily attendance/1022. Sum of Root To Leaf Binary Numbers.py","file_name":"1022. Sum of Root To Leaf Binary Numbers.py","file_ext":"py","file_size_in_byte":1653,"program_lang":"python","lang":"en","doc_type":"code","stars":3,"dataset":"github-code","pt":"17"} +{"seq_id":"18155033519","text":"import hashlib\nimport json\nimport requests\nimport threading\nimport random\nfrom time import time\nfrom uuid import uuid4\nfrom urllib.parse import urlparse\nfrom GeneralSettings import *\n\n\nclass Miner(object):\n def __init__(self, interval=1):\n self.interval = interval\n self.uuid = str(uuid4()).replace('-', '')\n self.node = None\n self.pool = None\n self.chain = []\n self.current_transactions = []\n\n # Create the genesis block\n self.chain.append(self.new_block(previous_hash=1, proof=100))\n\n # The miner starts to mine and mines forever\n thread = threading.Thread(target=self.mine_forever, args=())\n thread.daemon = True\n thread.start()\n\n def new_block(self, proof, previous_hash=None):\n \"\"\"\n Create a new Block in the Blockchain\n :param proof: The proof given by the Proof of Work algorithm\n :param previous_hash: (Optional) Hash of previous Block\n :return: New Block\n \"\"\"\n\n block = {\n 'index': len(self.chain) + 1,\n 'timestamp': time(),\n 'transactions': self.current_transactions,\n 'proof': proof,\n 'previous_hash': previous_hash or self.hash(self.chain[-1])\n }\n\n # Reset the current list of transactions\n self.current_transactions = []\n\n return block\n\n def new_transaction(self, sender, recipient, amount):\n \"\"\"\n Creates a new transaction to go into the next mined Block\n :param sender: Address of the Sender\n :param recipient: Address of the Recipient\n :param amount: Amount\n :return: The index of the Block that will hold this transaction\n \"\"\"\n self.current_transactions.append({\n 'sender': sender,\n 'recipient': recipient,\n 'amount': amount\n })\n\n return self.last_block['index'] + 1\n\n def proof_of_work(self, last_block):\n \"\"\"\n Simple Proof of Work Algorithm:\n - Find a number p' such that hash(pp') contains leading 4 zeroes\n - Where p is the previous proof, and p' is the new proof\n\n :param last_block: last Block\n :return: \n \"\"\"\n last_proof = last_block['proof']\n last_hash = self.hash(last_block)\n proof = 0\n count = 0\n\n while self.valid_proof(last_proof, proof, last_hash) is False:\n if count > iterations_to_consult: # After a fixed amount of iterations, go see if anyone else already has the solution.\n return -1\n proof = random.randint(0, proof_range) # The idea is to have a range big enough, but it will depend on complexity\n count += 1\n\n return proof\n\n def valid_chain(self, chain):\n \"\"\"\n Determine if a given blockchain is valid\n :param chain: A blockchain\n :return: True if valid, False if not\n \"\"\"\n last_block = chain[0]\n current_index = 1\n\n while current_index < len(chain):\n block = chain[current_index]\n # print(f'{last_block}')\n # print(f'{block}')\n # print(\"\\n-----------\\n\")\n # Check that the hash of the block is correct\n last_block_hash = self.hash(last_block)\n if block['previous_hash'] != self.hash(last_block):\n return False\n\n # Check that the Proof of Work is correct\n if not self.valid_proof(last_block['proof'], block['proof'], last_block_hash):\n return False\n\n last_block = block\n current_index += 1\n\n return True\n\n def resolve_conflicts(self):\n \"\"\"\n This is our Consensus Algorithm, it resolves conflicts\n by replacing our chain with the longest one in the network.\n :return: True if our chain was replaced, False if not\n \"\"\"\n best_neighbor_chain = None\n max_neighbor_length = 0\n neighbours = []\n pool_chain = None\n pool_chain_length = 0\n\n response = requests.get(f'http://{host_address}{blockchain_port}/nodes/get')\n if response.status_code == 200:\n neighbours = response.json()['nodes']\n\n # Shuffle the list so we consult them in random order\n random.shuffle(neighbours)\n\n # Grab and verify the chains from all the nodes in our network\n for node in neighbours:\n if node == self.node:\n continue\n\n response = requests.get(f'http://{node}/chain', params={'uuid': self.uuid})\n\n if response.status_code == 200:\n length = response.json()['length']\n chain = response.json()['chain']\n\n if node == self.pool:\n pool_chain = chain\n pool_chain_length = length\n # Check if the length is longer and the chain is valid\n elif length > max_neighbor_length and self.valid_chain(chain):\n max_neighbor_length = length\n best_neighbor_chain = chain\n\n # Replace our chain if we discovered a new, valid chain longer than ours\n if pool_chain_length >= len(self.chain):\n self.chain = pool_chain\n print('The chain was replaced by the pool')\n\n if max_neighbor_length > len(self.chain):\n self.chain = best_neighbor_chain\n print('The chain was replaced by a neighbor')\n\n # For selfish scenario, we always send the best node around.\n # If it's better it will be replaced, otherwise it won't, but the pool has the decision\n if self.pool is not None and best_neighbor_chain is not None:\n # Alert the pool that there is a better chain around\n requests.post(f'http://{self.pool}/pool/update_chain', json={'sender': None, 'chain': best_neighbor_chain})\n\n def mine(self):\n # First verify that our chain is up to date\n self.resolve_conflicts()\n # We run the proof of work algorithm to get the next proof...\n last_block = self.last_block\n proof = self.proof_of_work(last_block)\n\n if proof == -1:\n return 'Unable to find the block, check with the network for updates and try again'\n\n # We must receive a reward for finding the proof.\n # The sender is \"0\" to signify that this node has mined a new coin.\n self.new_transaction(\n sender=\"0\",\n recipient=self.uuid,\n amount=1\n )\n\n # Forge the new Block by adding it to the chain\n previous_hash = self.hash(last_block)\n block = self.new_block(proof, previous_hash)\n self.chain.append(block)\n\n # Alert the pool about the new node so it distributes the reward\n if self.pool is not None:\n response = requests.post(f'http://{self.pool}/pool/update_chain', json={'sender': self.uuid, 'chain': self.chain})\n self.chain = response.json()['chain']\n\n return block\n\n def mine_forever(self):\n while True:\n print(self.mine())\n\n def calculate_wallet(self):\n total = 0\n for block in self.chain:\n for transaction in block['transactions']:\n if transaction['recipient'] == self.uuid:\n total += transaction['amount']\n elif transaction['sender'] == self.uuid:\n total -= transaction['amount']\n\n return total\n\n def register_pool(self, address):\n parsed_url = urlparse(address)\n if parsed_url.netloc:\n self.pool = parsed_url.netloc\n elif parsed_url.path:\n # Accepts an URL without scheme like '192.168.0.5:5000'.\n self.pool = parsed_url.path\n else:\n raise ValueError('Invalid URL')\n\n def unregister_pool(self):\n self.pool = None\n\n\n @property\n def last_block(self):\n return self.chain[-1]\n\n @staticmethod\n def hash(block):\n \"\"\"\n Creates a SHA-256 hash of a Block\n :param block: Block\n :return: \n \"\"\"\n\n # We must make sure that the Dictionary is Ordered, or we'll have inconsistent hashes\n block_string = json.dumps(block, sort_keys=True).encode()\n return hashlib.sha256(block_string).hexdigest()\n\n @staticmethod\n def valid_proof(last_proof, proof, last_hash):\n \"\"\"\n Validates the Proof\n :param last_proof: Previous Proof\n :param proof: Current Proof\n :param last_hash: The hash of the Previous Block\n :return: True if correct, False if not.\n \"\"\"\n guess = f'{last_proof}{proof}{last_hash}'.encode()\n guess_hash = hashlib.sha256(guess).hexdigest()\n return guess_hash[:complexity] == \"0\" * complexity\n","repo_name":"facufref/MLSelfishMining","sub_path":"Miner.py","file_name":"Miner.py","file_ext":"py","file_size_in_byte":8897,"program_lang":"python","lang":"en","doc_type":"code","stars":3,"dataset":"github-code","pt":"17"} +{"seq_id":"17674510661","text":"import os\r\nimport pandas as pd\r\nimport json\r\nimport uuid\r\n\r\nimport scipy as sp\r\nimport time\r\n\r\ndef create_unique_id():\r\n return time.time() + sp.rand()\r\n\r\ndef parsePerfLogCallstack(rootEntry, gid, time, CMID, UID, URL, RQT, PQ, CPU, SQLT):\r\n records = []\r\n level = 1\r\n #print(\"start to parse perflog call stack \", rootEntry)\r\n if rootEntry[\"n\"] and rootEntry[\"i\"] and rootEntry[\"t\"]:\r\n record = {}\r\n name = rootEntry[\"n\"].replace('\"','')\r\n record[\"name\"] = name\r\n record[\"i\"] = rootEntry[\"i\"]\r\n record[\"t\"] = rootEntry[\"t\"]\r\n record[\"GID\"] = gid\r\n record[\"time\"] = time\r\n record[\"CMID\"] = CMID\r\n record[\"UID\"] = UID\r\n record[\"URL\"] = URL\r\n record[\"RQT\"] = RQT\r\n record[\"PQ\"] = PQ\r\n record[\"CPU\"] = CPU\r\n record[\"SQLT\"] = SQLT\r\n\r\n record[\"totalTime\"] = rootEntry[\"t\"]\r\n record[\"parent\"] = \"\"\r\n rootId = create_unique_id()\r\n record[\"uid\"] = rootId\r\n records.append(record)\r\n\r\n unknownTime = rootEntry[\"t\"]\r\n if rootEntry[\"sub\"] :\r\n nextLevel = level + 1\r\n for subEntry in rootEntry[\"sub\"]:\r\n parseEntry(records, subEntry, rootEntry[\"t\"], nextLevel, gid, name)\r\n unknownTime = unknownTime - subEntry[\"t\"]\r\n\r\n if unknownTime < rootEntry[\"t\"] and unknownTime > 0:\r\n otherrecord = {}\r\n otherrecord[\"name\"] = \"others\"\r\n otherrecord[\"i\"] = ''\r\n otherrecord[\"GID\"] = gid\r\n otherrecord[\"t\"] = unknownTime\r\n otherrecordId = create_unique_id()\r\n otherrecord[\"uid\"] = otherrecordId\r\n otherrecord[\"parent\"] = name\r\n otherrecord[\"totalTime\"] = rootEntry[\"t\"]\r\n records.append(otherrecord)\r\n\r\n #print(\"records \", records)\r\n return records\r\n\r\ndef parseEntry(records, entry, totalTime, level, gid, parentName):\r\n #print(\"start to parseEntry\")\r\n if entry[\"n\"] and entry[\"i\"] and entry[\"t\"]:\r\n record = {}\r\n name = entry[\"n\"].replace('\"','')\r\n record[\"name\"] = name\r\n record[\"i\"] = entry[\"i\"]\r\n record[\"t\"] = entry[\"t\"]\r\n record[\"GID\"] = gid\r\n record[\"totalTime\"] = totalTime\r\n record[\"level\"] = level\r\n record[\"parent\"] = parentName\r\n recordId = create_unique_id()\r\n record[\"uid\"] = recordId\r\n records.append(record)\r\n\r\n unknownTime = entry[\"t\"]\r\n\r\n if \"sub\" in entry.keys():\r\n nextLevel = level+1\r\n\r\n for subEntry in entry[\"sub\"]:\r\n parseEntry(records, subEntry, totalTime, nextLevel, gid, name)\r\n unknownTime = unknownTime - subEntry[\"t\"]\r\n\r\n if unknownTime < entry[\"t\"] and unknownTime > 0:\r\n record = {}\r\n record[\"name\"] = \"others\"\r\n record[\"i\"] = \"\"\r\n record[\"t\"] = unknownTime\r\n record[\"GID\"] = gid\r\n record[\"totalTime\"] = totalTime\r\n record[\"level\"] = nextLevel\r\n record[\"parent\"] = name\r\n\r\n recordId = create_unique_id()\r\n record[\"uid\"] = recordId\r\n\r\n records.append(record)\r\n \r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n","repo_name":"ydwisroad/competitions","sub_path":"pythonGraphProject/src/pandasDemo/parsePerflogCallStack.py","file_name":"parsePerflogCallStack.py","file_ext":"py","file_size_in_byte":3232,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"17"} +{"seq_id":"71134348185","text":"import sys\nimport logging\nimport cv2\n\nlogging.basicConfig(level=logging.INFO)\n\ntry:\n input_path = sys.argv[1] # 入力\n output_path = sys.argv[2] # 出力\nexcept IndexError:\n # コマンドライン引数が足りない場合は使い方を表示して終了する\n print('Usage: python detect_faces.py INPUT_PATH OUTPUT_PATH', file=sys.stderr)\n exit(1)\n\n# 特微量ファイ��のパスを定して分類器オブジェクトを作成する\n# cv2.data.haarcascadesはデータディレクトリのパス。公式のPythonバインディングには存在しない\nclassifier = cv2.CascadeClassifier(cv2.data.haarcascades + 'haarcascade_frontalface_alt.xml')\n\nimage = cv2.imread(input_path)\nif image is None:\n logging.error(f'Image \"{input_path}\" not found')\n\n# 顔を検出\nfaces = classifier.detectMultiScale(image)\nlogging.info(f'Found {len(faces)} faces.')\n\n# 検出された顔のリストについて反復処理をする\nfor x, y, w, h in faces:\n cv2.rectangle(image, (x, y), (x + w, y + h), color=(255, 255, 255), thickness=2)\n\n\ncv2.imwrite(output_path, image)\n\n","repo_name":"AkitoShiga/python","sub_path":"crawlingAndScraping/scraping/detect_faces.py","file_name":"detect_faces.py","file_ext":"py","file_size_in_byte":1091,"program_lang":"python","lang":"ja","doc_type":"code","stars":0,"dataset":"github-code","pt":"17"} +{"seq_id":"70089966744","text":"from utils.utils import *\nfrom utils.cocoapi_evaluator import COCOAPIEvaluator\nfrom utils.voc_evaluator import VOCEvaluator\nfrom utils import distributed_util\nfrom utils.distributed_util import reduce_loss_dict\nfrom dataset.cocodataset import *\nfrom dataset.vocdataset import *\nfrom dataset.data_augment import TrainTransform\nfrom dataset.dataloading import *\n\nimport os\nimport sys\nimport argparse\nimport yaml\nimport random\nimport math\nimport cv2\ncv2.setNumThreads(0)\n\nimport torch\nimport torch.nn as nn\nimport torch.nn.init as init\nfrom torch.autograd import Variable\nimport torch.distributed as dist\nimport torch.optim as optim\nimport time\n\nimport apex\nfrom utils.fp16_utils import FP16_Optimizer\n\n######## unlimit the resource in some dockers or cloud machines ####### \n#import resource\n#rlimit = resource.getrlimit(resource.RLIMIT_NOFILE)\n#resource.setrlimit(resource.RLIMIT_NOFILE, (4096, rlimit[1]))\n\n\ndef parse_args():\n parser = argparse.ArgumentParser()\n parser.add_argument('--cfg', type=str, default='config/yolov3_baseline.cfg',\n help='config file. see readme')\n parser.add_argument('-d', '--dataset', type=str,\n default='COCO', help='COCO or VOC dataset')\n parser.add_argument('--n_cpu', type=int, default=4,\n help='number of workers')\n parser.add_argument('--distributed', dest='distributed', action='store_true', default=False,\n help='distributed training')\n parser.add_argument('--local_rank', type=int,\n default=0, help='local_rank')\n parser.add_argument('--ngpu', type=int, default=10,\n help='number of gpu')\n parser.add_argument('--start_epoch', type=int,\n default=0, help='start epoch')\n parser.add_argument('--eval_interval', type=int,\n default=10, help='interval epoch between evaluations')\n parser.add_argument('-c', '--checkpoint', type=str,\n help='pytorch checkpoint file path')\n parser.add_argument('--save_dir', type=str,\n default='save',\n help='directory where model are saved')\n parser.add_argument('--test', dest='test', action='store_true', default=False,\n help='test model')\n parser.add_argument('-s', '--test_size', type=int, default=416)\n parser.add_argument('--testset', dest='testset', action='store_true', default=False,\n help='test set evaluation')\n parser.add_argument('--half', dest='half', action='store_true', default=False,\n help='FP16 training')\n parser.add_argument('--rfb', dest='rfb', action='store_true', default=False,\n help='Use rfb block')\n parser.add_argument('--asff', dest='asff', action='store_true', default=False,\n help='Use ASFF module for yolov3')\n parser.add_argument('--dropblock', dest='dropblock', action='store_true', default=False,\n help='Use dropblock')\n parser.add_argument('--nowd', dest='no_wd', action='store_true', default=False,\n help='no weight decay for bias')\n parser.add_argument('--vis', dest='vis', action='store_true', default=False,\n help='visualize fusion weight and detection results')\n parser.add_argument('--use_cuda', type=bool, default=True)\n parser.add_argument('--debug', action='store_true', default=False,\n help='debug mode where only one image is trained')\n parser.add_argument('--tfboard', action='store_true', help='tensorboard path for logging', default=False)\n parser.add_argument('--log_dir', type=str,\n default='log/',\n help='directory where tf log are saved')\n return parser.parse_args()\n\ndef main():\n \"\"\"\n YOLOv3 trainer. See README for details.\n \"\"\"\n args = parse_args()\n print(\"Setting Arguments.. : \", args)\n\n cuda = torch.cuda.is_available() and args.use_cuda\n os.makedirs(args.log_dir, exist_ok=True)\n os.makedirs(args.save_dir, exist_ok=True)\n\n if args.distributed:\n torch.cuda.set_device(args.local_rank)\n torch.distributed.init_process_group(backend=\"nccl\", init_method=\"env://\")\n\n save_prefix = 'yolov3'\n\n # Parse config settings\n with open(args.cfg, 'r') as f:\n cfg = yaml.safe_load(f)\n\n print(\"successfully loaded config file: \", cfg)\n\n backbone = cfg['MODEL']['BACKBONE']\n lr = cfg['TRAIN']['LR']\n epochs = cfg['TRAIN']['MAXEPOCH']\n cos = cfg['TRAIN']['COS']\n sybn = cfg['TRAIN']['SYBN']\n mixup = cfg['TRAIN']['MIX']\n no_mixup_epochs= cfg['TRAIN']['NO_MIXUP_EPOCHS']\n label_smooth = cfg['TRAIN']['LABAL_SMOOTH']\n momentum = cfg['TRAIN']['MOMENTUM']\n burn_in = cfg['TRAIN']['BURN_IN']\n batch_size = cfg['TRAIN']['BATCHSIZE']\n decay = cfg['TRAIN']['DECAY']\n ignore_thre = cfg['TRAIN']['IGNORETHRE']\n random_resize = cfg['TRAIN']['RANDRESIZE']\n input_size = (cfg['TRAIN']['IMGSIZE'],cfg['TRAIN']['IMGSIZE'])\n test_size = (args.test_size,args.test_size)\n steps = (180, 240) # for no cos lr shedule training\n\n\n # Learning rate setup\n base_lr = lr\n\n if args.dataset == 'COCO':\n dataset = COCODataset(\n data_dir='data/COCO/',\n img_size=input_size,\n preproc=TrainTransform(rgb_means=(0.485, 0.456, 0.406),std=(0.229, 0.224, 0.225),max_labels=50),\n debug=args.debug)\n num_class = 80\n elif args.dataset == 'VOC':\n train_sets = [('2007', 'trainval'), ('2012', 'trainval')]\n dataset = VOCDetection(root='data/VOC',\n image_sets = train_sets,\n input_dim = input_size,\n preproc=TrainTransform(rgb_means=(0.485, 0.456, 0.406),std=(0.229, 0.224, 0.225),max_labels=30))\n num_class = 20\n else:\n print('Only COCO and VOC datasets are supported!')\n return\n\n save_prefix += ('_'+args.dataset)\n\n if label_smooth:\n save_prefix += '_label_smooth'\n\n # Initiate model\n if args.asff:\n save_prefix += '_asff'\n if backbone == 'mobile':\n from models.yolov3_mobilev2 import YOLOv3\n save_prefix += '_mobilev2'\n print(\"For mobilenet, we currently don't support dropblock, rfb and FeatureAdaption\")\n else:\n from models.yolov3_asff import YOLOv3\n print('Training YOLOv3 with ASFF!')\n model = YOLOv3(num_classes = num_class, ignore_thre=ignore_thre, label_smooth = label_smooth, rfb=args.rfb, vis=args.vis, asff=args.asff)\n else:\n save_prefix += '_baseline'\n if backbone == 'mobile':\n from models.yolov3_mobilev2 import YOLOv3\n save_prefix += '_mobilev2'\n else:\n from models.yolov3_baseline import YOLOv3\n print('Training YOLOv3 strong baseline!')\n if args.vis:\n print('Visualization is not supported for YOLOv3 baseline model')\n args.vis = False\n model = YOLOv3(num_classes = num_class, ignore_thre=ignore_thre, label_smooth = label_smooth, rfb=args.rfb)\n\n\n save_to_disk = (not args.distributed) or distributed_util.get_rank() == 0\n\n def init_yolo(M):\n for m in M.modules():\n if isinstance(m, nn.Conv2d):\n if backbone == 'mobile':\n init.kaiming_normal_(m.weight, mode='fan_in')\n else:\n init.kaiming_normal_(m.weight, a=0.1, mode='fan_in')\n if m.bias is not None:\n init.zeros_(m.bias)\n elif isinstance(m, nn.BatchNorm2d):\n init.ones_(m.weight)\n init.zeros_(m.bias)\n elif isinstance(m, nn.Linear):\n init.normal_(m.weight, 0, 0.01)\n init.zeros_(m.bias)\n m.state_dict()[key][...] = 0\n\n model.apply(init_yolo)\n\n if sybn:\n model = apex.parallel.convert_syncbn_model(model)\n\n if args.checkpoint:\n print(\"loading pytorch ckpt...\", args.checkpoint)\n cpu_device = torch.device(\"cpu\")\n ckpt = torch.load(args.checkpoint, map_location=cpu_device)\n model.load_state_dict(ckpt,strict=False)\n #model.load_state_dict(ckpt)\n if cuda:\n print(\"using cuda\")\n torch.backends.cudnn.benchmark = True\n device = torch.device(\"cuda\")\n model = model.to(device)\n\n if args.half:\n model = model.half()\n\n if args.ngpu > 1:\n if args.distributed:\n model = apex.parallel.DistributedDataParallel(model, delay_allreduce=True)\n #model = apex.parallel.DistributedDataParallel(model)\n else:\n model = nn.DataParallel(model) \n\n if args.tfboard and save_to_disk:\n print(\"using tfboard\")\n from torch.utils.tensorboard import SummaryWriter\n tblogger = SummaryWriter(args.log_dir)\n\n model.train()\n if mixup:\n from dataset.mixupdetection import MixupDetection\n dataset = MixupDetection(dataset,\n preproc=TrainTransform(rgb_means=(0.485, 0.456, 0.406),std=(0.229, 0.224, 0.225),max_labels=50),\n )\n dataset.set_mixup(np.random.beta, 1.5,1.5)\n\n save_prefix += '_mixup'\n\n if args.distributed:\n sampler = torch.utils.data.DistributedSampler(dataset)\n else:\n sampler = torch.utils.data.RandomSampler(dataset)\n\n batch_sampler = YoloBatchSampler(sampler=sampler, batch_size=batch_size,drop_last=False,input_dimension=input_size)\n dataloader = DataLoader(\n dataset, batch_sampler=batch_sampler, num_workers=args.n_cpu, pin_memory=True)\n\n dataiterator = iter(dataloader)\n\n if args.dataset == 'COCO':\n evaluator = COCOAPIEvaluator(\n data_dir='data/COCO/',\n img_size=test_size,\n confthre=cfg['TEST']['CONFTHRE'],\n nmsthre=cfg['TEST']['NMSTHRE'],\n testset=args.testset,\n vis=args.vis)\n\n elif args.dataset == 'VOC':\n '''\n # COCO style evaluation, you have to convert xml annotation files into a json file.\n evaluator = COCOAPIEvaluator(\n data_dir='data/VOC/',\n img_size=test_size,\n confthre=cfg['TEST']['CONFTHRE'],\n nmsthre=cfg['TEST']['NMSTHRE'],\n testset=args.testset,\n voc = True)\n '''\n evaluator = VOCEvaluator(\n data_dir='data/VOC/',\n img_size=test_size,\n confthre=cfg['TEST']['CONFTHRE'],\n nmsthre=cfg['TEST']['NMSTHRE'],\n vis=args.vis)\n\n\n dtype = torch.float16 if args.half else torch.float32\n\n # optimizer setup\n # set weight decay only on conv.weight\n if args.no_wd:\n params_dict = dict(model.named_parameters())\n params = []\n for key, value in params_dict.items():\n if 'conv.weight' in key:\n params += [{'params':value, 'weight_decay':decay }]\n else:\n params += [{'params':value, 'weight_decay':0.0}]\n\n save_prefix += '_no_wd'\n else:\n params = model.parameters()\n\n optimizer = optim.SGD(params, lr=base_lr, momentum=momentum,\n dampening=0, weight_decay=decay)\n\n if args.half:\n optimizer = FP16_Optimizer(optimizer,verbose=False)\n\n if cos:\n save_prefix += '_cos'\n\n tmp_lr = base_lr\n\n def set_lr(tmp_lr):\n for param_group in optimizer.param_groups:\n param_group['lr'] = tmp_lr\n\n # start training loop\n start = time.time()\n epoch = args.start_epoch\n epoch_size = len(dataset) // (batch_size*args.ngpu)\n while epoch < epochs+1:\n if args.distributed:\n batch_sampler.sampler.set_epoch(epoch)\n\n if epoch > epochs-no_mixup_epochs+1:\n args.eval_interval = 1\n if mixup:\n print('Disable mix up now!')\n mixup=False\n dataset.set_mixup(None)\n if args.distributed:\n sampler = torch.utils.data.DistributedSampler(dataset)\n else:\n sampler = torch.utils.data.RandomSampler(dataset)\n batch_sampler = YoloBatchSampler(sampler=sampler, batch_size=batch_size,drop_last=False,input_dimension=input_size)\n dataloader = DataLoader(\n dataset, batch_sampler=batch_sampler, num_workers=args.n_cpu, pin_memory=True)\n\n #### DropBlock Shedule #####\n Drop_layer = [16, 24, 33]\n if args.asff:\n Drop_layer = [16, 22, 29]\n if (epoch == 5 or (epoch == args.start_epoch and args.start_epoch > 5)) and (args.dropblock) and backbone!='mobile':\n block_size = [1, 3, 5]\n keep_p = [0.9, 0.9, 0.9]\n for i in range(len(Drop_layer)):\n model.module.module_list[Drop_layer[i]].reset(block_size[i], keep_p[i])\n\n if (epoch == 80 or (epoch == args.start_epoch and args.start_epoch > 80) ) and (args.dropblock) and backbone!='mobile':\n block_size = [3, 5, 7]\n keep_p = [0.9, 0.9, 0.9]\n for i in range(len(Drop_layer)):\n model.module.module_list[Drop_layer[i]].reset(block_size[i], keep_p[i])\n\n if (epoch == 150 or (epoch == args.start_epoch and args.start_epoch > 150)) and (args.dropblock) and backbone!='mobile':\n block_size = [7, 7, 7]\n keep_p = [0.9, 0.9, 0.9]\n for i in range(len(Drop_layer)):\n model.module.module_list[Drop_layer[i]].reset(block_size[i], keep_p[i])\n\n\n for iter_i, (imgs, targets,img_info,idx) in enumerate(dataloader):\n #evaluation\n if ((epoch % args.eval_interval == 0)and epoch > args.start_epoch and iter_i == 0) or args.test:\n if not args.test and save_to_disk:\n torch.save(model.module.state_dict(), os.path.join(args.save_dir,\n save_prefix+'_'+repr(epoch)+'.pth'))\n\n if args.distributed:\n distributed_util.synchronize()\n ap50_95, ap50 = evaluator.evaluate(model, args.half,args.distributed)\n if args.distributed:\n distributed_util.synchronize()\n if args.test:\n sys.exit(0) \n model.train()\n if args.tfboard and save_to_disk:\n tblogger.add_scalar('val/COCOAP50', ap50, epoch)\n tblogger.add_scalar('val/COCOAP50_95', ap50_95, epoch)\n\n # learning rate scheduling (cos or step)\n if epoch < burn_in:\n tmp_lr = base_lr * pow((iter_i+epoch*epoch_size)*1. / (burn_in*epoch_size), 4)\n set_lr(tmp_lr)\n elif cos:\n if epoch <= epochs-no_mixup_epochs and epoch > 20:\n min_lr = 0.00001\n tmp_lr = min_lr + 0.5*(base_lr-min_lr)*(1+math.cos(math.pi*(epoch-20)*1./\\\n (epochs-no_mixup_epochs-20)))\n elif epoch > epochs-no_mixup_epochs:\n tmp_lr = 0.00001\n set_lr(tmp_lr)\n\n elif epoch == burn_in:\n tmp_lr = base_lr\n set_lr(tmp_lr)\n elif epoch in steps and iter_i == 0:\n tmp_lr = tmp_lr * 0.1\n set_lr(tmp_lr)\n\n\n optimizer.zero_grad()\n\n imgs = Variable(imgs.to(device).to(dtype))\n targets = Variable(targets.to(device).to(dtype), requires_grad=False)\n loss_dict = model(imgs, targets, epoch)\n loss_dict_reduced = reduce_loss_dict(loss_dict)\n loss = sum(loss for loss in loss_dict['losses'])\n if args.half:\n optimizer.backward(loss)\n else:\n loss.backward()\n\n #torch.nn.utils.clip_grad_norm_(model.parameters(), 10)\n\n optimizer.step()\n\n\n if iter_i % 10 == 0 and save_to_disk:\n # logging\n end = time.time()\n print('[Epoch %d/%d][Iter %d/%d][lr %.6f]'\n '[Loss: anchor %.2f, iou %.2f, l1 %.2f, conf %.2f, cls %.2f, imgsize %d, time: %.2f]'\n % (epoch, epochs, iter_i, epoch_size, tmp_lr,\n sum(anchor_loss for anchor_loss in loss_dict_reduced['anchor_losses']).item(),\n sum(iou_loss for iou_loss in loss_dict_reduced['iou_losses']).item(),\n sum(l1_loss for l1_loss in loss_dict_reduced['l1_losses']).item(),\n sum(conf_loss for conf_loss in loss_dict_reduced['conf_losses']).item(),\n sum(cls_loss for cls_loss in loss_dict_reduced['cls_losses']).item(),\n input_size[0], end-start),\n flush=True)\n\n start = time.time()\n if args.tfboard and save_to_disk:\n tblogger.add_scalar('train/total_loss',\n sum(loss for loss in loss_dict_reduced['losses']).item(),\n epoch*epoch_size+iter_i)\n\n # random resizing\n if random_resize and iter_i %10 == 0 and iter_i > 0:\n tensor = torch.LongTensor(1).to(device)\n if args.distributed:\n distributed_util.synchronize()\n\n if save_to_disk:\n if epoch > epochs-10:\n size = 416 if args.dataset=='VOC' else 608\n else:\n size = random.randint(*(10,19))\n size = int(32 * size)\n tensor.fill_(size)\n\n if args.distributed:\n distributed_util.synchronize()\n dist.broadcast(tensor, 0)\n\n input_size = dataloader.change_input_dim(multiple=tensor.item(), random_range=None)\n\n if args.distributed:\n distributed_util.synchronize()\n\n epoch +=1\n if not args.test and save_to_disk:\n torch.save(model.module.state_dict(), os.path.join(args.save_dir,\n \"yolov3_\"+args.dataset+'_Final.pth'))\n \n if args.distributed:\n distributed_util.synchronize()\n ap50_95, ap50 = evaluator.evaluate(model, args.half)\n\n if args.tfboard and save_to_disk:\n tblogger.close()\n\n\nif __name__ == '__main__':\n main()\n","repo_name":"GOATmessi7/ASFF","sub_path":"main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":18563,"program_lang":"python","lang":"en","doc_type":"code","stars":1027,"dataset":"github-code","pt":"17"} +{"seq_id":"2719789135","text":"import sys\n\nsys.path.append(\"../\")\n\nfrom spiders.netease_cloud_music.core import NeteaseCloudMusicRequest\nfrom models.singer.singer import Singer\nfrom models.song.song import Song\nfrom models.user.user import User\n\n\nclass Spider(object):\n CRAWL_PAGE_COUNT = 100 # 默认抓取前 100 条评论\n CRAWL_PAGE_SIZE = 20 # 每页评论的数量\n\n @classmethod\n def run(cls, song_ids):\n for song_id in song_ids:\n for i in range(cls.CRAWL_PAGE_COUNT):\n offset = i * cls.CRAWL_PAGE_SIZE\n comment_list = NeteaseCloudMusicRequest.music_comment(song_id, offset, cls.CRAWL_PAGE_SIZE)\n for comment in comment_list.get(\"comments\"):\n user_info = comment.get(\"user\")\n uid, nickname = user_info.get(\"userId\"), user_info.get(\"nickname\")\n user_detail = {\n \"uid\": uid,\n \"properties\": {\n \"name\": nickname\n }\n }\n ret = User.get_instance().save_vertex(**user_detail)\n print(\"save user:\", user_detail, ret)\n\n playlist_all = NeteaseCloudMusicRequest.user_playlist(uid, offset, cls.CRAWL_PAGE_SIZE)\n playlist = playlist_all.get(\"playlist\")[0] if playlist_all.get(\"playlist\") else None\n if playlist and playlist.get(\"name\") == \"{}喜欢的音乐\".format(nickname):\n playlist_id = playlist.get(\"id\")\n playlist_detail = NeteaseCloudMusicRequest.play_list_detail(playlist_id)\n\n song_id_list = []\n for track_id_info in playlist_detail.get(\"playlist\").get(\"trackIds\"):\n song_id_list.append(track_id_info[\"id\"])\n\n favorite_song_list = NeteaseCloudMusicRequest.song_detail(song_id_list)\n for favorite_song in favorite_song_list.get(\"songs\"):\n singer_info = favorite_song.get(\"ar\")[0] # 只保留第一作者\n singer_id, singer_name = singer_info.get(\"id\"), singer_info.get(\"name\")\n singer_detail = {\n \"singer_id\": singer_id,\n \"properties\": {\n \"name\": singer_name\n }\n }\n ret = Singer.get_instance().save_vertex(**singer_detail)\n print(\"save singer:\", singer_detail, ret)\n\n song_detail = {\n \"song_id\": favorite_song.get(\"id\"),\n \"properties\": {\n \"name\": favorite_song.get(\"name\")\n }\n }\n ret = Song.get_instance().save_vertex(**song_detail)\n print(\"save song:\", song_detail, ret)\n\n Song.get_instance().save_edge(song_detail[\"song_id\"], uid, \"favorite_song\", {})\n print(\"save {}--favorite_song-->{}\".format(uid, song_detail[\"song_id\"]))\n Song.get_instance().save_edge(song_detail[\"song_id\"], singer_id, \"create_song\", {})\n print(\"save {}--create_song-->{}\".format(singer_id, song_detail[\"song_id\"]))\n\n\nif __name__ == \"__main__\":\n Spider.run([\"1342950406\"])\n","repo_name":"changaolee/netease-cloud-music-graph","sub_path":"scripts/run_spider.py","file_name":"run_spider.py","file_ext":"py","file_size_in_byte":3565,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"17"} +{"seq_id":"11668784291","text":"import os\nimport regex as re\n\nfrom elasticsearch import Elasticsearch\nfrom elasticsearch.client import IndicesClient\n\nINDEX_NAME = 'legislatives'\nTYPE = 'text'\n\n\ndef open_directory(path):\n return os.listdir(path) if os.path.isdir(path) else [os.path.basename(path)]\n\n\ndef read_file(path, filename):\n with open(path + \"/\" + filename, 'r', encoding=\"utf-8\") as file:\n return file.read()\n\n\ndef initialize_elastic(address, path, settings, index_name=INDEX_NAME, doc_type=TYPE, **kwargs):\n es = Elasticsearch([address])\n if kwargs['reset']:\n ic = IndicesClient(es)\n if ic.exists(index=index_name):\n ic.delete(index_name)\n ic.create(index=index_name, body=settings)\n directory_contents = open_directory(path)\n counter = 0\n for filename in directory_contents:\n file_contents = re.sub(r'(?:[^\\w\\s])+', ' ', read_file(path, filename).lower().strip()) if kwargs[\n 'remove_non_alphanumeric'] else read_file(path, filename)\n index = counter if kwargs['index_counter'] else filename\n es.index(index=index_name, doc_type=doc_type, id=index, body={\n \"text\": file_contents,\n })\n print(filename + \" loaded\")\n counter += 1\n return es\n","repo_name":"Maheliusz/nlp_lab","sub_path":"utils/utils.py","file_name":"utils.py","file_ext":"py","file_size_in_byte":1287,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"17"} +{"seq_id":"40407235380","text":"__module_name__ = \"Rename Facebook and Google Talk (or Hangouts whatever) Contacts\" \n__module_version__ = \"0.1\" \n__module_description__ = \"Rename Bitlbee Facebook contacts to the name they have on Facebook (http://hofnar.ro)\" \n\nimport xchat \n\n# this function renames the ugly name\ndef rename_name(word, word_eol, userdata):\n # get the facebook name from whois, decode with string-escape, decode as utf-8,\n # encode to ascii and trim all spaces so you get the final name\n name = word[3].decode('string-escape').decode(\"utf-8\").encode(\"ascii\",\"ignore\").replace(\" \", \"\")\n # issue a command on channel &bitlbee to rename the ugly name to the new name\n xchat.command(\"msg &bitlbee rename %s %s\" % (word[0], name))\n # unhooking (use global variable)\n global rename_hook\n # if there is a hook\n if rename_hook is not None:\n # unhook\n xchat.unhook(rename_hook)\n # and set to None\n rename_hook = None\n # catch this print in other windows or something\n return xchat.EAT_ALL\n\n# this function will be called on join\ndef on_join(word, word_eol, userdata):\n # use global variable for unhooking\n global rename_hook\n # for comfort instead of word[0], word[1] and word[2]\n triggernick, triggerchannel, triggerhost = word\n # get the context\n destination = xchat.get_context()\n # if the channel is bitlbees channel and the nick begins with a dash\n if ((triggerchannel == \"&bitlbee\") and ((triggernick[0] == \"-\") or (triggernick[0] == \"_\"))):\n # send a whois on the nick\n xchat.command(\"whois %s\" % triggernick)\n # make a handler that hooks the Name Line of the whois and calls rename_name with this line\n rename_hook = xchat.hook_print(\"Whois Name Line\", rename_name)\n # unhook the whois\n return\n\n# this hooks on Join\nxchat.hook_print('Join', on_join)\n","repo_name":"WeNDoRx/scripts","sub_path":"xchat_rename_ugly_contacts.py","file_name":"xchat_rename_ugly_contacts.py","file_ext":"py","file_size_in_byte":1855,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"17"} +{"seq_id":"34081740729","text":"from flask import Flask,request\r\nfrom flask_cors import CORS\r\nfrom flask_mysqldb import MySQL\r\napp = Flask(\"__name__\")\r\n\r\napp.config['MYSQL_HOST']=\"localhost\"\r\napp.config['MYSQL_USER']=\"root\"\r\napp.config['MYSQL_PASSWORD']=\"Akhilyuvi143@\"\r\napp.config['MYSQL_DB']=\"data\"\r\n\r\nmysql = MySQL(app)\r\nCORS(app)\r\n\r\n@app.route(\"/USER_SPECIALIZATION\",methods = ['GET','POST'])\r\ndef index():\r\n if request.method=='POST':\r\n d=request.json\r\n USER_SPECIALIZATION_ID=d['USER_SPECIALIZATION_ID']\r\n USER_ID=d['USER_ID']\r\n SPECIALIZATION_NAME=d['SPECIALIZATION_NAME']\r\n cursor = mysql.connection.cursor()\r\n cursor.execute(\"INSERT INTO USER_SPECIALIZATION(USER_SPECIALIZATION_ID,USER_ID,SPECIALIZATION_NAME) VALUES( %s,%s,%s)\",(USER_SPECIALIZATION_ID,USER_ID,SPECIALIZATION_NAME))\r\n mysql.connection.commit()\r\n cursor.close()\r\n return 'success'\r\n else:\r\n return 'unsuccess'\r\n \r\n\r\n \r\n\r\nif __name__ == '__main__':\r\n app.run()","repo_name":"Akhilgarrapally/Akhil","sub_path":"Pythonfiles/api/USER_SPECIALIZATION.py","file_name":"USER_SPECIALIZATION.py","file_ext":"py","file_size_in_byte":992,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"17"} +{"seq_id":"32202759589","text":"from tqdm import tqdm\nimport pandas as pd\nimport numpy as np\nimport reverse_geocoder as rg\n\nfrom download_utils import download_url\n\n\ndef main():\n np.random.seed(0)\n\n download_url(\"https://raw.githubusercontent.com/nytimes/covid-19-data/master/us-counties.csv\", \"covid19\")\n\n df = pd.read_csv(\"covid19/us-counties.csv\")\n\n # Remove rows with unknown counties.\n df = df[df.county != \"Unknown\"]\n\n # Merge with latitude and longitude.\n url = \"https://en.m.wikipedia.org/wiki/User:Michael_J/County_table\"\n df_county_geoloc = pd.read_html(url)[0]\n df_county_geoloc[\"Area\"] = df_county_geoloc[\"Total Areakm²\"]\n df_county_geoloc = df_county_geoloc[[\"FIPS\", \"Longitude\", \"Latitude\", \"Area\"]]\n\n df_county_geoloc.Latitude = df_county_geoloc.Latitude.map(lambda s: float(s.replace(\"–\", \"-\").replace(\"°\", \"\")))\n df_county_geoloc.Longitude = df_county_geoloc.Longitude.map(lambda s: float(s.replace(\"–\", \"-\").replace(\"°\", \"\")))\n df_county_geoloc.FIPS = df_county_geoloc.FIPS.map(lambda x: float(x))\n df = df.merge(df_county_geoloc, left_on=\"fips\", right_on=\"FIPS\", how=\"left\")\n\n # Fill in rows with NaN FIPS.\n df.set_index(\"county\", inplace=True)\n missing_latlong = [\n [\"New York City\", 40.7128, -74.0060, 783.8],\n [\"Kansas City\", 39.0997, -94.5786, 815.72],\n [\"Joplin\", 37.0842, -94.5133, 81.7],\n [\"Kusilvak Census Area\", 62.1458, -162.8919, 44240],\n ]\n\n df_na = pd.DataFrame(missing_latlong, columns=[\"county\", \"Longitude\", \"Latitude\", \"Area\"])\n df_na.set_index(\"county\", inplace=True)\n df.update(df_na, overwrite=False)\n df = df.reset_index()\n\n # Remove Alaska and Hawaii.\n df = df[df.state != \"Alaska\"]\n df = df[df.state != \"Hawaii\"]\n\n # Compute number of new cases/deaths each day instead of cumulative.\n df.sort_values(by=[\"state\", \"county\", \"date\"], inplace=True)\n\n df[\"new_cases\"] = df.groupby([\"state\", \"county\"])[\"cases\"].diff().fillna(df[\"cases\"])\n df[\"new_deaths\"] = df.groupby([\"state\", \"county\"])[\"deaths\"].diff().fillna(df[\"deaths\"])\n\n # Select time line from March to June.\n df[\"date\"] = pd.to_datetime(df[\"date\"])\n start_date = pd.Timestamp(\"2020-03-15\")\n end_date = pd.Timestamp(\"2020-08-01\")\n df = df[pd.DatetimeIndex(df.date) >= start_date]\n df = df[pd.DatetimeIndex(df.date) <= end_date]\n\n # Create numeric time column.\n df[\"day\"] = df[\"date\"].apply(lambda x: float((x - start_date).days))\n\n # Cases in New Jersey.\n df = df[[\"day\", \"Longitude\", \"Latitude\", \"Area\", \"new_cases\", \"state\", \"county\"]]\n df = df[df.new_cases > 0]\n df = df.loc[df.index.repeat(df.new_cases)]\n df = df[df.state == \"New Jersey\"]\n\n # Break into 7 day intervals using a sliding window of 3 days.\n sequences = {}\n interval_length = 7\n for start in range(0, int(df[\"day\"].max()) - interval_length + 1, 3):\n date = start_date + pd.Timedelta(days=start)\n seq_name = f\"{date.year}{date.month:02d}\" + f\"{date.day:02d}\"\n\n df_range = df[df[\"day\"] >= start]\n df_range = df_range[df_range[\"day\"] < start + interval_length]\n df_range[\"day\"] = df_range[\"day\"] - start\n\n seq = df_range.to_numpy()[:, :4].astype(np.float64)\n counties = df_range.to_numpy()[:, -1]\n\n t, x = seq[:, 0:1], seq[:, 1:3]\n area = seq[:, 3]\n\n print(seq_name, seq.shape[0])\n\n for i in tqdm(range(50)):\n # subsample_idx = np.sort(np.random.choice(seq.shape[0], seq.shape[0] // 200, replace=False))\n subsample_idx = np.random.rand(seq.shape[0]) < (1 / 100)\n\n while np.sum(subsample_idx) == 0:\n subsample_idx = np.random.rand(seq.shape[0]) < (1 / 100)\n\n # Uniformly distribute the daily case count.\n _t = add_temporal_noise(t[subsample_idx])\n\n # Assume each degree of longitude/latitude is ~110km.\n degrees = np.sqrt(area) / 110.0\n _x = add_unif_spatial_noise(x[subsample_idx], degrees[subsample_idx].reshape(-1, 1), counties[subsample_idx])\n\n sort_idx = np.argsort(_t.reshape(-1))\n sequences[seq_name + f\"_{i:03d}\"] = np.concatenate([_t, _x], axis=1)[sort_idx]\n\n np.savez(\"covid19/covid_nj_cases.npz\", **sequences)\n\n\ndef add_unif_spatial_noise(coords, width, counties):\n sampled_coords = coords\n\n match = np.zeros(sampled_coords.shape[0]) > 0\n while not match.all():\n sampled_coords = sampled_coords * match.reshape(-1, 1) + (coords + 2.0 * (np.random.rand(*coords.shape) * width - width / 2)) * ~match.reshape(-1, 1)\n lons, lats = sampled_coords[:, 0], sampled_coords[:, 1]\n queries = list(zip(lats, lons))\n results = rg.search(queries)\n match = np.array([county in res[\"admin2\"] for county, res in zip(counties, results)])\n\n return sampled_coords\n\n\ndef add_temporal_noise(day):\n return day + np.random.rand(*day.shape)\n\n\nif __name__ == \"__main__\":\n main()\n","repo_name":"facebookresearch/neural_stpp","sub_path":"data/download_and_preprocess_covid19.py","file_name":"download_and_preprocess_covid19.py","file_ext":"py","file_size_in_byte":4925,"program_lang":"python","lang":"en","doc_type":"code","stars":90,"dataset":"github-code","pt":"17"} +{"seq_id":"10845867560","text":"# modified from pytorch densenet\n# so it runs with my script\n# NOTE: WIP\n\nimport tensorflow as tf\n\nclass DenseLayerTF(tf.keras.layers.Layer):\n # NOTE: haven't implemented memory efficient style, see pytorch vision\n def __init__(self,\n num_input_features,\n growth_rate,\n bn_size,\n drop_rate,\n data_format='channels_first'):\n super(DenseLayerTF, self).__init__()\n self.bn_axis = 1 if data_format == 'channels_first' else -1\n self.relu = tf.keras.layers.ReLU()\n self.dropout = tf.keras.layers.Dropout(drop_rate)\n\n # 1x1 Conv\n self.norm1 = tf.keras.layers.BatchNormalization(axis=self.bn_axis)\n self.conv1 = tf.keras.layers.Conv2D(bn_size * growth_rate, 1, 1, data_format=data_format, use_bias=False)\n \n # 3x3 Conv\n self.norm2 = tf.keras.layers.BatchNormalization(axis=self.bn_axis)\n self.padd2 = tf.keras.layers.ZeroPadding2D(padding=1, data_format=data_format)\n self.conv2 = tf.keras.layers.Conv2D(growth_rate, 3, 1, data_format=data_format)\n \n def call(self, inputs):\n x = self.norm1(inputs)\n x = self.relu(x)\n x = self.conv1(x)\n x = self.norm2(x)\n x = self.relu(x)\n x = self.padd2(x)\n x = self.conv2(x)\n x = self.dropout(x)\n return x\n\n\nclass DenseBlockTF(tf.keras.layers.Layer):\n def __init__(self, \n num_layers, \n num_input_features, \n bn_size, \n growth_rate,\n drop_rate,\n data_format='channels_first'):\n super(DenseBlockTF, self).__init__()\n self.layers = []\n self.concat_axis = 1 if data_format == 'channels_first' else -1\n for i in range(num_layers):\n layer = DenseLayerTF(\n num_input_features + i * growth_rate,\n growth_rate=growth_rate,\n bn_size=bn_size,\n drop_rate=drop_rate,\n data_format=data_format\n )\n self.layers.append(layer)\n \n def call(self, inputs):\n concat_feat=inputs\n for i in range(len(self.layers)):\n x = self.layers[i](concat_feat)\n concat_feat = tf.concat([concat_feat, x], self.concat_axis)\n return concat_feat\n \n\nclass TransitionBlockTF(tf.keras.layers.Layer):\n def __init__(self, num_output_features, data_format='channels_first'):\n super(TransitionBlockTF, self).__init__()\n self.bn_axis = 1 if data_format == 'channels_first' else -1\n self.norm = tf.keras.layers.BatchNormalization(axis=self.bn_axis)\n self.relu = tf.keras.layers.ReLU()\n self.conv = tf.keras.layers.Conv2D(num_output_features, 1, 1, use_bias=False, data_format=data_format)\n self.pool = tf.keras.layers.AvgPool2D(2, 2, data_format=data_format)\n \n def call(self, inputs):\n x = self.norm(inputs)\n x = self.relu(x)\n x = self.conv(x)\n x = self.pool(x)\n return x\n\n\nclass DenseNetTF(tf.keras.Model):\n def __init__(self, name, classes=10, is_training=True,\n initial_features=16, initial_kernel_size=3, initial_stride = 1,\n blocks_config=None, growth_rate=12, drop_rate=.0, bn_size=4, \n weights=None, data_format='channels_first', input_shape=None):\n\n super(DenseNetTF, self).__init__(name='densenet'+name)\n self.bn_axis = 1 if data_format == 'channels_first' else -1\n self.num_classes = classes\n self.features = tf.keras.Sequential()\n if len(blocks_config) > 3:\n # bigger densenet\n self.features.add(tf.keras.layers.ZeroPadding2D(padding=3, data_format=data_format, name='feature_zero_pad', input_shape=input_shape))\n self.features.add(tf.keras.layers.Conv2D(initial_features, initial_kernel_size, initial_stride, data_format=data_format, use_bias=False, kernel_initializer='he_normal', name='conv1'))\n self.features.add(tf.keras.layers.BatchNormalization(axis=self.bn_axis))\n self.features.add(tf.keras.layers.ReLU())\n self.features.add(tf.keras.layers.ZeroPadding2D(padding=1, data_format=data_format, name='pool1_zero_pad'))\n self.features.add(tf.keras.layers.MaxPool2D(pool_size=3, strides=2, padding='same', data_format=data_format))\n else:\n # smaller densenet, e.g. for cifar10\n self.features.add(tf.keras.layers.Conv2D(initial_features, initial_kernel_size, initial_stride, 'same', data_format=data_format, use_bias=False, kernel_initializer='he_normal', input_shape=input_shape))\n \n # Dense blocks\n num_features = initial_features\n for i, num_layers in enumerate(blocks_config):\n dblock = DenseBlockTF(\n num_layers=num_layers,\n num_input_features=num_features,\n bn_size=bn_size,\n growth_rate=growth_rate,\n drop_rate=drop_rate,\n data_format=data_format\n )\n self.features.add(dblock)\n \n num_features = num_features + num_layers * growth_rate\n\n # add transition layers\n if i != len(blocks_config) - 1:\n trans_layer = TransitionBlockTF(num_features // 2, data_format=data_format)\n num_features = num_features // 2\n \n # final batch norm\n self.features.add(tf.keras.layers.BatchNormalization(axis=self.bn_axis))\n\n # activation\n self.features.add(tf.keras.layers.ReLU())\n\n # avg pool\n self.features.add(tf.keras.layers.GlobalAvgPool2D(data_format))\n\n # Linear layer\n self.classifier = tf.keras.layers.Dense(classes, activation='softmax')\n \n def call(self, inputs):\n x = self.features(inputs['image'])\n x = self.classifier(x)\n # NOTE: not logits\n return x\n\n#NOTE: haven't done any loading weights, save weights\ndef densenet121(**kwargs):\n return DenseNetTF('121', blocks_config=(6,12,24,16), growth_rate=32, initial_features=64, **kwargs)\n\ndef densenet40(**kwargs):\n return DenseNetTF('40', blocks_config=(12,12,12), growth_rate=12, initial_features=16, **kwargs)\n","repo_name":"matthewygf/torch_interference","sub_path":"tf_image_models/densenet_tf.py","file_name":"densenet_tf.py","file_ext":"py","file_size_in_byte":5749,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"17"} +{"seq_id":"31312119417","text":"import torch\n\nfrom torch import nn\nfrom torch.nn import init\nfrom torch.nn import functional as F\nfrom torch.autograd import Function\n\nfrom math import sqrt\n\nimport random\n\n\ndef init_linear(linear):\n init.xavier_normal(linear.weight)\n linear.bias.data.zero_()\n\n\ndef init_conv(conv, glu=True):\n init.kaiming_normal(conv.weight)\n if conv.bias is not None:\n conv.bias.data.zero_()\n\n\nclass EqualLR:\n def __init__(self, name):\n self.name = name\n\n def compute_weight(self, module):\n weight = getattr(module, self.name + '_orig')\n fan_in = weight.data.size(1) * weight.data[0][0].numel()\n\n return weight * sqrt(2 / fan_in)\n\n @staticmethod\n def apply(module, name):\n fn = EqualLR(name)\n\n weight = getattr(module, name)\n del module._parameters[name]\n module.register_parameter(name + '_orig', nn.Parameter(weight.data))\n module.register_forward_pre_hook(fn)\n\n return fn\n\n def __call__(self, module, input):\n weight = self.compute_weight(module)\n setattr(module, self.name, weight)\n\n\ndef equal_lr(module, name='weight'):\n EqualLR.apply(module, name)\n\n return module\n\n\nclass FusedUpsample(nn.Module):\n def __init__(self, in_channel, out_channel, kernel_size, padding=0):\n super().__init__()\n\n weight = torch.randn(in_channel, out_channel, kernel_size, kernel_size)\n bias = torch.zeros(out_channel)\n\n fan_in = in_channel * kernel_size * kernel_size\n self.multiplier = sqrt(2 / fan_in)\n\n self.weight = nn.Parameter(weight)\n self.bias = nn.Parameter(bias)\n\n self.pad = padding\n\n def forward(self, input):\n weight = F.pad(self.weight * self.multiplier, [1, 1, 1, 1])\n weight = (\n weight[:, :, 1:, 1:]\n + weight[:, :, :-1, 1:]\n + weight[:, :, 1:, :-1]\n + weight[:, :, :-1, :-1]\n ) / 4\n\n out = F.conv_transpose2d(input, weight, self.bias, stride=2, padding=self.pad)\n\n return out\n\n\nclass FusedDownsample(nn.Module):\n def __init__(self, in_channel, out_channel, kernel_size, padding=0):\n super().__init__()\n\n weight = torch.randn(out_channel, in_channel, kernel_size, kernel_size)\n bias = torch.zeros(out_channel)\n\n fan_in = in_channel * kernel_size * kernel_size\n self.multiplier = sqrt(2 / fan_in)\n\n self.weight = nn.Parameter(weight)\n self.bias = nn.Parameter(bias)\n\n self.pad = padding\n\n def forward(self, input):\n weight = F.pad(self.weight * self.multiplier, [1, 1, 1, 1])\n weight = (\n weight[:, :, 1:, 1:]\n + weight[:, :, :-1, 1:]\n + weight[:, :, 1:, :-1]\n + weight[:, :, :-1, :-1]\n ) / 4\n\n out = F.conv2d(input, weight, self.bias, stride=2, padding=self.pad)\n\n return out\n\n\nclass PixelNorm(nn.Module):\n def __init__(self):\n super().__init__()\n\n def forward(self, input):\n return input / torch.sqrt(torch.mean(input ** 2, dim=1, keepdim=True) + 1e-8)\n\n\nclass BlurFunctionBackward(Function):\n @staticmethod\n def forward(ctx, grad_output, kernel, kernel_flip):\n ctx.save_for_backward(kernel, kernel_flip)\n\n grad_input = F.conv2d(\n grad_output, kernel_flip, padding=1, groups=grad_output.shape[1]\n )\n\n return grad_input\n\n @staticmethod\n def backward(ctx, gradgrad_output):\n kernel, kernel_flip = ctx.saved_tensors\n\n grad_input = F.conv2d(\n gradgrad_output, kernel, padding=1, groups=gradgrad_output.shape[1]\n )\n\n return grad_input, None, None\n\n\nclass BlurFunction(Function):\n @staticmethod\n def forward(ctx, input, kernel, kernel_flip):\n ctx.save_for_backward(kernel, kernel_flip)\n\n output = F.conv2d(input, kernel, padding=1, groups=input.shape[1])\n\n return output\n\n @staticmethod\n def backward(ctx, grad_output):\n kernel, kernel_flip = ctx.saved_tensors\n\n grad_input = BlurFunctionBackward.apply(grad_output, kernel, kernel_flip)\n\n return grad_input, None, None\n\n\nblur = BlurFunction.apply\n\n\nclass Blur(nn.Module):\n def __init__(self, channel):\n super().__init__()\n\n weight = torch.tensor([[1, 2, 1], [2, 4, 2], [1, 2, 1]], dtype=torch.float32)\n weight = weight.view(1, 1, 3, 3)\n weight = weight / weight.sum()\n weight_flip = torch.flip(weight, [2, 3])\n\n self.register_buffer('weight', weight.repeat(channel, 1, 1, 1))\n self.register_buffer('weight_flip', weight_flip.repeat(channel, 1, 1, 1))\n\n def forward(self, input):\n return blur(input, self.weight, self.weight_flip)\n # return F.conv2d(input, self.weight, padding=1, groups=input.shape[1])\n\n\nclass EqualConv2d(nn.Module):\n def __init__(self, *args, **kwargs):\n super().__init__()\n\n conv = nn.Conv2d(*args, **kwargs)\n conv.weight.data.normal_()\n conv.bias.data.zero_()\n self.conv = equal_lr(conv)\n\n def forward(self, input):\n return self.conv(input)\n\n\nclass EqualLinear(nn.Module):\n def __init__(self, in_dim, out_dim):\n super().__init__()\n\n linear = nn.Linear(in_dim, out_dim)\n linear.weight.data.normal_()\n linear.bias.data.zero_()\n\n self.linear = equal_lr(linear)\n\n def forward(self, input):\n return self.linear(input)\n\n\nclass ConvBlock(nn.Module):\n def __init__(\n self,\n in_channel,\n out_channel,\n kernel_size,\n padding,\n kernel_size2=None,\n padding2=None,\n downsample=False,\n fused=False,\n residual=False\n ):\n super().__init__()\n self.residual = residual\n pad1 = padding\n pad2 = padding\n if padding2 is not None:\n pad2 = padding2\n\n kernel1 = kernel_size\n kernel2 = kernel_size\n if kernel_size2 is not None:\n kernel2 = kernel_size2\n\n self.conv1 = nn.Sequential(\n EqualConv2d(in_channel, out_channel, kernel1, padding=pad1),\n nn.LeakyReLU(0.2),\n )\n if in_channel!=out_channel:\n self.ch_match = EqualConv2d(in_channel,out_channel,1,1,0)\n else:\n self.ch_match = nn.Identity()\n if downsample:\n if fused:\n self.conv2 = nn.Sequential(\n Blur(out_channel),\n FusedDownsample(out_channel, out_channel, kernel2, padding=pad2),\n nn.LeakyReLU(0.2),\n )\n\n else:\n self.conv2 = nn.Sequential(\n Blur(out_channel),\n EqualConv2d(out_channel, out_channel, kernel2, padding=pad2),\n nn.AvgPool2d(2),\n nn.LeakyReLU(0.2),\n )\n\n else:\n self.conv2 = nn.Sequential(\n EqualConv2d(out_channel, out_channel, kernel2, padding=pad2),\n nn.LeakyReLU(0.2),\n )\n\n def forward(self, input):\n res = self.ch_match(input)\n \n out = self.conv1(input)\n out = self.conv2(out)\n if self.residual:\n return out + res\n else:\n return out\n\n\nclass AdaptiveAttention(nn.Module):\n def __init__(self, img_dim,style_dim):\n super().__init__()\n\n self.img_dim = img_dim\n self.fc = EqualLinear(style_dim, (img_dim**2))\n self.gamma = nn.Parameter(torch.ones(1,1,1,1))\n\n def forward(self, x, p):\n\n h = self.fc(p)\n h = h.view(h.size(0), 1, self.img_dim, self.img_dim)\n h = F.sigmoid(h)\n\n return self.gamma*(h*x)+x\n \nclass AdaptiveInstanceNorm(nn.Module):\n def __init__(self, in_channel, style_dim):\n super().__init__()\n\n self.norm = nn.InstanceNorm2d(in_channel)\n self.style = EqualLinear(style_dim, in_channel * 2)\n \n self.style.linear.bias.data[:in_channel] = 1\n self.style.linear.bias.data[in_channel:] = 0\n\n def forward(self, input, style):\n style = self.style(style).unsqueeze(2).unsqueeze(3)\n gamma, beta = style.chunk(chunks=2, dim=1)\n \n out = self.norm(input)\n out = gamma * out + beta\n\n return out\n\n\nclass NoiseInjection(nn.Module):\n def __init__(self, channel):\n super().__init__()\n\n self.weight = nn.Parameter(torch.zeros(1, channel, 1, 1))\n\n def forward(self, image, noise):\n return image + self.weight * noise\n\n\nclass ConstantInput(nn.Module):\n def __init__(self, channel, size=4):\n super().__init__()\n\n self.input = nn.Parameter(torch.randn(1, channel, size, size))\n\n def forward(self, input):\n batch = input.shape[0]\n out = self.input.repeat(batch, 1, 1, 1)\n\n return out\n\n\nclass StyledConvBlock(nn.Module):\n def __init__(\n self,\n in_channel,\n out_channel,\n kernel_size=3,\n padding=1,\n style_dim=512,\n img_dim=0,\n initial=False,\n upsample=False,\n fused=False,\n use_att=True\n ):\n super().__init__()\n self.use_att = use_att\n if initial:\n self.conv1 = ConstantInput(in_channel)\n \n else:\n if upsample:\n if fused:\n self.conv1 = nn.Sequential(\n FusedUpsample(\n in_channel, out_channel, kernel_size, padding=padding\n ),\n Blur(out_channel),\n )\n\n else:\n self.conv1 = nn.Sequential(\n nn.Upsample(scale_factor=2, mode='nearest'),\n EqualConv2d(\n in_channel, out_channel, kernel_size, padding=padding\n ),\n Blur(out_channel),\n )\n\n else:\n self.conv1 = EqualConv2d(\n in_channel, out_channel, kernel_size, padding=padding\n )\n \n self.adain1 = AdaptiveInstanceNorm(out_channel, style_dim)\n if use_att:\n self.adaat1 = AdaptiveAttention(img_dim,style_dim)\n self.adaat2 = AdaptiveAttention(img_dim,style_dim)\n self.lrelu1 = nn.LeakyReLU(0.2)\n\n self.conv2 = EqualConv2d(out_channel, out_channel, kernel_size, padding=padding)\n self.adain2 = AdaptiveInstanceNorm(out_channel, style_dim)\n self.lrelu2 = nn.LeakyReLU(0.2)\n\n def forward(self, input, style, pix,style2=None,pix2=None,eval_mode=False):\n \n if eval_mode == False:\n pix2 = pix\n style2 = style\n \n out = self.conv1(input)\n if self.use_att:\n out = self.adaat1(out, pix)\n out = self.adain1(out, style)\n out = self.lrelu1(out)\n\n out = self.conv2(out)\n if self.use_att:\n out = self.adaat2(out,pix2)\n out = self.adain2(out, style2)\n out = self.lrelu2(out)\n\n return out\n\nclass UpConvBlock(nn.Module):\n def __init__(\n self,\n in_channel,\n out_channel,\n kernel_size=3,\n padding=1,\n# style_dim=512,\n img_dim=0,\n initial=False,\n upsample=False,\n fused=False,\n ):\n super().__init__()\n\n if initial:\n self.conv1 = ConstantInput(in_channel)\n\n else:\n if upsample:\n if fused:\n self.conv1 = nn.Sequential(\n FusedUpsample(\n in_channel, out_channel, kernel_size, padding=padding\n ),\n Blur(out_channel),\n )\n\n else:\n self.conv1 = nn.Sequential(\n nn.Upsample(scale_factor=2, mode='nearest'),\n EqualConv2d(\n in_channel, out_channel, kernel_size, padding=padding\n ),\n Blur(out_channel),\n )\n\n else:\n self.conv1 = EqualConv2d(\n in_channel, out_channel, kernel_size, padding=padding\n )\n\n self.in1 = nn.InstanceNorm2d(out_channel)\n self.lrelu1 = nn.LeakyReLU(0.2)\n\n self.conv2 = EqualConv2d(out_channel, out_channel, kernel_size, padding=padding)\n self.in2 = nn.InstanceNorm2d(out_channel)\n self.lrelu2 = nn.LeakyReLU(0.2)\n\n def forward(self, input, style, pix):\n out = self.conv1(input)\n out = self.in1(out)\n out = self.lrelu1(out)\n\n out = self.conv2(out)\n out = self.in2(out)\n out = self.lrelu2(out)\n\n return out\n\nclass Generator(nn.Module):\n def __init__(self, code_dim, fused=True):\n super().__init__()\n\n self.progression = nn.ModuleList(\n [\n StyledConvBlock(512, 512, 3, 1, img_dim = 4,initial=True), # 4\n StyledConvBlock(512, 512, 3, 1, img_dim = 8,upsample=True), # 8\n StyledConvBlock(512, 512, 3, 1, img_dim = 16,upsample=True), # 16\n StyledConvBlock(512, 512, 3, 1, img_dim = 32,upsample=True), # 32\n StyledConvBlock(512, 256, 3, 1, img_dim = 64,upsample=True), # 64\n StyledConvBlock(256, 128, 3, 1, img_dim = 128,upsample=True), # 128\n StyledConvBlock(128, 64, 3, 1, img_dim = 256,upsample=True), # 256\n ]\n )\n\n self.to_rgb = nn.ModuleList(\n [\n EqualConv2d(512, 3, 1),\n EqualConv2d(512, 3, 1),\n EqualConv2d(512, 3, 1),\n EqualConv2d(512, 3, 1),\n EqualConv2d(256, 3, 1),\n EqualConv2d(128, 3, 1),\n EqualConv2d(64, 3, 1),\n\n ]\n )\n\n # self.blur = Blur()\n\n def forward(self, style, pix, step=0, alpha=-1,eval_mode=False):\n if eval_mode:\n out = style[0]\n else:\n out = style\n \n for i, (conv, to_rgb) in enumerate(zip(self.progression, self.to_rgb)):\n if i > 0 and step > 0:\n out_prev = out\n if eval_mode:\n out = conv(out,style[2*i],pix[2*i],style[2*i+1],pix[2*i+1],eval_mode=eval_mode)\n else:\n out = conv(out,style,pix)\n if i == step:\n out = to_rgb(out)\n\n if i > 0 and 0 <= alpha < 1:\n skip_rgb = self.to_rgb[i - 1](out_prev)\n skip_rgb = F.interpolate(skip_rgb, scale_factor=2, mode='nearest')\n out = (1 - alpha) * skip_rgb + alpha * out\n\n break\n\n return out\n\nclass MappingNets(nn.Module):\n def __init__(self,code_dim=512,n_mlp = 8,num_domains=2):\n super().__init__()\n layers = [PixelNorm()]\n for i in range(n_mlp//2):\n layers.append(EqualLinear(code_dim, code_dim))\n layers.append(nn.LeakyReLU(0.2))\n self.style_shared = nn.Sequential(*layers)\n layers2 = [PixelNorm()]\n for i in range(n_mlp):\n layers2.append(EqualLinear(code_dim, code_dim))\n layers2.append(nn.LeakyReLU(0.2))\n self.pix_shared = nn.Sequential(*layers2)\n \n self.style_unshared = nn.ModuleList()\n \n for _ in range(num_domains):\n self.style_unshared.append(nn.Sequential(EqualLinear(code_dim,code_dim),\n nn.LeakyReLU(0.2),\n EqualLinear(code_dim,code_dim),\n nn.LeakyReLU(0.2),\n EqualLinear(code_dim,code_dim),\n nn.LeakyReLU(0.2),\n EqualLinear(code_dim,code_dim),\n nn.LeakyReLU(0.2)\n ))\n\n \n def forward(self,input1,input2,y):\n style = self.style_shared(input1)\n pix = self.pix_shared(input2)\n \n styles = []\n for layer in self.style_unshared:\n styles += [layer(style)]\n styles = torch.stack(styles, dim=1) # (batch, num_domains, style_dim)\n idx = torch.LongTensor(range(y.size(0))).to(y.device)\n styles = styles[idx, y]\n\n return styles,pix\nclass StyledGenerator(nn.Module):\n def __init__(self, code_dim=512,num_domains=2, n_mlp=8):\n super().__init__()\n\n self.generator = Generator(code_dim)\n self.mapping = MappingNets(code_dim,n_mlp,num_domains)\n\n def forward(\n self,\n input,\n input2,\n y,\n noise=None,\n step=0,\n alpha=-1,\n mean_style=None,\n mean_pix=None,\n fix_style = False,\n fix_pix = False,\n style_weight=0,\n pix_weight=0,\n eval_mode=False\n \n ):\n\n styles,pix = self.mapping(input,input2,y)\n \n\n batch = input.shape[0]\n\n if noise is None:\n noise = []\n\n for i in range(step + 1):\n size = 4 * 2 ** i\n# noise.append(torch.randn(batch, 1, size, size, device=input[0].device))\n\n if mean_style is not None:\n mean_style = mean_style.repeat(batch,1)\n styles_norm = mean_style + style_weight * (styles - mean_style)\n \n styles = styles_norm\n if mixing_range!=(-1,-1):\n style_norm2 = mean_style + style_weight * (styles2 - mean_style)\n styles2 = style_norm2\n if fix_style:\n styles = mean_style\n if mean_pix is not None:\n mean_pix = mean_pix.repeat(batch,1)\n pix_norm = mean_pix + pix_weight*(pix-mean_pix)\n \n pix = pix_norm\n\n if fix_pix: \n pix = mean_pix\n\n return self.generator(styles, pix, step, alpha,eval_mode)\n\n def mean_style(self, input,input2):\n style = self.style(input).mean(0, keepdim=True)\n pix = self.pix(input2).mean(0,keepdim=True)\n return style,pix\n\n\nclass Discriminator(nn.Module):\n def __init__(self, fused=True, num_domains=2,from_rgb_activate=False):\n super().__init__()\n\n self.progression = nn.ModuleList(\n [\n\n ConvBlock(64, 128, 3, 1, downsample=True), # 128\n ConvBlock(128, 256, 3, 1, downsample=True), # 64\n ConvBlock(256, 512, 3, 1, downsample=True), # 32\n ConvBlock(512, 512, 3, 1, downsample=True), # 16\n ConvBlock(512, 512, 3, 1, downsample=True), # 8\n ConvBlock(512, 512, 3, 1, downsample=True), # 4\n ConvBlock(513, 512, 3, 1, 4, 0),\n ]\n )\n\n def make_from_rgb(out_channel):\n if from_rgb_activate:\n return nn.Sequential(EqualConv2d(3, out_channel, 1), nn.LeakyReLU(0.2))\n\n else:\n return EqualConv2d(3, out_channel, 1)\n\n self.from_rgb = nn.ModuleList(\n [\n\n make_from_rgb(64),\n make_from_rgb(128),\n make_from_rgb(256),\n make_from_rgb(512),\n make_from_rgb(512),\n make_from_rgb(512),\n make_from_rgb(512),\n ]\n )\n\n # self.blur = Blur()\n\n self.n_layer = len(self.progression)\n\n self.linear = EqualLinear(512, num_domains)\n\n def forward(self, input, y,step=0, alpha=-1):\n feats = []\n for i in range(step, -1, -1):\n index = self.n_layer - i - 1\n\n if i == step:\n out = self.from_rgb[index](input)\n\n if i == 0:\n out_std = torch.sqrt(out.var(0, unbiased=False) + 1e-8)\n mean_std = out_std.mean()\n mean_std = mean_std.expand(out.size(0), 1, 4, 4)\n out = torch.cat([out, mean_std], 1)\n out = self.progression[index](out)\n\n if i > 0:\n if i == step and 0 <= alpha < 1:\n skip_rgb = F.avg_pool2d(input, 2)\n skip_rgb = self.from_rgb[index + 1](skip_rgb)\n\n out = (1 - alpha) * skip_rgb + alpha * out\n\n out = out.squeeze(2).squeeze(2)\n out = self.linear(out)\n \n idx = torch.LongTensor(range(y.size(0))).to(y.device)\n out = out[idx, y]\n \n return out\n\nclass StyleEncoder(nn.Module):\n def __init__(self, fused=True, num_domains=2,style_dim=512,from_rgb_activate=False):\n super().__init__()\n\n self.progression = nn.ModuleList(\n [\n ConvBlock(64, 128, 3, 1, downsample=False,residual=True), # 128\n ConvBlock(128, 256, 3, 1, downsample=False,residual=True), # 64\n ConvBlock(256, 512, 3, 1, downsample=False,residual=True), # 32\n ConvBlock(512, 512, 3, 1, downsample=False,residual=True), # 16\n ConvBlock(512, 512, 3, 1, downsample=False,residual=True), # 8\n ConvBlock(512, 512, 3, 1, downsample=False,residual=True), # 4\n ConvBlock(512, 512, 3, 1, 4, 0, downsample=False),\n ]\n )\n self.avgpool = nn.AvgPool2d(2)\n def make_from_rgb(out_channel):\n if from_rgb_activate:\n return nn.Sequential(EqualConv2d(3, out_channel, 1), nn.LeakyReLU(0.2))\n\n else:\n return EqualConv2d(3, out_channel, 1)\n\n self.from_rgb = nn.ModuleList(\n [\n make_from_rgb(64),\n make_from_rgb(128),\n make_from_rgb(256),\n make_from_rgb(512),\n make_from_rgb(512),\n make_from_rgb(512),\n make_from_rgb(512),\n ]\n )\n \n # self.blur = Blur()\n\n self.n_layer = len(self.progression)\n\n self.unshared = nn.ModuleList()\n for _ in range(num_domains):\n self.unshared += [EqualLinear(512, style_dim)]\n\n def forward(self, input,y, step=0, alpha=-1):\n feats = []\n for i in range(step, -1, -1):\n index = self.n_layer - i - 1\n\n if i == step:\n out = self.from_rgb[index](input)\n\n out = self.progression[index](out)\n if i > 0:\n if i == step and 0 <= alpha < 1:\n skip_rgb = F.avg_pool2d(input, 2)\n skip_rgb = self.from_rgb[index + 1](skip_rgb)\n\n out = (1 - alpha) * skip_rgb + alpha * out\n if i != 0:\n out = self.avgpool(out)\n \n out = out.view(out.size(0), -1)\n sty = []\n for layer in self.unshared:\n sty += [layer(out)]\n sty = torch.stack(sty, dim=1) # (batch, num_domains, style_dim)\n idx = torch.LongTensor(range(y.size(0))).to(y.device)\n s = sty[idx, y] # (batch, style_dim)\n \n return s\n\nclass ContentEncoder(nn.Module):\n def __init__(self, fused=True,style_dim=512,from_rgb_activate=False):\n super().__init__()\n\n self.progression = nn.ModuleList(\n [\n\n ConvBlock(64, 128, 3, 1, downsample=False,residual=True), # 128\n ConvBlock(128, 256, 3, 1, downsample=False,residual=True), # 64\n ConvBlock(256, 512, 3, 1, downsample=False,residual=True), # 32\n ConvBlock(512, 512, 3, 1, downsample=False,residual=True), # 16\n ConvBlock(512, 512, 3, 1, downsample=False,residual=True), # 8\n ConvBlock(512, 512, 3, 1, downsample=False,residual=True), # 4\n ConvBlock(512, 512, 3, 1, 4, 0, downsample=False),\n ]\n )\n self.avgpool = nn.AvgPool2d(2)\n def make_from_rgb(out_channel):\n if from_rgb_activate:\n return nn.Sequential(EqualConv2d(3, out_channel, 1), nn.LeakyReLU(0.2))\n\n else:\n return EqualConv2d(3, out_channel, 1)\n\n self.from_rgb = nn.ModuleList(\n [\n\n make_from_rgb(64),\n make_from_rgb(128),\n make_from_rgb(256),\n make_from_rgb(512),\n make_from_rgb(512),\n make_from_rgb(512),\n make_from_rgb(512),\n ]\n )\n \n # self.blur = Blur()\n\n self.n_layer = len(self.progression)\n\n self.linear = EqualLinear(512,style_dim)\n\n def forward(self, input, step=0, alpha=-1):\n feats = []\n for i in range(step, -1, -1):\n index = self.n_layer - i - 1\n\n if i == step:\n out = self.from_rgb[index](input)\n\n out = self.progression[index](out)\n \n if i > 0:\n \n if i == step and 0 <= alpha < 1:\n skip_rgb = F.avg_pool2d(input, 2)\n skip_rgb = self.from_rgb[index + 1](skip_rgb)\n\n out = (1 - alpha) * skip_rgb + alpha * out\n if i != 0:\n out = self.avgpool(out)\n out = out.view(out.size(0), -1)\n c = self.linear(out)\n return c","repo_name":"AnshMittal1811/MachineLearning-AI","sub_path":"167_Content_Style_Disentanglement_in_Image_Generation_and_Translation/model_mult.py","file_name":"model_mult.py","file_ext":"py","file_size_in_byte":25377,"program_lang":"python","lang":"en","doc_type":"code","stars":181,"dataset":"github-code","pt":"17"} +{"seq_id":"40150184275","text":"import torch\r\nfrom torch.functional import Tensor\r\nimport torch.nn as nn\r\n\r\n\"\"\" This script defines the network.\r\n\"\"\"\r\n\r\n\r\nclass ResNet(nn.Module):\r\n def __init__(self,\r\n resnet_version,\r\n resnet_size,\r\n num_classes,\r\n first_num_filters,\r\n ):\r\n \"\"\"\r\n 1. Define hyperparameters.\r\n Args:\r\n resnet_version: 1 or 2, If 2, use the bottleneck blocks.\r\n resnet_size: A positive integer (n).\r\n num_classes: A positive integer. Define the number of classes.\r\n first_num_filters: An integer. The number of filters to use for the\r\n first block layer of the model. This number is then doubled\r\n for each subsampling block layer.\r\n \r\n 2. Classify a batch of input images.\r\n\r\n Architecture (first_num_filters = 16):\r\n layer_name | start | stack1 | stack2 | stack3 | output |\r\n output_map_size | 32x32 | 32X32 | 16x16 | 8x8 | 1x1 |\r\n #layers | 1 | 2n/3n | 2n/3n | 2n/3n | 1 |\r\n #filters | 16 | 16(*4) | 32(*4) | 64(*4) | num_classes |\r\n\r\n n = #residual_blocks in each stack layer = self.resnet_size\r\n The standard_block has 2 layers each.\r\n The bottleneck_block has 3 layers each.\r\n \r\n Example of replacing:\r\n standard_block conv3-16 + conv3-16\r\n bottleneck_block conv1-16 + conv3-16 + conv1-64\r\n\r\n Args:\r\n inputs: A Tensor representing a batch of input images.\r\n \r\n Returns:\r\n A logits Tensor of shape [, self.num_classes].\r\n \"\"\"\r\n super(ResNet, self).__init__()\r\n self.resnet_version = resnet_version\r\n self.resnet_size = resnet_size\r\n self.num_classes = num_classes\r\n self.first_num_filters = first_num_filters\r\n\r\n ### YOUR CODE HERE\r\n filters = 0\r\n # define conv1\r\n self.start_layer = nn.Conv2d(in_channels=3, out_channels=self.first_num_filters, kernel_size=3, stride=1,\r\n padding=1, bias=False)\r\n ### YOUR CODE HERE\r\n\r\n # We do not include batch normalization or activation functions in V2\r\n # for the initial conv1 because the first block unit will perform these\r\n # for both the shortcut and non-shortcut paths as part of the first\r\n # block's projection.\r\n if self.resnet_version == 1:\r\n self.batch_norm_relu_start = batch_norm_relu_layer(\r\n num_features=self.first_num_filters,\r\n eps=1e-5,\r\n momentum=0.997,\r\n )\r\n if self.resnet_version == 1:\r\n block_fn = standard_block\r\n else:\r\n block_fn = bottleneck_block\r\n\r\n self.stack_layers = nn.ModuleList()\r\n for i in range(3):\r\n filters = self.first_num_filters * (2 ** i)\r\n strides = 1 if i == 0 else 2\r\n self.stack_layers.append(stack_layer(filters, block_fn, strides, self.resnet_size, self.first_num_filters))\r\n self.output_layer = output_layer(filters * 4, self.resnet_version, self.num_classes)\r\n\r\n def forward(self, inputs):\r\n outputs = self.start_layer(inputs)\r\n if self.resnet_version == 1:\r\n outputs = self.batch_norm_relu_start(outputs)\r\n for i in range(3):\r\n outputs = self.stack_layers[i](outputs)\r\n # print(\"Output layer: \", i)\r\n outputs = self.output_layer(outputs)\r\n return outputs\r\n\r\n\r\n#############################################################################\r\n# Blocks building the network\r\n#############################################################################\r\n\r\nclass batch_norm_relu_layer(nn.Module):\r\n \"\"\" Perform batch normalization then relu.\r\n \"\"\"\r\n\r\n def __init__(self, num_features, eps=1e-5, momentum=0.997) -> None:\r\n super(batch_norm_relu_layer, self).__init__()\r\n ### YOUR CODE HERE\r\n self.batchNorm = nn.BatchNorm2d(num_features=num_features, eps=eps, momentum=momentum)\r\n self.relu = nn.ReLU()\r\n ### YOUR CODE HERE\r\n\r\n def forward(self, inputs: Tensor) -> Tensor:\r\n ### YOUR CODE HERE\r\n outputs = self.batchNorm(inputs)\r\n outputs = self.relu(outputs)\r\n return outputs\r\n ### YOUR CODE HERE\r\n\r\n\r\nclass standard_block(nn.Module):\r\n \"\"\" Creates a standard residual block for ResNet.\r\n\r\n Args:\r\n filters: A positive integer. The number of filters for the first \r\n convolution.\r\n projection_shortcut: The function to use for projection shortcuts\r\n \t\t(typically a 1x1 convolution when downsampling the input).\r\n\t\tstrides: A positive integer. The stride to use for the block. If\r\n\t\t\tgreater than 1, this block will ultimately downsample the input.\r\n first_num_filters: An integer. The number of filters to use for the\r\n first block layer of the model.\r\n \"\"\"\r\n\r\n def __init__(self, filters, projection_shortcut, strides, first_num_filters) -> None:\r\n super(standard_block, self).__init__()\r\n ### YOUR CODE HERE\r\n self.projection_shortcut = projection_shortcut\r\n ### YOUR CODE HERE\r\n\r\n ### YOUR CODE HERE\r\n # creating residual block for standard resnet\r\n self.conv1 = nn.Conv2d(in_channels=filters, out_channels=filters, stride=1, padding=1, kernel_size=3,\r\n bias=False)\r\n self.bn1 = nn.BatchNorm2d(num_features=filters, eps=1e-5, momentum=0.997)\r\n self.relu1 = nn.ReLU()\r\n\r\n self.conv2 = nn.Conv2d(in_channels=filters, out_channels=filters, stride=1, padding=1, kernel_size=3,\r\n bias=False)\r\n self.bn2 = nn.BatchNorm2d(num_features=filters, eps=1e-5, momentum=0.997)\r\n self.relu2 = nn.ReLU()\r\n ### YOUR CODE HERE\r\n\r\n def forward(self, inputs: Tensor) -> Tensor:\r\n ### YOUR CODE HERE\r\n outputs = inputs\r\n if self.projection_shortcut is not None:\r\n outputs = self.projection_shortcut(inputs)\r\n residual = outputs\r\n # first convolution layer\r\n outputs = self.conv1(outputs)\r\n outputs = self.bn1(outputs)\r\n outputs = self.relu1(outputs)\r\n # second convolution layer\r\n outputs = self.conv2(outputs)\r\n outputs = self.bn2(outputs)\r\n # addition of inputs to outputs\r\n outputs = outputs + residual\r\n # relu after addition\r\n outputs = self.relu2(outputs)\r\n # print(\"Standard layer final: Out final size: \", outputs.size())\r\n return outputs\r\n ### YOUR CODE HERE\r\n\r\n\r\nclass bottleneck_block(nn.Module):\r\n \"\"\" Creates a bottleneck block for ResNet.\r\n\r\n Args:\r\n filters: A positive integer. The number of filters for the first \r\n convolution. NOTE: filters_out will be 4xfilters.\r\n projection_shortcut: The function to use for projection shortcuts\r\n \t\t(typically a 1x1 convolution when downsampling the input).\r\n\t\tstrides: A positive integer. The stride to use for the block. If\r\n\t\t\tgreater than 1, this block will ultimately downsample the input.\r\n first_num_filters: An integer. The number of filters to use for the\r\n first block layer of the model.\r\n \"\"\"\r\n\r\n def __init__(self, filters, projection_shortcut, strides, first_num_filters) -> None:\r\n super(bottleneck_block, self).__init__()\r\n\r\n ### YOUR CODE HERE\r\n # Hint: Different from standard lib implementation, you need pay attention to \r\n # how to define in_channel of the first bn and conv of each block based on\r\n # Args given above.\r\n self.projection_shortcut = projection_shortcut\r\n # creating residual block for standard resnet\r\n in_channel = filters\r\n out_channel = filters // 4\r\n self.bn1 = nn.BatchNorm2d(num_features=filters, eps=1e-5, momentum=0.997)\r\n self.relu1 = nn.ReLU()\r\n self.conv1 = nn.Conv2d(in_channels=in_channel, out_channels=out_channel, stride=1, padding=1, kernel_size=3,\r\n bias=False)\r\n self.bn2 = nn.BatchNorm2d(num_features=out_channel, eps=1e-5, momentum=0.997)\r\n self.relu2 = nn.ReLU()\r\n self.conv2 = nn.Conv2d(in_channels=out_channel, out_channels=out_channel, stride=1, padding=1, kernel_size=3,\r\n bias=False)\r\n self.bn3 = nn.BatchNorm2d(num_features=out_channel, eps=1e-5, momentum=0.997)\r\n self.relu3 = nn.ReLU()\r\n self.conv3 = nn.Conv2d(in_channels=out_channel, out_channels=in_channel, stride=1, padding=1, kernel_size=3,\r\n bias=False)\r\n ### YOUR CODE HERE\r\n\r\n def forward(self, inputs: Tensor) -> Tensor:\r\n ### YOUR CODE HERE\r\n # The projection shortcut should come after the first batch norm and ReLU\r\n # since it performs a 1x1 convolution.\r\n outputs = inputs\r\n if self.projection_shortcut is not None:\r\n outputs = self.projection_shortcut(inputs)\r\n # print(\"bottleneck: input shape: \", inputs.size())\r\n residual = outputs\r\n # first convolution layer - pre activation\r\n outputs = self.bn1(outputs)\r\n outputs = self.relu1(outputs)\r\n outputs = self.conv1(outputs)\r\n # second convolution layer - pre activation\r\n outputs = self.bn2(outputs)\r\n outputs = self.relu2(outputs)\r\n outputs = self.conv2(outputs)\r\n # third convolution - pre activation\r\n outputs = self.bn3(outputs)\r\n outputs = self.relu3(outputs)\r\n outputs = self.conv3(outputs)\r\n # addition of input to output\r\n outputs = outputs + residual\r\n # print(\"Output: \", outputs.size())\r\n # print(\"Bottleneck: final output\")\r\n return outputs\r\n ### YOUR CODE HERE\r\n\r\n\r\nclass stack_layer(nn.Module):\r\n \"\"\" Creates one stack of standard blocks or bottleneck blocks.\r\n\r\n Args:\r\n filters: A positive integer. The number of filters for the first\r\n\t\t\t convolution in a block.\r\n\t\tblock_fn: 'standard_block' or 'bottleneck_block'.\r\n\t\tstrides: A positive integer. The stride to use for the first block. If\r\n\t\t\t\tgreater than 1, this layer will ultimately downsample the input.\r\n resnet_size: #residual_blocks in each stack layer\r\n first_num_filters: An integer. The number of filters to use for the\r\n first block layer of the model.\r\n \"\"\"\r\n\r\n def __init__(self, filters, block_fn, strides, resnet_size, first_num_filters) -> None:\r\n super(stack_layer, self).__init__()\r\n filters_out = filters * 4 if block_fn is bottleneck_block else filters\r\n ### END CODE HERE\r\n # projection_shortcut = ?\r\n # Only the first block per stack_layer uses projection_shortcut and strides\r\n self.projection_shortcut = None\r\n if block_fn is standard_block:\r\n if first_num_filters != filters:\r\n self.projection_shortcut = nn.Sequential(\r\n nn.Conv2d(in_channels=filters_out // 2, out_channels=filters_out, stride=strides, kernel_size=1,\r\n bias=False),\r\n nn.BatchNorm2d(filters_out)\r\n )\r\n elif block_fn is bottleneck_block:\r\n in_filters = filters if first_num_filters == filters else filters * 2\r\n # if first_num_filters != filters:\r\n self.projection_shortcut = nn.Sequential(\r\n nn.Conv2d(in_channels=in_filters, out_channels=filters_out, stride=strides, kernel_size=1,\r\n bias=False),\r\n nn.BatchNorm2d(filters_out)\r\n )\r\n\r\n # create residual blocks\r\n # standard residual block - 2 layers per block\r\n # bottleneck residual block - 3 layers per block\r\n stack_layers = []\r\n for i in range(resnet_size):\r\n # if block_fn is standard_block:\r\n self.projection_shortcut = None if i > 0 else self.projection_shortcut\r\n # print(\"stack layer \", i, \" : filter size\", filters_out)\r\n stack_layers.append(block_fn(filters_out, self.projection_shortcut, strides, first_num_filters))\r\n # print(\"Stack: \", i)\r\n # print(\"Stack layer length: \", len(stack_layers))\r\n self.stack = nn.Sequential(*stack_layers)\r\n ### END CODE HERE\r\n\r\n def forward(self, inputs: Tensor) -> Tensor:\r\n ### END CODE HERE\r\n outputs = self.stack(inputs)\r\n return outputs\r\n ### END CODE HERE\r\n\r\n\r\nclass output_layer(nn.Module):\r\n \"\"\" Implement the output layer.\r\n\r\n Args:\r\n filters: A positive integer. The number of filters.\r\n resnet_version: 1 or 2, If 2, use the bottleneck blocks.\r\n num_classes: A positive integer. Define the number of classes.\r\n \"\"\"\r\n\r\n def __init__(self, filters, resnet_version, num_classes) -> None:\r\n super(output_layer, self).__init__()\r\n # Only apply the BN and ReLU for model that does pre_activation in each\r\n # bottleneck block, e.g. resnet V2.\r\n # print(\"Output Layer filter: \", filters)\r\n if (resnet_version == 2):\r\n self.bn_relu = batch_norm_relu_layer(filters, eps=1e-5, momentum=0.997)\r\n\r\n ### END CODE HERE\r\n if resnet_version == 1:\r\n filters = filters // 4\r\n self.avg_pool = nn.AvgPool2d(8)\r\n self.fc = nn.Linear(in_features=filters, out_features=num_classes, bias=True)\r\n self.softmax = nn.Softmax(dim=-1)\r\n ### END CODE HERE\r\n\r\n def forward(self, inputs: Tensor) -> Tensor:\r\n ### END CODE HERE\r\n outputs = self.avg_pool(inputs)\r\n outputs = outputs.view(outputs.size(0), -1)\r\n outputs = self.fc(outputs)\r\n outputs = self.softmax(outputs)\r\n\r\n return outputs\r\n ### END CODE HERE\r\n","repo_name":"natsu1628/Deep-Learning","sub_path":"ResNet/NetWork.py","file_name":"NetWork.py","file_ext":"py","file_size_in_byte":13954,"program_lang":"python","lang":"en","doc_type":"code","stars":2,"dataset":"github-code","pt":"17"} +{"seq_id":"21568086686","text":"#!/usr/bin/env python3\n# -*- coding: utf-8 -*-\n\"\"\"\nCreated on Thu Mar 2 12:56:53 2023\n\n@author: johnmorgan\n\"\"\"\n\n# O(n^2 + 2^n + nl)\n# Recursive calls to helper O(n^2), n is query length\n# Helper iterates over all possible solutions O(2^n)\n# Helper iterates over entire dictionary O(nl), l is length of dict list\n\n# Space O((n * 2^n) + l)\n\n# Review\n\ndef rec_word_break(s, word_dict, result):\n if len(s) == 0:\n return\n if s in result:\n return result[s]\n res = []\n for word in word_dict:\n if not s.startswith(word):\n continue\n if len(word) == len(s):\n res.append(s)\n else:\n suffix = rec_word_break(s[len(word):], word_dict, result)\n for item in suffix:\n item = word + \" \" + item\n res.append(item)\n result[s] = res\n return res\n\ndef word_break(s, word_dict):\n result = {}\n output = rec_word_break(s, word_dict, result)\n print(result)\n return output\n\ns = \"magiclly\"\nword_dict = [\"ag\",\"al\",\"icl\",\"mag\",\"magic\",\"ly\",\"lly\"]\nprint(word_break(s, word_dict))","repo_name":"johntmorgan/coding_coursework_public","sub_path":"python_practice_problems_2/29_dynamic_programming/word_break.py","file_name":"word_break.py","file_ext":"py","file_size_in_byte":1086,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"17"} +{"seq_id":"70374853466","text":"#!/usr/bin/python3\n\nimport os, time, random\nfrom datetime import datetime\n\ndef read(path='data.txt'):\n raw = data = []\n with open(path, 'r') as file:\n raw = file.readlines()\n \n for item in raw:\n data.append(item.split()[0].split(','))\n for i in range(1, len(data[-1])):\n data[-1][i] = float(data[-1][i])\n return data\n\ndef write(data, path='test.txt'):\n content = ''\n if data:\n for item in data:\n for i in range(1, len(item)):\n item[i] = str(item[i])\n content += ','.join(item) + '\\n'\n with open(path, 'w') as file:\n file.write(content)\n\ndef show(menu, prompt='All stores:'):\n if menu:\n print (prompt)\n for item in menu:\n print(f'{item[0]}')\n else:\n print('The list is empty now.\\n')\n print()\n\ndef reset(menu):\n # os.system('clear')\n print('Data is reset!\\n')\n return menu.clear()\n\ndef input_time(prompt, default):\n business_hour = -1\n try:\n business_hour = float(input(prompt))\n while not 0 <= business_hour <= 24:\n print('invalid time input')\n business_hour = float(input(prompt))\n except:\n business_hour = default\n return business_hour\n\ndef add(menu):\n store = input('Add one new store ......')\n if store not in menu:\n open_hour = input_time('Add open_hours ...... (ex: 7.25)', 0)\n close_hour = input_time('Add close_hours ...... (ex: 16.30)', 24)\n menu.append([store, open_hour, close_hour])\n # os.system('clear')\n print ('Data is update!\\n')\n return menu\n\ndef delete(menu):\n store = input('Delete one store ......')\n menu = [item for item in menu if store != item[0]]\n # os.system('clear')\n print ('Data is update!\\n')\n return menu\n\ndef filter(menu):\n now = datetime.now().hour + datetime.now().minute * 0.01\n new_menu = []\n for item in menu:\n for i in range(1, len(item), 2):\n if item[i] < now < item[i + 1]:\n new_menu.append(item)\n break\n return new_menu\n\ndef choose(menu):\n if menu:\n return random.choice(menu)[0]\n # os.system('clear')\n print('The list is empty now.\\n')\n\ndef main():\n option = '\\n'.join(['(E)xecute program',\n '(L)ist all stores',\n '(A)dd store',\n '(D)elete store',\n '(R)eset data',\n '(Q)uit'])\n path = 'data.txt'\n menu = read(path)\n os.system('clear')\n command = ''\n while command.lower() not in ['quit', 'q']:\n show(filter(menu), 'now available:')\n print(option)\n command = input('Let\\'s choose what to eat ......').lower()\n os.system('clear')\n if command in ['show', 's', 'list', 'ls', 'l']:\n show(menu)\n elif command in ['append', 'add', 'a']:\n menu = add(menu)\n elif command in ['delete', 'del', 'd']:\n menu = delete(menu)\n elif command in ['execute', 'exe', 'e']:\n print(choose(filter(menu)))\n elif command in ['reset', 'r']:\n menu = reset(menu)\n elif command in ['quit', 'q']:\n print ('Thanks for your visit!')\n else:\n print('invalid option input')\n write(menu)\n\ndef test(path='data.txt'):\n menu = read()\n show(menu)\n write(menu)\n\nif __name__ == '__main__':\n main()\n # test()","repo_name":"Chang-chia-hsiang/DineIT","sub_path":"dineit.py","file_name":"dineit.py","file_ext":"py","file_size_in_byte":3451,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"17"} +{"seq_id":"31580320306","text":"import sys\ninput = sys.stdin.readline\n\nif __name__ == \"__main__\":\n N, L = map(int, (input().split(\" \")))\n ant = []\n\n for i in range(1, N+1) :\n buf = int(input())\n ant.append([buf, i])\n ant = sorted(ant, key= lambda x: abs(x[0]))\n \n\n","repo_name":"miseop25/Back_Jun_Code_Study","sub_path":"back_joon/구현/back_joon_2136_개미/back_joon_2136_ver3.py","file_name":"back_joon_2136_ver3.py","file_ext":"py","file_size_in_byte":265,"program_lang":"python","lang":"en","doc_type":"code","stars":2,"dataset":"github-code","pt":"17"} +{"seq_id":"28477851947","text":"from odoo import models, fields, api, _\nfrom odoo.exceptions import UserError\nfrom openerp.addons.amount_to_text_id.amount_to_text import Terbilang\n\nclass ka_account_payment_confirm(models.Model):\n _name = \"ka_account.payment.confirm\" \n _order = \"confirm_date desc, id desc\"\n _inherit = ['mail.thread', 'barcodes.barcode_events_mixin']\n\n _template_voucher = 'ka_account.template_report_confirmed_payment'\n _template_slip_setoran= 'ka_account.template_slip_setoran_bank'\n \n @api.depends('journal_voucher_ids.total_amount')\n def compute_amount(self):\n for rec in self:\n amount_total = 0.0\n for line in rec.journal_voucher_ids:\n amount_total += line.total_amount\n rec.amount_total = amount_total\n \n name = fields.Char('Name', copy=False, default='New')\n confirm_date = fields.Date('Tanggal', copy=False, default=fields.Datetime.now)\n state = fields.Selection([('draft', 'Draft'),('confirm', 'Confirmed')], string='State', default='draft', track_visibility=\"always\", copy=False)\n currency_id = fields.Many2one('res.currency', 'Currency', default=lambda self: self.env.user.company_id.currency_id)\n company_id = fields.Many2one('res.company', 'Company', default=lambda self: self.env.user.company_id.id)\n amount_total = fields.Monetary('Total Amount', compute='compute_amount', copy=False)\n printed = fields.Boolean('Printed', default=False, copy=False)\n journal_id = fields.Many2one('account.journal', 'Journal')\n add_voucher_id = fields.Many2one('ka_account.voucher', 'Tambah Bukti Kas')\n journal_voucher_ids = fields.One2many('ka_account.voucher','confirmed_payment_id', 'Bukti Kas')\n ttd_dir = fields.Many2one('hr.employee', string='Tanda Tangan-1', default=lambda self: self.env.user.company_id.dept_dirut.manager_id)\n ttd_tuk = fields.Many2one('hr.employee', string='Tanda Tangan-2', default=lambda self: self.env.user.company_id.dept_dirprod.manager_id)\n _barcode_msg = fields.Char(\"Error Barcode\", size=64, store=False, default='Atau klik area kosong untuk scan barcode', readonly=True)\n \n @api.multi\n def action_confirm(self):\n for rec in self:\n vals = {'state': 'confirm'}\n if rec.name == 'New':\n vals['name'] = self.env['ir.sequence'].next_by_code(\"ka_account.payment.confirm\")\n rec.write(vals)\n \n for voucher in rec.journal_voucher_ids:\n for payment in voucher.ka_payment_ids:\n payment.write({'state': 'confirmed'})\n \n# if voucher.type == 'internal':\n# if voucher.journal_id.id == voucher.destination_journal_id.id:\n# raise UserError('Sorry, The Journal and Destination Journal cannot be same.')\n# bank_statement_obj_1=self.env['account.bank.statement'].search([('journal_id','=',voucher.journal_id.id), ('state','=','open')])\n# \n# if len(bank_statement_obj_1) > 1:\n# raise UserError(_('You have more than 1 bank statements of journal %s with status New. Please make sure that you only have only 1.') % (voucher.journal_id.name,))\n# elif len(bank_statement_obj_1) == 0:\n# raise UserError(_('You have no bank statement of journal %s with status New. Please create the new one.') % (voucher.journal_id.name,))\n# \n# for statement in bank_statement_obj_1:\n# amount = voucher.total_amount*-1\n# vals = {\n# 'date':voucher.date,\n# 'name': voucher.description,\n# 'partner_id':voucher.partner_id.id,\n# 'amount' : amount,\n# 'statement_id' : statement.id,\n# 'journal_voucher_id' : voucher.id\n# }\n# bank_statement_line_create = self.env['account.bank.statement.line'].create(vals)\n# \n# \n# bank_statement_obj_2=self.env['account.bank.statement'].search([('journal_id','=',voucher.destination_journal_id.id), ('state','=','open')])\n# \n# if len(bank_statement_obj_2) > 1:\n# raise UserError(_('You have more than 1 bank statements of journal %s with status New. Please make sure that you only have only 1.') % (voucher.destination_journal_id.name,))\n# elif len(bank_statement_obj_2) == 0:\n# raise UserError(_('You have no bank statement of journal %s with status New. Please create the new one.') % (voucher.destination_journal_id.name,))\n# \n# for statement in bank_statement_obj_2:\n# amount = voucher.total_amount\n# vals = {\n# 'date':voucher.date,\n# 'name': voucher.description,\n# 'partner_id':voucher.partner_id.id,\n# 'amount' : amount,\n# 'statement_id' : statement.id,\n# 'journal_voucher_id' : voucher.id\n# }\n# bank_statement_line_create = self.env['account.bank.statement.line'].create(vals)\n# else: \n# bank_statement_obj=self.env['account.bank.statement'].search([('journal_id','=',voucher.journal_id.id), ('state','=','open')]) \n# \n# if len(bank_statement_obj) > 1:\n# raise UserError(_('You have more than 1 bank statements of journal %s with status New. Please make sure that you only have only 1.') % (voucher.journal_id.name,))\n# elif len(bank_statement_obj) == 0:\n# raise UserError(_('You have no bank statement of journal %s with status New. Please create the new one.') % (voucher.journal_id.name,))\n# \n# for statement in bank_statement_obj:\n# amount = 0.0\n# if voucher.type == \"inbound\":\n# amount = voucher.total_amount\n# elif voucher.type == \"outbound\":\n# amount = voucher.total_amount*-1 \n# vals = {\n# 'date':voucher.date,\n# 'name': voucher.description,\n# 'partner_id':voucher.partner_id.id,\n# 'amount' : amount,\n# 'statement_id' : statement.id,\n# 'journal_voucher_id' : voucher.id\n# }\n# bank_statement_line_create = self.env['account.bank.statement.line'].create(vals)\n \n @api.multi\n def action_set_draft(self):\n for rec in self:\n rec.write({'state': 'draft', 'printed': False})\n for voucher in rec.journal_voucher_ids:\n for payment in voucher.ka_payment_ids:\n payment.write({'state': 'proposed'})\n \n bank_statement_lines = self.env['account.bank.statement.line'].search([('journal_voucher_id','=',voucher.id)])\n if bank_statement_lines:\n for stline in bank_statement_lines:\n if stline.journal_entry_ids == []:\n stline.unlink()\n else:\n raise UserError('Sorry, you cannot set status to draft because the bank statement line already reconciled.')\n \n @api.multi\n def unlink(self):\n for this in self:\n if this.state == 'confirm':\n raise UserError('Sorry, you can not delete confirmed payments. Please set to draft first.')\n return super(ka_account_payment_confirm, self).unlink()\n\n @api.multi\n def get_partners(self):\n partner_array = []\n for this in self:\n voucher_obj = this.journal_voucher_ids\n for voucher in voucher_obj:\n if voucher.partner_id not in partner_array:\n partner_array.append(voucher.partner_id)\n return partner_array\n \n @api.multi\n def get_vouchers(self,partner):\n payment_array = []\n for this in self:\n voucher_obj = this.journal_voucher_ids\n for voucher in voucher_obj:\n if voucher.partner_id.id == partner.id:\n payment_array.append(voucher)\n return payment_array\n \n @api.multi\n def do_print_selected_payment(self):\n # return\n for this in self:\n report_obj = self.env['report']\n template = self._template_voucher\n report = report_obj._get_report_from_name(template)\n data = {}\n datas = {\n 'ids': this.id,\n 'model': report.model,\n 'form': data,\n }\n self.mark_printed_document()\n return report_obj.get_action(self, template, data=datas)\n\n @api.multi\n def print_slip_setoran_bank(self):\n for this in self:\n report_obj = self.env['report']\n template = self._template_slip_setoran\n report = report_obj._get_report_from_name(template)\n data = {}\n datas = {\n 'ids': this.id,\n 'model': report.model,\n 'form': data,\n }\n self.mark_printed_document()\n return report_obj.get_action(self, template, data=datas)\n\n @api.multi\n def mark_printed_document(self):\n for this in self:\n if this.printed != True:\n vals = {'printed': True}\n this.write(vals)\n \n def amount_to_text_id(self, amount):\n return Terbilang(amount) + \" Rupiah\"\n\n @api.onchange('journal_voucher_ids', 'journal_id')\n def _onchange_allowed_voucher_ids(self):\n '''\n The purpose of the method is to define a domain for the available\n purchase orders.\n '''\n result = {}\n\n # A kas bon can be selected only if at least one kas bon line is not already in the lines\n voucher_ids = self.journal_voucher_ids.mapped('id')\n result['domain'] = {'add_voucher_id': [\n ('state', 'in', ('proposed','approved')),\n ('journal_id', '=', self.journal_id.id),\n ('id', 'not in', voucher_ids)\n ]}\n return result\n \n @api.onchange('add_voucher_id')\n def onchange_voucher(self):\n if not self.add_voucher_id:\n return {}\n\n # Load a line only once\n voucher_id = self.add_voucher_id\n if self.add_voucher_id in self.journal_voucher_ids:\n return\n \n v_ids = []\n vals={}\n for voucher in self.journal_voucher_ids:\n v_ids.append(voucher.id)\n v_ids.append(self.add_voucher_id.id)\n \n vals.update(journal_voucher_ids=[(6, 0, v_ids)])\n self.add_voucher_id = False\n return {'value': vals}\n\n def on_barcode_scanned(self, barcode): \n if barcode:\n voucher_ids = self.journal_voucher_ids.mapped('id')\n voucher_id = self.env['ka_account.voucher'].search([\n ('name','=',barcode),\n ('state', 'in', ('proposed','approved')),\n ('journal_id', '=', self.journal_id.id),\n ('id', 'not in', voucher_ids),\n ])\n if len(voucher_id) > 1:\n self._barcode_msg = 'Nomor Bukti tersebut Ada lebih dari satu'\n \n if voucher_id:\n self.add_voucher_id = voucher_id[0]\n self._barcode_msg = \"\"\n else:\n self._barcode_msg = 'Nomor Bukti Kas tidak ditemukan'\n\n\n def write(self, vals):\n voucher_ids = []\n if 'journal_voucher_ids' in vals:\n for j in vals['journal_voucher_ids']:\n voucher_ids.append([4, j[1], False])\n \n vals.update({'journal_voucher_ids': voucher_ids})\n return super(ka_account_payment_confirm, self).write(vals)\n\n @api.model\n def create(self, vals):\n voucher_ids = []\n if 'journal_voucher_ids' in vals:\n for j in vals['journal_voucher_ids']:\n voucher_ids.append([4, j[1], False])\n \n vals.update({'journal_voucher_ids': voucher_ids})\n return super(ka_account_payment_confirm, self).create(vals)\n ","repo_name":"Daneswara/odoou","sub_path":"ka_account/models/ka_account_payment_confirm.py","file_name":"ka_account_payment_confirm.py","file_ext":"py","file_size_in_byte":12907,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"17"} +{"seq_id":"28653449848","text":"import numpy as np\nimport matplotlib.pyplot as plt\n#import toàn bộ file univariate.txt\nX = np.loadtxt('D:\\\\OneDrive - Hanoi University of Science and Technology\\\\Tailieu\\\\AI\\\\Code\\\\MLpredict\\\\univariate.txt', delimiter = ',')\n#import Theta từ file univariate_theta.txt\nTheta = np.loadtxt('D:\\\\OneDrive - Hanoi University of Science and Technology\\\\Tailieu\\\\AI\\\\Code\\\\MLpredict\\\\univariate_theta.txt')\n#Lưu y\ny = np.copy(X[:,-1])\n#Chuyển cột đầu (x1) sang cột thứ 2\nX[:,1] = X[:,0]\n#Đổi cột đầu thành số 1\nX[:,0] = 1\n#Tính lợi nhuận (đơn vị 10000$)\npredict = X @ Theta\n#Chuyển lợi nhuận về đơn vị $\npredict = 10000 * predict\n#in cặp dân số-lợi nhuận đầu tiên (đơn vị dân số: người)\nprint('%d người : %.2f$' %(X[0,1]*10000,predict[0]))\n\n#Plot giá trị thực tế (không lấy cột bias 1 đầu)\n#X[:,1:] là x-axis của biểu đồ, không lấy cột đầu; y là y-axis, rx là red x, plot dữ liệu bằng dấu x màu đỏ\nplt.plot(X[:,1:],y,'rx')\nplt.plot(predict/10000, y, '-b')\nplt.show()","repo_name":"nazubi222/AI","sub_path":"Code/MLpredict/predict.py","file_name":"predict.py","file_ext":"py","file_size_in_byte":1080,"program_lang":"python","lang":"vi","doc_type":"code","stars":0,"dataset":"github-code","pt":"17"} +{"seq_id":"25464731736","text":"import math\r\n\r\nprint(\"Is it Prime\")\r\n\r\nn = int(input(\"Enter Number: \"))\r\n\r\nif n < 2:\r\n print (\"All Prime numbers are greater that 1\")\r\n quit()\r\nelif n == 2:\r\n print(\"It's Prime\")\r\n quit()\r\n \r\ni = 2\r\n\r\nlimit = int(math.sqrt(n))\r\n\r\nwhile i <= limit:\r\n if n % i == 0:\r\n print(\"It's not Prime\")\r\n quit()\r\n i += 1\r\n \r\nprint (\"It's Prime\")","repo_name":"XaveXendragon/special-octo-enigma","sub_path":"python3/prime/Priming.py","file_name":"Priming.py","file_ext":"py","file_size_in_byte":371,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"17"} +{"seq_id":"16945862296","text":"\"\"\"Support for the Xiaomi IR Remote (Chuangmi IR).\"\"\"\r\nimport asyncio\r\nimport logging\r\nfrom datetime import timedelta\r\nimport re\r\nfrom xml.dom import minidom\r\nfrom xml.sax.saxutils import escape\r\nimport struct\r\nimport time\r\n\r\nimport voluptuous as vol\r\n\r\nfrom homeassistant.components.remote import (\r\n ATTR_DELAY_SECS,\r\n DEFAULT_DELAY_SECS, PLATFORM_SCHEMA, RemoteDevice)\r\nfrom homeassistant.const import (\r\n CONF_NAME, CONF_URL, CONF_TIMEOUT)\r\nimport homeassistant.helpers.config_validation as cv\r\nfrom homeassistant.util import (Throttle, slugify)\r\nimport traceback\r\nREQUIREMENTS = ['async-upnp-client==0.14.8']\r\n_LOGGER = logging.getLogger(__name__)\r\n\r\nDATA_KEY = 'upnp_maintvagent2_remote'\r\n\r\n\r\nDEFAULT_TIMEOUT = 5\r\nMIN_TIME_BETWEEN_UPDATES = timedelta(minutes=1)\r\n\r\nPLATFORM_SCHEMA = PLATFORM_SCHEMA.extend({\r\n vol.Required(CONF_NAME): cv.string,\r\n vol.Required(CONF_URL): cv.string,\r\n vol.Optional(CONF_TIMEOUT, default=DEFAULT_TIMEOUT):\r\n vol.All(int, vol.Range(min=0))\r\n}, extra=vol.ALLOW_EXTRA)\r\n\r\n\r\nasync def async_setup_platform(hass, config, async_add_entities,\r\n discovery_info=None):\r\n \"\"\"Set up the Xiaomi IR Remote (Chuangmi IR) platform.\"\"\"\r\n\r\n friendly_name = config.get(CONF_NAME)\r\n url = config.get(CONF_URL)\r\n # Create handler\r\n _LOGGER.info(\"Initializing %s with url %s\", friendly_name, url)\r\n # The Chuang Mi IR Remote Controller wants to be re-discovered every\r\n # 5 minutes. As long as polling is disabled the device should be\r\n # re-discovered (lazy_discover=False) in front of every command.\r\n\r\n # Check that we can communicate with device.\r\n\r\n if DATA_KEY not in hass.data:\r\n hass.data[DATA_KEY] = {}\r\n\r\n timeout = config.get(CONF_TIMEOUT)\r\n unique_id = url.replace(\"/\", \"\").replace(\":\", \"\").replace(\".\", \"_\")\r\n\r\n xiaomi_miio_remote = MainTVAgent2Remote(friendly_name, url, unique_id, timeout)\r\n\r\n hass.data[DATA_KEY][friendly_name] = xiaomi_miio_remote\r\n\r\n async_add_entities([xiaomi_miio_remote])\r\n\r\n\r\nclass MainTVAgent2Remote(RemoteDevice):\r\n \"\"\"Representation of a Xiaomi Miio Remote device.\"\"\"\r\n\r\n STATES = [\"channel\", \"source\", \"sourceidx\"]\r\n\r\n def _destroy_device(self):\r\n self._service = None\r\n self._state = \"off\"\r\n\r\n async def reinit(self):\r\n if not self._service:\r\n try:\r\n _LOGGER.warn(\"Reiniting %s\", self._url)\r\n self._device = await self._factory.async_create_device(self._url)\r\n # get RenderingControle-service\r\n self._service = self._device.service('urn:samsung.com:service:MainTVAgent2:1')\r\n await self._get_channels_list()\r\n await self._get_sources_list()\r\n if len(self._channels) and len(self._sources):\r\n self._state = \"on\"\r\n return self._service\r\n else:\r\n self._destroy_device()\r\n except BaseException as ex:\r\n self._state = \"off\"\r\n _LOGGER.error(\"Reinit Error %s: %s\", self._url, ex)\r\n return None\r\n except Exception:\r\n self._state = \"off\"\r\n _LOGGER.error(\"Reinit Error %s\", self._url)\r\n return None\r\n else:\r\n return self._service\r\n\r\n def __init__(self, friendly_name, url, unique_id, timeout):\r\n from async_upnp_client import UpnpFactory\r\n from async_upnp_client.aiohttp import AiohttpRequester\r\n \"\"\"Initialize the remote.\"\"\"\r\n self._name = friendly_name\r\n self._url = url\r\n self._unique_id = unique_id\r\n self._state = \"off\"\r\n self._device = None\r\n self._service = None\r\n self._states = dict.fromkeys(MainTVAgent2Remote.STATES, '-5')\r\n requester = AiohttpRequester(timeout)\r\n self._factory = UpnpFactory(requester, disable_unknown_out_argument_error=True)\r\n self._sources = []\r\n self._channels = {}\r\n self._channel_list_type = None\r\n self._channel_satellite_id = None\r\n self._current_source = ''\r\n self._current_source_t = 0\r\n self._current_channel_t = 0\r\n self._current_source_l_t = 0\r\n self._current_channel_l_t = 0\r\n\r\n @property\r\n def unique_id(self):\r\n \"\"\"Return an unique ID.\"\"\"\r\n return self._unique_id\r\n\r\n @property\r\n def name(self):\r\n \"\"\"Return the name of the remote.\"\"\"\r\n return self._name\r\n\r\n @property\r\n def device(self):\r\n \"\"\"Return the remote object.\"\"\"\r\n return self._device\r\n\r\n @property\r\n def is_on(self):\r\n \"\"\"Return False if device is unreachable, else True.\"\"\"\r\n return self._state == \"on\"\r\n\r\n @property\r\n def should_poll(self):\r\n \"\"\"We should not be polled for device up state.\"\"\"\r\n return True\r\n\r\n @property\r\n def device_state_attributes(self):\r\n \"\"\"Hide remote by default.\"\"\"\r\n return self._states\r\n\r\n async def async_turn_on(self, **kwargs):\r\n \"\"\"Turn the device on.\"\"\"\r\n _LOGGER.error(\"Device does not support turn_on, \"\r\n \"please use 'remote.send_command' to send commands.\")\r\n\r\n async def async_turn_off(self, **kwargs):\r\n \"\"\"Turn the device off.\"\"\"\r\n _LOGGER.error(\"Device does not support turn_off, \"\r\n \"please use 'remote.send_command' to send commands.\")\r\n\r\n @staticmethod\r\n async def fetch_page(url, timeout=10):\r\n import aiohttp\r\n async with aiohttp.ClientSession() as session:\r\n async with session.get(url, timeout=timeout) as response:\r\n assert response.status == 200\r\n return await response.read()\r\n\r\n async def _get_channels_list(self):\r\n now = time.time()\r\n if (not len(self._channels) or now - self._current_channel_l_t >= 600) and self._service:\r\n res = dict()\r\n try:\r\n res = await self._service.action(\"GetChannelListURL\").async_call()\r\n self._channel_list_type = res[\"ChannelListType\"]\r\n self._channel_satellite_id = 0 if \"SatelliteID\" not in res or res[\"SatelliteID\"] is None else res[\"SatelliteID\"]\r\n webContent = await MainTVAgent2Remote.fetch_page(res['ChannelListURL'])\r\n self._channels = Channel._parse_channel_list(webContent)\r\n self._current_channel_l_t = now\r\n except Exception:\r\n _LOGGER.error(\"GetChannelsList error rv = %s: %s\", str(res), traceback.format_exc())\r\n self._channels = {}\r\n\r\n async def _get_sources_list(self):\r\n now = time.time()\r\n if (not len(self._sources) or now - self._current_source_l_t >= 600) and self._service:\r\n res = dict()\r\n try:\r\n res = await self._service.action(\"GetSourceList\").async_call()\r\n xmldoc = minidom.parseString(res['SourceList'])\r\n sources = xmldoc.getElementsByTagName('Source')\r\n self._sources = []\r\n i = 0\r\n for s in sources:\r\n src = Source(s, i)\r\n i += 1\r\n if src.sname != 'av' and src.sname != 'AV':\r\n self._sources.append(src)\r\n self._current_source_l_t = now\r\n except Exception:\r\n _LOGGER.error(\"GetSourceList error rv = %s: %s\", res, traceback.format_exc())\r\n self._sources = []\r\n\r\n async def _get_current_source(self):\r\n now = time.time()\r\n rv = self._states['source']\r\n if not len(rv) or now-self._current_source_t >= 10:\r\n try:\r\n res = await self._service.action(\"GetCurrentExternalSource\").async_call()\r\n if 'Result' in res and res['Result'] == \"OK\":\r\n self._current_source_t = now\r\n rv = res['CurrentExternalSource']\r\n if self._states[\"source\"] != rv:\r\n self._states[\"source\"] = rv\r\n c = next((x.idx for x in self._sources if x.sname == rv), 0)\r\n self._states[\"sourceidx\"] = c\r\n else:\r\n rv = ''\r\n except Exception:\r\n _LOGGER.error(\"GetCurentExternalSource error %s\", traceback.format_exc())\r\n rv = ''\r\n return rv\r\n\r\n async def _get_current_channel(self):\r\n now = time.time()\r\n rv = self._states[\"channel\"]\r\n if not len(rv) or now - self._current_channel_t >= 10:\r\n try:\r\n res = await self._service.action(\"GetCurrentMainTVChannel\").async_call()\r\n if 'Result' in res and res['Result'] == \"OK\":\r\n self._current_channel_t = now\r\n xmldoc = minidom.parseString(res['CurrentChannel'])\r\n c = Channel(xmldoc)\r\n rv = c.major_ch\r\n self._states[\"channel\"] = rv\r\n else:\r\n rv = ''\r\n except Exception:\r\n _LOGGER.error(\"GetCurrentMainTVChannel error %s\", traceback.format_exc())\r\n rv = ''\r\n return rv\r\n\r\n @Throttle(MIN_TIME_BETWEEN_UPDATES)\r\n async def async_update(self, **kwargs):\r\n self._state = \"off\"\r\n err = 0\r\n if await self.reinit():\r\n src = await self._get_current_source()\r\n if not len(src):\r\n err += 1\r\n chan = await self._get_current_channel()\r\n if not len(chan):\r\n err += 1\r\n if err == 2:\r\n self._destroy_device()\r\n else:\r\n self._state = \"on\"\r\n\r\n async def _send_command(self, packet, totretry):\r\n if isinstance(packet, float):\r\n await asyncio.sleep(packet)\r\n return True\r\n else:\r\n for r in range(totretry):\r\n _LOGGER.info(\"Pid is %s (%d/%d)\", repr(packet), r, totretry)\r\n if await self.reinit():\r\n try:\r\n if isinstance(packet, Channel):\r\n vv = await self._service.action(\"SetMainTVChannel\").async_call(\r\n **packet.as_params(self._channel_list_type, self._channel_satellite_id))\r\n if 'Result' in vv and vv['Result'] == \"OK\":\r\n self._states[\"channel\"] = packet.dispno\r\n break\r\n else:\r\n _LOGGER.error(\"Change channel rv %s\", str(vv))\r\n self._destroy_device()\r\n elif isinstance(packet, Source):\r\n vv = await self._service.action(\"SetMainTVSource\").async_call(**packet.as_params())\r\n if 'Result' in vv and vv['Result'] == \"OK\":\r\n self._states[\"source\"] = packet.sname\r\n self._states[\"sourceidx\"] = packet.idx\r\n break\r\n else:\r\n _LOGGER.error(\"Change source rv %s\", str(vv))\r\n elif packet == \"reloadchannels\":\r\n self._current_channel_l_t = 0\r\n await self._get_channels_list()\r\n if self._current_channel_l_t > 0:\r\n break\r\n elif packet == \"reloadsources\":\r\n self._current_source_l_t = 0\r\n await self._get_sources_list()\r\n if self._current_source_l_t > 0:\r\n break\r\n except Exception:\r\n _LOGGER.error(\"Send command channel %s\", traceback.format_exc())\r\n self._destroy_device()\r\n return False\r\n\r\n def command2payloads(self, command):\r\n command = command.lower()\r\n _LOGGER.info(\"Searching for %s\", command)\r\n if command == \"reloadchannels\" or command == \"reloadsources\":\r\n return [command]\r\n elif re.search(r\"^t[0-9\\.]+$\", command) is not None:\r\n return [float(command[1:])]\r\n mo = re.search(r\"^ch([0-9]+)$\", command)\r\n if mo is not None:\r\n c = mo.group(1)\r\n if c in self._channels:\r\n return [self._channels[c]]\r\n else:\r\n return []\r\n mo = re.search(r\"^sr([0-9]+)$\", command)\r\n if mo is not None:\r\n c = int(mo.group(1))\r\n if len(self._sources) > c:\r\n return [self._sources[c]]\r\n else:\r\n return []\r\n c = next((x for x in self._sources if x.sname == command or slugify(x.sname) == command), None)\r\n if c is not None:\r\n return [c]\r\n else:\r\n return []\r\n\r\n async def async_send_command(self, command, **kwargs):\r\n \"\"\"Send a command.\"\"\"\r\n if await self.reinit():\r\n delay = kwargs.get(ATTR_DELAY_SECS, DEFAULT_DELAY_SECS)\r\n j = 0\r\n for c in command:\r\n payloads = self.command2payloads(c)\r\n k = 0\r\n pause = False\r\n for local_payload in payloads:\r\n pause = await self._send_command(local_payload, 3)\r\n k += 1\r\n if not pause and k < len(payloads):\r\n await asyncio.sleep(delay)\r\n j += 1\r\n if not pause and j < len(command):\r\n await asyncio.sleep(delay)\r\n\r\n\r\nclass ContextException(Exception):\r\n \"\"\"An Exception class with context attached to it, so a caller can catch a\r\n (subclass of) ContextException, add some context with the exception's\r\n add_context method, and rethrow it to another callee who might again add\r\n information.\"\"\"\r\n\r\n def __init__(self, msg, context=[]):\r\n self.msg = msg\r\n self.context = list(context)\r\n\r\n def __str__(self):\r\n if self.context:\r\n return '%s [context: %s]' % (self.msg, '; '.join(self.context))\r\n else:\r\n return self.msg\r\n\r\n def add_context(self, context):\r\n self.context.append(context)\r\n\r\n\r\nclass ParseException(ContextException):\r\n \"\"\"An Exception for when something went wrong parsing the channel list.\"\"\"\r\n pass\r\n\r\n\r\ndef _getint(buf, offset):\r\n \"\"\"Helper function to extract a 16-bit little-endian unsigned from a char\r\n buffer 'buf' at offset 'offset'..'offset'+2.\"\"\"\r\n x = struct.unpack('\r\n # [2 bytes int] Major channel ()\r\n # [2 bytes int] Minor channel ()\r\n # [2 bytes int] PTC (Physical Transmission Channel?), \r\n # [2 bytes int] Program Number (in the mux'ed MPEG or so?), \r\n # [2 bytes int] They've always been 0xffff for me, so I'm just assuming\r\n # they have to be :)\r\n # [4 bytes string, \\0-padded] The (usually 3-digit, for me) channel number\r\n # that's displayed (and which you can enter), in ASCII\r\n # [2 bytes int] Length of the channel title\r\n # [106 bytes string, \\0-padded] The channel title, in UTF-8 (wow)\r\n\r\n t = _getint(buf, 0)\r\n if t == 4:\r\n self.ch_type = 'CDTV'\r\n elif t == 3:\r\n self.ch_type = 'CATV'\r\n elif t == 2:\r\n self.ch_type = 'DTV'\r\n else:\r\n raise ParseException('Unknown channel type %d' % t)\r\n\r\n self.major_ch = _getint(buf, 2)\r\n self.minor_ch = _getint(buf, 4)\r\n self.ptc = _getint(buf, 6)\r\n self.prog_num = _getint(buf, 8)\r\n\r\n if _getint(buf, 10) != 0xffff:\r\n raise ParseException('reserved field mismatch (%04x)' % _getint(buf, 10))\r\n\r\n self.dispno = buf[12:16].decode('utf-8').rstrip('\\x00')\r\n\r\n title_len = _getint(buf, 22)\r\n self.title = buf[24:24+title_len].decode('utf-8')\r\n\r\n def display_string(self):\r\n \"\"\"Returns a unicode display string, since both __repr__ and __str__ convert it\r\n to ascii.\"\"\"\r\n\r\n return u'[%s] % 4s %s' % (self.ch_type, self.dispno, self.title)\r\n\r\n def __repr__(self):\r\n # return self.as_xml\r\n return '' % \\\r\n (self.dispno, repr(self.title), self.ch_type, self.major_ch, self.minor_ch, self.ptc,\r\n self.prog_num)\r\n\r\n @property\r\n def as_xml(self):\r\n \"\"\"The channel list as XML representation for SetMainTVChannel.\"\"\"\r\n\r\n return ('%s%d'\r\n '%d%d%d') % \\\r\n (escape(self.ch_type), self.major_ch, self.minor_ch, self.ptc, self.prog_num)\r\n\r\n def as_params(self, chtype, sid):\r\n return {'ChannelListType': chtype, 'Channel': self.as_xml, 'SatelliteID': sid}\r\n\r\n\r\nclass Source(object):\r\n def __init__(self, root, idx):\r\n name = root.getElementsByTagName('SourceType')\r\n sid = root.getElementsByTagName('ID')\r\n self.sname = name[0].childNodes[0].nodeValue\r\n self.sid = int(sid[0].childNodes[0].nodeValue)\r\n self.idx = idx\r\n\r\n def __repr__(self):\r\n return '' % \\\r\n (repr(self.sname), self.sid, self.idx)\r\n\r\n def as_params(self):\r\n return {'Source': self.sname, 'ID': self.sid, 'UiID': self.sid}\r\n","repo_name":"p3g4asus/home-assistant-custom-components","sub_path":"upnp_maintvagent2/remote.py","file_name":"remote.py","file_ext":"py","file_size_in_byte":21456,"program_lang":"python","lang":"en","doc_type":"code","stars":8,"dataset":"github-code","pt":"17"} +{"seq_id":"30843443410","text":"import cv2\nimport pytesseract\nimport numpy as np\nfrom sys import argv\nfrom invoice2data import extract_data\nfrom invoice2data.extract.loader import read_templates\nimport yaml\nimport glob\nimport errno\nimport os\nimport pymongo\n#jpg_path=\"pdf/RG_100068630897.pdf0.jpg\"\n# Import Python json module\nimport json\n\nif len(argv) > 1:\n jpg_path = argv[1]\nelse:\n jpg_path = input('pdf file path>>> ')\n\ntry:\n # Store Pdf with convert_from_path function\n print(jpg_path)\n read_template = read_templates(folder=\"invoice_templates\")\n pdfFiles = []\n pdfFiles1 = []\n pdfFiles2 = []\n filenames=[]\n path_filename=[]\n\n for filename in os.listdir(jpg_path):\n if filename.endswith(\".pdf\"):\n filenames.append(filename)\n pathname = jpg_path+str(filename)\n print(pathname)\n #path_filename.append(pathname)\n result = extract_data(pathname, read_template)\n print(result)\n #exit()\n\n result['date']=result['date'].strftime(\"%d.%m.%Y\")\n\n if \"sale_date\" in result:\n result['sale_date']=result['sale_date'].strftime(\"%d.%m.%Y\")\n\n if \"subscription_date\" in result:\n result['subscription_date']=result['subscription_date'].strftime(\"%d.%m.%Y\")\n\n print(result)\n print(\"----------------------\")\n if (result==False):\n #pdfFiles.append(filename)\n exit()\n else:\n #pdfFiles.append(result)\n with open(pathname + \".json\", 'w') as file:\n file.write(json.dumps(result))\n\n with open(pathname + \".date\", 'w') as file:\n file.write(str(result['date']))\n\n with open(pathname + \".price\", 'w') as file:\n file.write(str(result['amount']))\n\n with open(pathname + \".number\", 'w') as file:\n file.write(str(result['invoice_number']))\n\n with open(pathname + \".currency\", 'w') as file:\n currency=str(result['currency'])\n currency=currency.replace(\"€\", \"EUR\" )\n currency=currency.replace(\"$\", \"USD\" )\n file.write(currency)\n\n #image = cv2.imread(jpg_path)\n #custom_config = r'--oem 3 --psm 6'\n #txt_content = (pytesseract.image_to_string(image, config=custom_config))\n #with open(jpg_path + \".txt\", 'w') as file:\n # file.write(txt_content)\n\n\nexcept FileNotFoundError:\n print(f'{argv[1]} not found')\n\nexcept TypeError as error:\n print(error)\n\n","repo_name":"letpdf/bash","sub_path":"pdfs2txt.py","file_name":"pdfs2txt.py","file_ext":"py","file_size_in_byte":2604,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"17"} +{"seq_id":"73583768024","text":"from linecache import checkcache, getline\r\nfrom typing import Tuple, Optional\r\nfrom sys import exc_info\r\nimport traceback\r\nimport asyncio\r\nimport logging\r\nimport shutil\r\nimport time\r\nimport pwd\r\nimport os\r\n\r\n\r\n_LOGGER = logging.getLogger(__name__)\r\n_LOGGER.addHandler(logging.NullHandler())\r\n\r\n\r\ndef exception_handler(a_exception):\r\n e_type, e_obj, e_tb = exc_info()\r\n frame = e_tb.tb_frame\r\n lineno = e_tb.tb_lineno\r\n filename = frame.f_code.co_filename\r\n checkcache(filename)\r\n line = getline(filename, lineno, frame.f_globals)\r\n return \"Exception{0} in {1}\\n\"\\\r\n \"Line {2}: '{3}'\\n\"\\\r\n \"Message: {4}\".format(type(a_exception), filename, lineno, line.strip(), a_exception)\r\n\r\n\r\ndef get_decorator(errors=(Exception, ), default_value=None, log_out_foo=print):\r\n def decorator(func):\r\n def new_func(*args, **kwargs):\r\n try:\r\n return func(*args, **kwargs)\r\n except errors:\r\n log_out_foo(traceback.format_exc())\r\n return default_value\r\n return new_func\r\n return decorator\r\n\r\n\r\nexception_decorator = get_decorator(log_out_foo=logging.critical)\r\nexception_decorator_print = get_decorator(log_out_foo=print)\r\nassertion_decorator = get_decorator(errors=(AssertionError, ), log_out_foo=logging.critical)\r\n\r\n\r\nclass Timer:\r\n \"\"\"\r\n Класс таймера.\r\n Позволяет измерять время\r\n \"\"\"\r\n def __init__(self, a_interval_s: float):\r\n \"\"\"\r\n Инициализирует таймер\r\n :param a_interval_s: интервал таймера в секундах\r\n \"\"\"\r\n self.interval_s = a_interval_s\r\n self.start_time = 0.\r\n self.stop_time = 0.\r\n self.__started = False\r\n\r\n def start(self, a_interval_s: float = None):\r\n \"\"\"\r\n Запускает таймер\r\n Если a_interval_s != None, устанавливает время таймера перед запуском\r\n \"\"\"\r\n self.__started = True\r\n self.start_time = time.perf_counter()\r\n if a_interval_s is not None:\r\n self.interval_s = a_interval_s\r\n self.stop_time = self.start_time + self.interval_s\r\n\r\n def stop(self):\r\n \"\"\"\r\n Останавливает таймер\r\n \"\"\"\r\n self.start_time = 0\r\n self.stop_time = 0\r\n self.__started = False\r\n\r\n def check(self) -> bool:\r\n \"\"\"\r\n Возвращает True, если таймер сработал (Вре��я self.interval_s прошло с момента вызова self.start()), иначе False\r\n Если таймер сработал, будет всегда возвращать True, пока не будут вызваны self.start() или self.stop()\r\n \"\"\"\r\n if not self.__started:\r\n return False\r\n return time.perf_counter() > self.stop_time\r\n\r\n def started(self) -> bool:\r\n \"\"\"\r\n Останавливает таймер (функция self.check() будет возвращать False)\r\n \"\"\"\r\n return self.__started\r\n\r\n def time_passed(self) -> float:\r\n \"\"\"\r\n Если таймер остановлен, возвращает 0\r\n Если таймер запущен, возвращает время, которое прошло с момента запуска таймера.\r\n Если таймер сработал, возвращает self.interval_s\r\n \"\"\"\r\n if not self.__started:\r\n return 0\r\n elif time.perf_counter() > self.stop_time:\r\n return self.interval_s\r\n else:\r\n return time.perf_counter() - self.start_time\r\n\r\n\r\nasync def async_check_output(command: str, log_errors=True) -> Tuple[int, str, str]:\r\n \"\"\"\r\n Асинхронно вызывает команду command и ждет ее завершения.\r\n Возвращает stdout, stderr и код возврата команды.\r\n \"\"\"\r\n\r\n proc = await asyncio.subprocess.create_subprocess_shell(command, stdout=asyncio.subprocess.PIPE,\r\n stderr=asyncio.subprocess.PIPE)\r\n stdout, stderr = await proc.communicate()\r\n stdout_formatted = stdout.decode().strip().replace('\\r', '')\r\n stderr_formatted = stderr.decode().strip().replace('\\r', '')\r\n\r\n if log_errors and (proc.returncode or stderr_formatted):\r\n err_msg = f'Команда \"{command}\" вернула код \"{proc.returncode}\"'\r\n if stderr_formatted:\r\n err_msg += f' (stderr: {stderr_formatted})'\r\n else:\r\n err_msg += ' (stderr пуст)'\r\n\r\n _LOGGER.warning(err_msg)\r\n\r\n return proc.returncode, stdout_formatted, stderr_formatted\r\n\r\n\r\ndef utility_call_cmd(utility_name: str) -> Optional[str]:\r\n \"\"\"\r\n Ищет программу с помощью which. Если не находит, то ищет программу в пакетном менеджере flatpak.\r\n Если находит, то возвращает команду для запуска этой программы, иначе None\r\n \"\"\"\r\n call_cmd = shutil.which(utility_name)\r\n return call_cmd\r\n\r\n\r\ndef get_home_dir() -> str:\r\n \"\"\"\r\n Возвращает домашний каталог текущего пользователя\r\n Если при получении домашнего каталога возникла ошибка, возвращает пустую строку\r\n \"\"\"\r\n home = os.environ.get('HOME')\r\n if home is not None:\r\n return home\r\n try:\r\n pw = pwd.getpwuid(os.getuid())\r\n return pw.pw_dir\r\n except Exception:\r\n return \"\"\r\n\r\n\r\ndef string_hex_to_16_bit_integer(s: str):\r\n integer = int(s, 16)\r\n if integer < 2 ** 16:\r\n return integer\r\n else:\r\n raise ValueError","repo_name":"Feelinglight/usbip_userspace","sub_path":"common/utils.py","file_name":"utils.py","file_ext":"py","file_size_in_byte":5947,"program_lang":"python","lang":"ru","doc_type":"code","stars":0,"dataset":"github-code","pt":"17"} +{"seq_id":"31876311767","text":"from pythonic_testcase import *\n\nfrom ..json_utilities import as_safe_json\n\n\nclass AsSafeJsonTest(PythonicTestCase):\n def test_returns_json_string_for_simple_python_types(self):\n assert_equals('1', as_safe_json(1))\n assert_equals('\"foo\"', as_safe_json(u'foo'))\n\n def test_can_escape_html_characters(self):\n assert_equals(\n '\"\\\\u003cscript\\\\u003efoo\\\\u003c/script\\\\u003e\"',\n as_safe_json(u'')\n )\n\n\nimport unittest\ndef suite():\n suite = unittest.TestSuite()\n suite.addTest(unittest.makeSuite(AsSafeJsonTest))\n return suite\n\nif __name__ == '__main__':\n unittest.main(defaultTest='suite')\n","repo_name":"mediadrop/mediadrop","sub_path":"mediadrop/lib/resource_delivery/tests/json_utilities_test.py","file_name":"json_utilities_test.py","file_ext":"py","file_size_in_byte":673,"program_lang":"python","lang":"en","doc_type":"code","stars":864,"dataset":"github-code","pt":"17"} +{"seq_id":"39577940479","text":"#!/usr/bin/python3\n\"\"\" Starts a Flask Web Application \"\"\"\n\nfrom flask import Flask, render_template\napp = Flask(__name__)\n\n\n@app.route('/afrilegal-api-documentation/', strict_slashes=False)\ndef documentation():\n \"\"\"Render technical documentation page\"\"\"\n\n return render_template('doc.html')\n\n\nif __name__ == \"__main__\":\n \"\"\" Main Function \"\"\"\n app.run(host='0.0.0.0', port=5005)\n","repo_name":"samuelselasi/AfriLegal_API","sub_path":"frontend/web_dynamic/tech_doc.py","file_name":"tech_doc.py","file_ext":"py","file_size_in_byte":391,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"17"} +{"seq_id":"40243392772","text":"import asyncio\n\nfrom helpers.mystem import system\nfrom helpers.stemmer import stemmer\n\nfrom typing import NamedTuple\n\nfrom fuzzy import is_dictionary_word, get_fuzzy_words\n\n\ndef get_lexemes(text: str) -> list[str]:\n return [\n stemmer.stem(lexem)\n for lexem in system.lemmatize(text)\n if lexem.strip()\n ]\n\n\nclass EnrichQuery(NamedTuple):\n query: list[str]\n fuzzy_mapping: dict[str, list[tuple[str, float]]]\n\n\nasync def process_lexeme(lexeme: str) -> tuple[str, str]:\n if await is_dictionary_word(lexeme):\n return lexeme, lexeme\n else:\n return lexeme, await get_fuzzy_words(lexeme) or lexeme\n\n\nasync def get_enrich_query(text: str) -> EnrichQuery:\n lexemes = get_lexemes(text)\n query: list[str] = []\n fuzzy_mapping: dict[str, list[tuple[str, float]]] = {}\n process_lexeme_tasks = (process_lexeme(lexeme) for lexeme in lexemes)\n\n for lexeme, processed_lexeme in await asyncio.gather(*process_lexeme_tasks):\n query.append(lexeme)\n if lexeme != processed_lexeme:\n fuzzy_mapping[lexeme] = processed_lexeme\n\n return EnrichQuery(query, fuzzy_mapping)\n\n","repo_name":"GrozniyToaster/info_search","sub_path":"web-api/enrich.py","file_name":"enrich.py","file_ext":"py","file_size_in_byte":1140,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"17"} +{"seq_id":"15853345779","text":"import argparse\r\nfrom antlr4 import *\r\nfrom testLexer import testLexer\r\nfrom testListener import testListener\r\nfrom testParser import testParser\r\nfrom antlr4.tree.Trees import Trees\r\n\r\ndef get_token_type(token):\r\n if token.type == testLexer.INT:\r\n return \"INT\"\r\n elif token.type == testLexer.NEWLINE:\r\n return \"NEWLINE\"\r\n elif token.type == testLexer.OPERATOR:\r\n return \"OPERATOR\"\r\n else:\r\n return \"ERROR UNKNOWN TOKEN\"\r\n\r\ndef main():\r\n\r\n with open(args.file, \"r\") as file:\r\n lines = file.read()\r\n input_stream = InputStream(lines)\r\n lexer = testLexer(input_stream)\r\n token_stream = CommonTokenStream(lexer)\r\n parser = testParser(token_stream)\r\n\r\n # tree = parser.start()\r\n # print(Trees.toStringTree(tree,None, parser))\r\n\r\n token = lexer.nextToken()\r\n\r\n while not token.type == Token.EOF:\r\n print(get_token_type(token), token.text)\r\n token = lexer.nextToken()\r\n\r\n\r\nif __name__ == '__main__':\r\n parser = argparse.ArgumentParser(add_help=True, description='Sample Commandline')\r\n\r\n parser.add_argument('--file', action=\"store\", help=\"path of file to take as input\", nargs=\"?\", metavar=\"file\")\r\n\r\n args = parser.parse_args()\r\n\r\n print(args.file)\r\n\t\r\n main()\t","repo_name":"Alyamr96/Projects","sub_path":"Compilers/Milestone1-Aly/test/AssignemtnII_sampletest_28544.py","file_name":"AssignemtnII_sampletest_28544.py","file_ext":"py","file_size_in_byte":1257,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"17"} +{"seq_id":"29375585723","text":"from typing import List\n\n\"\"\"\n给你一个整数数组 arr,请你帮忙统计数组中每个数的出现次数。\n\n如果每个数的出现次数都是独一无二的,就返回 true;否则返回 false。\n示例 1:\n输入:arr = [1,2,2,1,1,3]\n输出:true\n解释:在该数组中,1 出现了 3 次,2 出现了 2 次,3 只出现了 1 次。没有两个数的出现次数相同。\n\"\"\"\n\n\nclass Solution:\n def uniqueOccurrences(self, arr: List[int]) -> bool:\n dict = {}\n for i in range(len(arr)):\n if str(arr[i]) not in dict:\n dict[str(arr[i])] = 1\n else:\n dict[str(arr[i])] += 1\n arr_show = []\n for key in dict.keys():\n arr_show.append(dict[key])\n arr_show.sort()\n for i in range(1, len(arr_show)):\n if arr_show[i] == arr_show[i - 1]:\n return False\n return True\n","repo_name":"guixiaole/leetcode","sub_path":"simple/leetcode1207.py","file_name":"leetcode1207.py","file_ext":"py","file_size_in_byte":917,"program_lang":"python","lang":"zh","doc_type":"code","stars":0,"dataset":"github-code","pt":"17"} +{"seq_id":"10061304948","text":"import alsaseq\n\nimport pygame\nimport os\nimport os.path\nimport argparse\nimport configparser\nimport options_play\n\nclass SoundGame(object):\n \"\"\"docstring forSoundGame.\"\"\"\n\n def __init__(self, options):\n self.options = options\n self.perform_initializations()\n\n\n def print_newpage(self):\n newpage_string = '\\x1bc'\n print(newpage_string)\n\n\n def load_files(self):\n self.images = []\n\n if self.options[\"presentation_mode\"]:\n filename = self.options[\"song_folder_complete\"] + \"/presentation_mode_start.png\"\n img = pygame.image.load(filename)\n self.images.append(img)\n\n\n folder = self.options[\"song_folder_complete\"]\n files = [f for f in os.listdir(folder) if os.path.isfile(os.path.join(folder, f))]\n files = sorted(files)\n for f in files:\n extension = os.path.splitext(f)[1]\n if extension == \".png\" and f != \"presentation_mode_start.png\":\n filename = os.path.join(folder, f)\n img = pygame.image.load(filename)\n self.images.append(img)\n no_of_steps = len(self.images)\n print(str(no_of_steps) + \" images loaded.\")\n\n\n self.midi_notes = []\n read_data_to_container(self.midi_notes, \"midi_notes\", self.options[\"song_folder_complete\"], int)\n\n if self.options[\"presentation_mode\"]:\n self.midi_notes.append([])\n\n def update_step(self, direction=\"forward\"):\n if direction == \"forward\":\n self.current_step = (self.current_step + 1) % len(self.images)\n elif direction == \"backward\":\n self.current_step = (self.current_step - 1)\n if self.current_step == -1:\n self.current_step = len(self.images) - 1\n\n self.current_activations = []\n self.correct_notes = self.midi_notes[self.current_step]\n white = (255,255,255)\n self.display.fill(white)\n self.display.blit(self.images[self.current_step], (0,0))\n pygame.display.update()\n\n\n\n\n def perform_initializations(self):\n self.init_pygame()\n self.init_alsa()\n self.load_files()\n self.is_running = True\n self.interrupt = False\n\n\n self.current_step = -1\n self.update_step()\n\n\n\n\n def init_alsa(self):\n # prepare alsaseq\n device_no = self.options[\"midi_device_no\"] # find out using aconnect or aconnectgui\n alsaseq.client('Recorder', 1, 0, True )\n alsaseq.connectfrom( 0, device_no, 0 )\n alsaseq.start()\n\n\n def init_pygame(self):\n # pygame mixer\n # mixer_buffer = 10\n # pygame.mixer.pre_init(44100, -16, 1, mixer_buffer)\n # pygame.mixer.init()\n\n # display\n full_screen = False\n full_screen = True\n if full_screen:\n os.environ['SDL_VIDEO_WINDOW_POS'] = \"0,0\"\n pygame.init()\n\n info = pygame.display.Info()\n\n self.display = pygame.display.set_mode((info.current_w, info.current_h), pygame.NOFRAME)\n else:\n self.display = pygame.display.set_mode((0,0))\n\n pygame.display.set_caption('Lilypond Piano Trainer')\n\n\n\n def reaction_note_on(self,event):\n if not self.interrupt:\n pitch = event[7][1]\n velocity = event[7][2]\n if velocity > 0:\n if pitch in self.correct_notes:\n if not pitch in self.current_activations:\n self.current_activations.append(pitch)\n if len(self.current_activations) == len(self.correct_notes):\n self.update_step()\n elif self.options[\"presentation_mode\"] and self.current_step == len(self.images) - 1:\n self.update_step()\n\n def reaction_note_off(self,event):\n pass\n\n\n def play(self):\n\n while self.is_running:\n # check for quit in pygame\n for event in pygame.event.get():\n if event.type == pygame.KEYDOWN:\n if event.key == pygame.K_SPACE:\n self.interrupt = not self.interrupt\n print(\"toggle interrupt\")\n if event.key == pygame.K_ESCAPE:\n self.is_running = False\n if event.key == pygame.K_RIGHT:\n self.update_step()\n if event.key == pygame.K_LEFT:\n self.update_step(direction=\"backward\")\n elif event.type == pygame.QUIT:\n self.is_running = False\n\n\n if alsaseq.inputpending():\n event = alsaseq.input()\n if event[0] == 6: # note on event (zumindest bei kleinem midikeyboard)\n self.reaction_note_on(event)\n elif event[0] == 7:\n self.reaction_note_off(event)\n\n\ndef get_config(filename):\n \"\"\"\n All settings are stored in an external text file.\n \"\"\"\n config = configparser.ConfigParser()\n config.read(filename)\n return config\n\ndef main():\n options = options_play.get_options()\n game = SoundGame(options)\n game.play()\n\n\ndef read_data_to_container(container, filename, song_folder, conversion_func, no_list=False):\n with open(song_folder + filename + \".txt\") as infile:\n for line in infile.read().split(\"\\n\"):\n if line != \"\":\n data = [conversion_func(n) for n in line.split(\" \")]\n if no_list:\n data = data[0]\n container.append(data)\n\n\nif __name__ == \"__main__\":\n main()\n","repo_name":"dh13119/lilypond-piano-trainer","sub_path":"play.py","file_name":"play.py","file_ext":"py","file_size_in_byte":5616,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"17"} +{"seq_id":"11704529109","text":"import bottle\nfrom model import *\n\nime_piskotka = \"uporabnisko_ime\"\nskrivnost = \"ne izdam je\"\n\n\ndef trenutni_uporabnik():\n up_ime = bottle.request.get_cookie(ime_piskotka, secret=skrivnost)\n if up_ime:\n return Uporabnik.preberi(up_ime)\n else:\n bottle.redirect(\"/prijava\")\n\n##############\n\n@bottle.get(\"/\")\ndef osnovna_stran():\n bottle.redirect(\"/prijava\")\n\n@bottle.get(\"/glavna_stran\")\ndef glavna_stran():\n return bottle.template(\"osnovna_stran.html\",\n uporabnik = trenutni_uporabnik(),\n napaka = None)\n\n@bottle.get(\"/prijava\")\ndef prijava_get():\n return bottle.template(\"prijava.html\", napaka=None)\n\n@bottle.post(\"/prijava\")\ndef prijava_post():\n uporabnisko_ime = bottle.request.forms.getunicode(\"uporabnisko_ime\")\n geslo = bottle.request.forms.getunicode(\"geslo\")\n if not uporabnisko_ime:\n return bottle.template(\"prijava.html\", napaka=\"Prosim vnesite uporabniško ime\")\n try:\n Uporabnik.prijava(uporabnisko_ime, geslo)\n bottle.response.set_cookie(ime_piskotka, uporabnisko_ime, skrivnost, path=\"/\")\n bottle.redirect(\"/glavna_stran\")\n except ValueError as upsala:\n return bottle.template(\"prijava.html\", napaka=upsala)\n \n@bottle.get(\"/registracija\")\ndef registracija_get():\n return bottle.template(\"registracija\", napaka=None)\n\n@bottle.post(\"/registracija\")\ndef registracija_post():\n uporabnisko_ime = bottle.request.forms.getunicode(\"uporabnisko_ime\")\n geslo = bottle.request.forms.getunicode(\"geslo\")\n if not uporabnisko_ime:\n return bottle.template(\"registracija.html\", napaka=\"Prosim vnesite uporabniško ime\")\n try:\n Uporabnik.registracija(uporabnisko_ime, geslo)\n bottle.response.set_cookie(ime_piskotka, uporabnisko_ime, secret=skrivnost, path=\"/\")\n bottle.redirect(\"/prijava\")\n except ValueError as upsala:\n return bottle.template(\"registracija.html\", napaka = upsala)\n\n@bottle.get(\"/odjava\")\ndef odjava():\n bottle.response.delete_cookie(ime_piskotka)\n bottle.redirect(\"/prijava\")\n\n###############################\n\n\n@bottle.get(\"/recepti\")\ndef recepti_get():\n vrni = []\n seznam = Recept.naredi_seznam_receptov(os.path.dirname(os.path.abspath(__file__))) #POPRAV DA BO NORMALN DELAL\n if seznam != None:\n for (datoteka, slovar) in seznam:\n vrni.append(slovar)\n return bottle.template(\"rec.html\", recepti = vrni)\n\n@bottle.get(\"/recepti/\")\ndef recepti_post(jed):\n seznam = Recept.naredi_seznam_receptov(os.path.dirname(os.path.abspath(__file__)))\n for (datoteka, slovar) in seznam:\n if jed in datoteka:\n return bottle.template(\"rec_pogled.html\",\n jed = slovar[\"jed\"],\n cas_priprave = slovar[\"cas_priprave\"],\n cas_kuhanja = slovar[\"cas_kuhanja\"],\n priprava = slovar[\"postopek\"])\n else:\n return bottle.redirect(\"/recepti\")\n\n\n@bottle.get(\"/uredi_recept\")\ndef uredi_recept_get():\n vrni = []\n seznam = Recept.naredi_seznam_receptov(os.path.dirname(os.path.abspath(__file__))) #POPRAV DA BO NORMALN DELAL\n if seznam != None:\n for (datoteka, slovar) in seznam:\n vrni.append(slovar)\n return bottle.template(\"uredi_rec.html\", recepti = vrni) \n\n@bottle.get(\"/uredi_recept/\")\ndef uredi_recept_get_jed(jed):\n seznam = Recept.naredi_seznam_receptov(os.path.dirname(os.path.abspath(__file__)))\n for (datoteka, slovar) in seznam:\n if jed in datoteka:\n return bottle.template(\"uredi_rec_pogled.html\",\n jed = slovar[\"jed\"],\n cas_priprave = slovar[\"cas_priprave\"],\n cas_kuhanja = slovar[\"cas_kuhanja\"],\n priprava = slovar[\"postopek\"])\n else:\n return bottle.redirect(\"/recepti\")\n\n@bottle.post(\"/uredi_recept\")\ndef uredi_recept_post():\n jed = bottle.request.forms.getunicode(\"ime\")\n seznam = Recept.naredi_seznam_receptov(os.path.dirname(os.path.abspath(__file__)))\n\n s = None\n for (datoteka, slovar) in seznam:\n if jed in datoteka:\n s = slovar\n \n if s is not None:\n s[\"cas_priprave\"] = bottle.request.forms.getunicode(\"cas_priprave\")\n s[\"cas_kuhanja\"] = bottle.request.forms.getunicode(\"cas_kuhanja\")\n s[\"postopek\"] = bottle.request.forms.getunicode(\"postopek\")\n Recept.shrani_recept_slovar(s)\n else:\n return bottle.redirect(\"/recepti\")\n\n\n@bottle.get(\"/nov_recept\")\ndef nov_recept_get():\n return bottle.template(\"nov_rec.html\", napaka = None)\n\n@bottle.post(\"/nov_recept\") #popravi cas samo stevilke-drgac error, nobeno polje ne sme bit prazno\ndef nov_recept_get():\n jed = bottle.request.forms.getunicode(\"jed\")\n cas_priprave = bottle.request.forms.getunicode(\"cas_priprave\")\n cas_kuhanja = bottle.request.forms.getunicode(\"cas_kuhanja\")\n postopek = bottle.request.forms.getunicode(\"postopek\")\n \n if len(jed) == 0 or len(cas_priprave) == 0 or len(cas_kuhanja) == 0 or len(postopek) == 0:\n return bottle.template(\"nov_rec.html\", napaka = \"Izpolniti morate vsa polja\")\n\n try:\n recept = Recept(jed)\n recept.nastavi_cas(int(cas_priprave), int(cas_kuhanja))\n recept.napisi_postopek(postopek)\n recept.shrani_recept()\n return bottle.template(\"osnovna_stran.html\", uporabnik = trenutni_uporabnik(), napaka = \"Recep uspešno zabeležen!\")\n except ValueError as upsala:\n return bottle.template(\"nov_rec.html\", napaka = upsala)\n\n@bottle.post(\"/izbrisi_recept/\")\ndef izbrisi_recept(jed):\n os.remove(f\"recept.{jed}.json\")\n return bottle.redirect(\"/glavna_stran\")\n\nbottle.run(debug=True, reloader=True)","repo_name":"jostv99/Projekt","sub_path":"spletni_vmesnik.py","file_name":"spletni_vmesnik.py","file_ext":"py","file_size_in_byte":5855,"program_lang":"python","lang":"sl","doc_type":"code","stars":0,"dataset":"github-code","pt":"17"} +{"seq_id":"289161712","text":"from django.contrib import admin\nfrom django.urls import path,include\nfrom customers.views import *\n\nurlpatterns = [\n path('Create',Create,name=\"Create\"),\n path('CreateCustomer',CreateCustomer,name=\"CreateCustomer\"),\n path('List',ListCustomer,name=\"List\"),\n path('edit/',Edit,name=\"Edit\"),\n path('delete/',Delete,name=\"Delete\"),\n]\n","repo_name":"swathi352001/Droame","sub_path":"droame/customers/urls.py","file_name":"urls.py","file_ext":"py","file_size_in_byte":354,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"17"} +{"seq_id":"33185230799","text":"import pytz\nimport pyowm\nimport streamlit as st\nfrom matplotlib import dates\nfrom datetime import datetime\nfrom matplotlib import pyplot as plt\nimport plotly.graph_objects as go\n\nowm = pyowm.OWM('2ab0bb4b60ceed1c7f6b118682958184')\nmgr = owm.weather_manager()\n\ndegree_sign = u'\\N{DEGREE SIGN}'\n\nst.title('Five Day Weather Forecast 🌤')\nst.write('##### Write the name of the City and Select Temperature Unit and Graph Type')\n\nplace = st.text_input(\"Name of the City:\", \"\")\nif place is None:\n st.write(\"Input a City!\")\n\nselect_unit = st.selectbox(\"Select Unit\", (\"Celcius\", \"Fahrenheit\"))\n\ng_type = st.selectbox(\"Select Graph Type\", (\"Line Graph\", \"Bar Graph\"))\n\nif select_unit == 'Celcius':\n unit = 'celsius'\nelse:\n unit = 'fahrenheit'\n\n\ndef get_temperature():\n days = []\n dates_ = []\n temp_min = []\n temp_max = []\n\n forecaster = mgr.forecast_at_place(place, '3h')\n forecast = forecaster.forecast\n\n for weather in forecast:\n day = datetime.utcfromtimestamp(weather.reference_time())\n date = day.date()\n if date not in dates_:\n dates_.append(date)\n temp_min.append(None)\n temp_max.append(None)\n days.append(date)\n temperature = weather.temperature(unit)['temp']\n if not temp_min[-1] or temperature < temp_min[-1]:\n temp_min[-1] = temperature\n if not temp_max[-1] or temperature > temp_max[-1]:\n temp_max[-1] = temperature\n return days, temp_min, temp_max\n\n\ndef init_plot():\n plt.figure(\"PyOWM Weather\", figsize=(5, 4))\n plt.xlabel('Day')\n plt.ylabel(f'Temperature ({degree_sign}F)')\n plt.title('Weekly Forecast')\n\n\ndef plot_temperatures(days, temp_min, temp_max):\n fig = go.Figure(\n data=[\n go.Bar(name='Minimum Temperature', x=days, y=temp_min),\n go.Bar(name='Maximum Temperature', x=days, y=temp_max)\n ]\n )\n fig.update_layout(barmode='group')\n return fig\n\n\ndef plot_temperatures_line(days, temp_min, temp_max):\n fig = go.Figure()\n fig.add_trace(go.Scatter(x=days, y=temp_min, name='Minimum Temperatures'))\n fig.add_trace(go.Scatter(x=days, y=temp_max, name='Maximum Temperatures'))\n return fig\n\n\ndef label_xaxis(days):\n plt.xticks(days)\n axes = plt.gca()\n xaxis_format = dates.DateFormatter('%m/%d')\n axes.xaxis.set_major_formatter(xaxis_format)\n\n\ndef draw_bar_chart():\n days, temp_min, temp_max = get_temperature()\n fig = plot_temperatures(days, temp_min, temp_max)\n st.plotly_chart(fig)\n st.title('Minimum and Maximum Temperatures')\n for i in range(0, 5):\n st.write(\"### \", temp_min[i], degree_sign, ' --- ', temp_max[i], degree_sign)\n\n\ndef draw_line_chart():\n days, temp_min, temp_max = get_temperature()\n fig = plot_temperatures_line(days, temp_min, temp_max)\n st.plotly_chart(fig)\n st.title('Minimum and Maximum Temperatures')\n for i in range(0, 5):\n st.write(\"### \", temp_min[i], degree_sign, ' --- ', temp_max[i], degree_sign)\n\n\ndef other_weather_updates():\n forecaster = mgr.forecast_at_place(place, '3h')\n st.title(\"Impending Temperature Changes: \")\n if forecaster.will_have_fog():\n st.write(\"### FOG Alert!\")\n if forecaster.will_have_rain():\n st.write(\"### RAIN Alert!\")\n if forecaster.will_have_snow():\n st.write(\"### SNOW Alert!\")\n if forecaster.will_have_clear():\n st.write(\"### CLEAR Weather!\")\n if forecaster.will_have_storm():\n st.write(\"### STORM Alert!\")\n if forecaster.will_have_clouds():\n st.write(\"### CLOUDY!\")\n if forecaster.will_have_tornado():\n st.write(\"### TORNADO Alert!\")\n if forecaster.will_have_hurricane():\n st.write(\"### HURRICANE Alert!\")\n\n\ndef cloud_wind():\n obs = mgr.weather_at_place(place)\n weather = obs. weather\n cloud_cov = weather.clouds\n winds = weather.wind()['speed']\n st.title('Cloud Coverage and Wind Speed')\n st.write('### The current cloud coverage for', place, 'is', cloud_cov, '%')\n st.write('### The current wind speed for', place, 'is', winds, '%')\n\n\ndef sunrise_sunset():\n obs = mgr.weather_at_place(place)\n weather = obs.weather\n st.title('Sunrise and Sunset')\n pytz.timezone(\"Asia/Kolkata\")\n ss = weather.sunset_time(timeformat='iso')\n sr = weather.sunrise_time(timeformat='iso')\n st.write('### Sunrise time in', place, 'is', sr)\n st.write('### Sunset time in', place, 'is', ss)\n\n\ndef updates():\n other_weather_updates()\n cloud_wind()\n sunrise_sunset()\n\n\nif __name__ == '__main__':\n\n if st.button(\"SUBMIT\"):\n if g_type == 'Line Graph':\n draw_line_chart()\n else:\n draw_bar_chart()\n updates()\n","repo_name":"vatsal-06/Weather-Forecasting-App","sub_path":"main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":4703,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"17"} +{"seq_id":"3487517913","text":"import requests\nfrom bs4 import BeautifulSoup\nimport pandas as pd\nimport re\nimport pymysql\nimport yaml\nimport sqlalchemy\n\npymysql.install_as_MySQLdb()\n\nwith open(f'..\\..\\config.yaml', encoding='UTF-8') as f:\n _cfg = yaml.load(f, Loader=yaml.FullLoader)\n\n# DB info\nDB_SECRET = _cfg['DB_SECRET']\nFS_DUMMY_TABLE = _cfg['TB_FS_DUMMY'] # test db table\n\ndef crawling_financial_statments(ticker: int):\n \"\"\"\n crawling financial statements from https://finance.naver.com/\n :param ticker: ticker\n :return: no return\n \"\"\"\n\n res = requests.get(f'https://finance.naver.com/item/coinfo.naver?code={ticker}')\n soup = BeautifulSoup(res.text, \"lxml\")\n\n stock_name = soup.select_one('.wrap_company > h2:nth-child(1) > a:nth-child(1)').text\n\n # iframe src\n referer = f'https://navercomp.wisereport.co.kr/v2/company/c1010001.aspx?cmp_cd={ticker}'\n\n res = requests.get(referer)\n soup = BeautifulSoup(res.text, \"lxml\")\n\n # find href from iframe\n id_cnt = 0\n request_id = ''\n for i in soup.find('div', class_=\"all\"): # find all parents that have div.id\n try:\n # find id at 6th div\n if id_cnt < 6:\n request_id = i.attrs['id']\n # print(\"id_cnt : \", id_cnt, \", request_id:\", request_id, i)\n id_cnt += 1\n else:\n break\n except Exception as e:\n # print(e)\n continue\n\n # print(\"request_id : \", request_id)\n\n javascript = soup.select_one('body > div > script') # get javascript\n result = re.search(\"encparam\", javascript.text) # find encparam\n request_encparam = javascript.text[result.end() + 3:result.end() + 35]\n\n market = soup.select('dt.line-left')[8].text.split()[0] # KOSPI or KOSDAQ\n sector = soup.select('dt.line-left')[8].text.split()[-1] # industry classification(Main)\n industry = soup.select('dt.line-left')[9].text.split()[-1] # industry classification(Sub)\n beta = soup.select_one(\n '#cTB11 > tbody > tr:nth-child(6) > td').text.lstrip().rstrip() # beta, unique usage for this project\n\n # find cmp_cd(ticker) and encparam from javascript code(JSON type) because both params always changes\n # fin_typ=4 - IFRS linked financial statements only\n request_url = f\"https://navercomp.wisereport.co.kr/v2/company/ajax/cF1001.aspx?cmp_cd={ticker}&fin_typ=4&freq_typ=A&encparam={request_encparam}&id={request_id}\"\n # print(\"request_url : \", request_url)\n\n # request headers to request with referer\n headers = {\n \"Accept\": \"text/html, */*; q=0.01\",\n \"Accept-Encoding\": \"gzip, deflate, bcolumnsr\",\n \"Accept-Language\": \"ko,ko-KR;q=0.9,en-US;q=0.8,en;q=0.7\",\n \"Host\": \"navercomp.wisereport.co.kr\",\n \"User-Agent\": \"Mozilla/5.0 (X11; Ubuntu; Linux x86_64; rv:107.0) Gecko/20100101 Firefox/107.0\",\n \"referer\": referer,\n }\n\n res = requests.get(request_url, headers=headers)\n soup = BeautifulSoup(res.text, \"lxml\")\n\n # get published year of annual financial statements\n columns = []\n for i in soup.select('th[class^=\"r02c0\"]')[:4]:\n column = i.text.lstrip().rstrip()[:7]\n columns.append(column)\n\n # get annual financial statements info\n financial_summary = soup.select('tbody')[1]\n\n # get index for Dataframe column\n index = []\n for i in financial_summary.select('th.bg.txt'):\n index.append(i.text.lstrip())\n\n df = pd.DataFrame(columns=columns, index=index)\n\n for idx, tr in enumerate(financial_summary.select('tr')):\n values = []\n # annual financial statement info only\n for td in tr.select('td')[:4]:\n try:\n value = td.select_one('span').text.replace(',', '')\n except Exception as e:\n value = 0\n # print(f'value error - select_one(span): ', e)\n values.append(value)\n\n # print(\"values : \", values)\n df.loc[index[idx]] = values\n\n df_T = df.T\n\n df_T['종목코드'] = ticker\n df_T['시장'] = market\n df_T['종목명'] = stock_name\n df_T['대분류'] = sector\n df_T['소분류'] = industry\n df_T['종목베타'] = beta\n df_T['폐업여부'] = 'n' # Y - Close Biz / N - on going biz\n\n df_T = df_T.reset_index(drop=False) # make published year as a column, not index\n df_T.rename(columns={'index': '결산일'}, inplace=True)\n\n # adjust columns for database table\n df_rename_columns = {'결산일': 'setting_date', '시장': 'market', '종목코드': 'ticker', '종목명': 'stock_name',\n '대분류': 'sector', '소분류': 'industry', '종목베타': 'beta', '매출액': 'revenue',\n '영업이익': 'operating_profit', '영업이익(발표기준)': 'std_operating_profit',\n '세전계속사업이익': 'continuing_operations_profit', '당기순이익': 'net_income',\n '당기순이익(지배)': 'control_int_net_income', '당기순이익(비지배)': 'uncontrol_int_net_income',\n '자산총계': 'total_asset', '부채총계': 'total_debt', '자본총계': 'total_capital',\n '자본총계(지배)': 'control_int_total_capital', '자본총계(비지배)': 'uncontrol_int_total_capital',\n '자본금': 'capital', '영업활동현금흐름': 'cf_operation', '투자활동현금흐름': 'cf_investing',\n '재무활동현금흐름': 'cf_financing', 'CAPEX': 'capex', 'FCF': 'fcf', '이자발생부채': 'debt_from_int',\n '영업이익률': 'operating_margin', '순이익률': 'net_margin', 'ROE(%)': 'roe', 'ROA(%)': 'roa',\n '부채비율': 'debt_ratio', '자본유보율': 'retention_rate', 'EPS(원)': 'eps', 'PER(배)': 'per',\n 'BPS(원)': 'bps', 'PBR(배)': 'pbr', '현금DPS(원)': 'cash_dps', '현금배당수익률': 'cash_div_return',\n '현금배당성향(%)': 'cash_div_payout_ratio', '발행주식수(보통주)': 'issued_shares', '폐업여부': 'closure_yn'\n }\n\n df_T.rename(columns=df_rename_columns, inplace=True)\n\n # DB insert\n try:\n engine = sqlalchemy.create_engine(f'mysql://root:{DB_SECRET}@localhost:3306/sqldb', encoding='utf8')\n df_T.to_sql(name=FS_DUMMY_TABLE, con=engine, if_exists='append', index=False)\n print(f\"{stock_name}'s financial statement info insert into {FS_DUMMY_TABLE}\")\n except Exception as e:\n print(f'DB insert exception({FS_DUMMY_TABLE}): ', e)\n\n# test\ncrawling_financial_statments('214870')\n","repo_name":"OliverJoo/AIStockTrading_ReinforcementLearning","sub_path":"Crawling/FinancialStatement/CrawlingFinancialStatement.py","file_name":"CrawlingFinancialStatement.py","file_ext":"py","file_size_in_byte":6636,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"17"} +{"seq_id":"31632197135","text":"from aiogram import types, Dispatcher\nfrom config import bot, dp\n\nfrom aiogram.types import InlineKeyboardMarkup, InlineKeyboardButton\n\n\n# @dp.callback_query_handler(text=\"button_call_1\")\nasync def quiz_2(call: types.CallbackQuery):\n markup = InlineKeyboardMarkup()\n button_call_1 = InlineKeyboardButton(\"NEXT 2\", callback_data=\"button_call_2\")\n markup.add(button_call_1)\n\n question = \"Сколько направление в Geek Tech\"\n answers = [\n \"5\",\n \"3\",\n \"2\",\n \"6\",\n \"4\",\n \"7\",\n ]\n\n await bot.send_poll(\n chat_id=call.from_user.id,\n question=question,\n options=answers,\n is_anonymous=False,\n type='quiz',\n correct_option_id=5,\n explanation=\"Стыдно не знать\",\n open_period=5,\n reply_markup=markup\n )\n\n\nasync def quiz_3(call: types.CallbackQuery):\n markup = InlineKeyboardMarkup()\n button_call_1 = InlineKeyboardButton(\"NEXT 2\", callback_data=\"button_call_3\")\n markup.add(button_call_1)\n\n question = \"в каком году началась 2 мировая война\"\n answers = [\n \"1999\",\n \"2020\",\n \"1894\",\n \"1941\",\n \"2000\",\n ]\n\n await bot.send_poll(\n chat_id=call.from_user.id,\n question=question,\n options=answers,\n is_anonymous=False,\n type='quiz',\n correct_option_id=3,\n explanation=\"Стыдно не знать\",\n open_period=5,\n reply_markup=markup\n )\n\n\ndef register_handler_callback(dp: Dispatcher):\n dp.register_callback_query_handler(quiz_2, text=\"button_call_1\")\n dp.register_callback_query_handler(quiz_3, text=\"button_call_2\")\n","repo_name":"adylbek0408/AdylbekBot","sub_path":"handlers/callback.py","file_name":"callback.py","file_ext":"py","file_size_in_byte":1720,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"17"} +{"seq_id":"29753094767","text":"import paho.mqtt.client as mqtt\nimport json\nimport threading\nimport logging\n\n\nclass PubThread(threading.Thread):\n \"\"\"This class includes the methods necessary to send data to Thingsboard while respecting its API\"\"\"\n\n def __init__(self, raw_connect, raw_telemetry):\n \"\"\"Identifies the Thingsboard IP address and the access token to the gateway created on Thingsboard\"\"\"\n threading.Thread.__init__(self)\n self.gtw_access_token = 'cmrtWotOUSysmsydspo4'\n self.client = None\n self.thingsboard_host = \"iotplatform.int.cetic.be\"\n self.topic_connect = \"v1/gateway/connect\"\n self.topic_attributes = \"v1/gateway/attributes\"\n self.topic_telemetry = \"v1/gateway/telemetry\"\n self.raw_connect = raw_connect\n self.raw_telemetry = raw_telemetry\n\n def on_connect(self, client, userdata, flags, rc):\n if rc == 0:\n logging.info(\"connected with result code \" + str(rc) + \" to Thingsboard\")\n self.client.loop_start()\n try:\n self.client.publish(self.topic_connect, self.raw_connect, qos=1)\n self.client.publish(self.topic_telemetry, self.raw_telemetry, qos=1)\n except KeyboardInterrupt:\n pass\n self.client.loop_stop()\n self.client.disconnect()\n else:\n print(\"Bad connection returned code\", rc)\n\n def on_publish(self, client, obj, mid):\n print(\"mid: \" + str(mid))\n print(\"bonjouuuur\")\n\n def on_disconnect(client, userdata, rc):\n print(\"disconnecting reason \" + str(rc))\n\n def run(self):\n self.client = mqtt.Client()\n self.client.on_connect = self.on_connect\n self.client.on_publish = self.on_publish\n self.client.username_pw_set(self.gtw_access_token)\n self.client.connect(self.thingsboard_host, port=1883, keepalive=60)\n\n self.client.loop_forever()","repo_name":"martindenion/dmway","sub_path":"src/publish/publish.py","file_name":"publish.py","file_ext":"py","file_size_in_byte":1914,"program_lang":"python","lang":"en","doc_type":"code","stars":8,"dataset":"github-code","pt":"17"} +{"seq_id":"2103351421","text":"# {{{ Imports\nfrom django.core.exceptions import PermissionDenied\nfrom django.db.models import F\nfrom django.http import HttpResponse\nfrom django.shortcuts import get_object_or_404\n\nfrom ratings.models import (\n Group,\n Player,\n)\nfrom ratings.templatetags.ratings_extras import (\n ratscale,\n ratscalediff,\n)\n# }}}\n\n# {{{ training view\n# Questions to TheBB\ndef training(request, team_id):\n team = get_object_or_404(Group, id=team_id)\n\n allowed = [\n ('Wake', 'mousesports'),\n ('mouz', 'mousesports'),\n ('TheBB', 'mousesports'),\n ]\n\n if not request.user.is_authenticated() or (request.user.username, team.name) not in allowed:\n raise PermissionDenied\n\n players = Player.objects.filter(\n groupmembership__group=team,\n groupmembership__current=True,\n groupmembership__playing=True,\n )\n\n out = []\n\n for rca in 'ptz':\n players_race = players.filter(race=rca.upper())\n for rcb in 'ptz':\n players_race_weak = players_race\n for other in [r for r in 'ptz' if r != rcb]:\n players_race_weak = players_race_weak.filter(\n **{'current_rating__rating_v%s__lt' % rcb: F('current_rating__rating_v%s' % other)}\n )\n\n if players_race_weak.exists():\n out.append('

Weak %sv%s

    ' % (rca.upper(), rcb.upper()))\n for p in players_race_weak:\n out.append(\n '
  • %s (%.0f; %+.0f)
  • ' \n % ( \n p.tag, \n ratscale(p.current_rating.get_totalrating(rcb.upper())),\n ratscalediff(p.current_rating.get_rating(rcb.upper())),\n )\n )\n out.append('
')\n\n opponents = sorted(\n [p for p in players if p.race == rcb.upper()],\n key=lambda p: p.current_rating.get_totalrating(rca.upper()), reverse=True\n )\n\n out.append(\n '

Strongest %sv%s players are, in order: %s.

'\n % (rcb.upper(), rca.upper(), ', '.join([o.tag for o in opponents]))\n )\n\n return HttpResponse('\\n'.join(out))\n# }}}\n","repo_name":"martijnhoekstra/aligulac","sub_path":"aligulac/ratings/misc_views.py","file_name":"misc_views.py","file_ext":"py","file_size_in_byte":2308,"program_lang":"python","lang":"en","doc_type":"code","dataset":"github-code","pt":"17"} +{"seq_id":"20350084101","text":"import os\nimport pandas as pd\nfrom datasets import Impl_DatasetsWindow\nimport unittest\nimport sys\n\nfrom PyQt5 import QtWidgets\n\napp = QtWidgets.QApplication(sys.argv)\n\nclass Impl_DatasetsWindowTest(unittest.TestCase):\n '''Test the DatasetsWindow GUI'''\n def setUp(self):\n '''Create the GUI'''\n self.form = Impl_DatasetsWindow()\n self.test_csv_path = 'test.csv'\n self.test_csv_data = {'Fixable': [0, 1, 1], 'Column1': ['A', 'B', 'C'], 'Column2': [4.5, 6.7, 8.9]}\n self.test_df = pd.DataFrame(data=self.test_csv_data)\n self.test_json_data = {\"@priority\": [\"1\", \"2\", \"3\", \"4\", \"\"], \"@Fixable\": [0, 1, 0, 1, \"\"], \"@status\": [\"false-positive\", \"false-positive\", \"false-positive\", \"false-positive\", \"\"]}\n self.test_df = pd.DataFrame(self.test_json_data)\n\n def tearDown(self):\n if os.path.exists(self.test_csv_path):\n os.remove(self.test_csv_path)\n\n def test_btn_Labeler_clicked(self):\n self.form.btn_Labeler_clicked()\n pass\n\n def test_btn_Labeler_clicked_fail(self):\n self.form.convertXmlToCSV(\"Test.xml\")\n self.form.btn_Labeler_clicked(\"Test.csv\")\n pass\n\n def test_checkFileFormat(self):\n self.assertEqual(self.form.checkFileFormat(\"Test.xml\"), True)\n self.assertEqual(self.form.checkFileFormat(\"Test.csv\"), False)\n \n def test_load_csv_dataset_file_fail(self):\n csv_path = self.test_csv_path\n self.assertFalse(os.path.exists(csv_path))\n\n # Call the function under test\n self.form.loadDatasetFile(csv_path)\n\n #Check that the function correctly loads the csv file\n self.assertTrue(os.path.exists(csv_path))\n self.assertEqual(self.form.dataset_type, 'csv')\n self.assertTrue('Status' in self.form.df_dataset.columns)\n self.assertEqual(self.form.df_dataset['Status'].iloc[0], 'false-positive')\n self.assertEqual(self.form.df_dataset['Status'].iloc[1], 'escalated')\n self.assertEqual(self.form.df_dataset['Status'].iloc[2], 'escalated')\n self.assertEqual(len(self.form.cBox_Preset), 20)\n\n def test_save_csv_dataset_file_fail(self):\n csv_path = self.test_csv_path\n self.form.dataset_type = 'csv'\n self.form.df_dataset = self.test_df\n\n # Call the function under test\n self.form.loadDatasetFile(csv_path)\n\n # Check that the function correctly saves the csv file\n self.assertTrue(os.path.exists(csv_path))\n saved_data = pd.read_csv(self.test_csv_path)\n self.assertTrue('Status' in saved_data.columns)\n self.assertEqual(saved_data['Status'].iloc[1], 'escalated')\n self.assertEqual(saved_data['Status'].iloc[2], 'escalated')\n self.assertEqual(len(self.form.cBox_Preset), 20)\n \n def test_PMD(self):\n df = pd.DataFrame({\n 'ID': [1, 2, 3, 4],\n 'Priority': [2, 4, 3, 1]})\n # Check if 'Priority' column is present in the DataFrame\n assert 'Priority' in df.columns\n\n # Check if 'Status' column is not present in the DataFrame\n assert 'Status' not in df.columns\n\n def set_status_column_fail(df_dataset):\n # Helper function to apply the modifications to the @status column\n if not df_dataset.empty:\n if not df_dataset['@priority'].isna().all():\n df_dataset['@status'] = df_dataset['@priority']\n first_column = df_dataset.pop('@status')\n df_dataset.insert(0,'@status',first_column)\n df_dataset['@status'] = np.where(df_dataset['@status']>=\"3\",'escalated','false-positive')\n elif not df_dataset['@Fixable'].isna().all():\n df_dataset['@status'] = df_dataset['@Fixable']\n first_column = df_dataset.pop('@status')\n df_dataset.insert(0,'@status',first_column)\n df_dataset['@status'] = df_dataset[\"@status\"].replace(0,'false-positive')\n df_dataset['@status'] = df_dataset[\"@status\"].replace(1,'escalated')\n return df_dataset\n \n\n \nif __name__ == \"__main__\":\n unittest.main()","repo_name":"aanthir1/SER517-Fall23-Team4","sub_path":"gui/test_datasets.py","file_name":"test_datasets.py","file_ext":"py","file_size_in_byte":4098,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"17"} +{"seq_id":"33492525735","text":"import random\nimport pygame as pg\n\nclass Euler_cromer:\n def __init__(self, s, v, dt):\n self.s = s\n self.v = v\n self.dt = dt\n\n def acc(self, t = 0):\n return 0\n\n def calculate(self, t = 0):\n self.v = self.v + self.dt*self.acc(t)\n self.s = self.s + self.dt*self.v\n return self.s, self.v\n\nclass Gravity(Euler_cromer):\n def acc(self, t = 0):\n return 9.81\n\ndef draw_circle(x, y, surf):\n radius = 1\n pg.draw.circle(surf, (255,255,255,255), (x, y), radius)\n\n\ndef test():\n import viewscreen as vs\n width = 1920\n height = 1080\n dt = 0.01\n test = vs.Screen(width, height)\n x = Euler_cromer(1000, 10, dt)\n y = Gravity(1000, -100, dt)\n testrun = True\n surf = pg.display.get_surface()\n while testrun:\n pg.time.delay(1)\n draw_circle(int(x.s), int(y.s), surf)\n pg.display.flip()\n x.calculate()\n y.calculate()\n for event in pg.event.get():\n if event.type == pg.QUIT:\n test.close()\n testrun = False\n\nif __name__ == '__main__':\n test()\n","repo_name":"markuspettbor/Rockets","sub_path":"gravity.py","file_name":"gravity.py","file_ext":"py","file_size_in_byte":1107,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"17"} +{"seq_id":"40127924521","text":"from MVP4.centralisation_global import *\n\ndef note_assert_par_test(evaluation):\n nb_assert_par_test = evaluation[\"nombre moyen d'asserts par test\"]\n if nb_assert_par_test >= 3 :\n return 3\n return (nb_assert_par_test - 1) * 3/2\n\ndef note_long_nom_fonction(evaluation):\n longueur_moyenne_nom_fonctions = evaluation[\"moyenne longueur nom des fonctions\"]\n if longueur_moyenne_nom_fonctions >= 15 :\n return 1.5\n return longueur_moyenne_nom_fonctions * 0.1\n\ndef note_long_nom_variables(evaluation):\n long_moyenne_nom_variables = evaluation[\"nom des variables\"]\n if long_moyenne_nom_variables >= 8 :\n return 1\n return long_moyenne_nom_variables * 1/8\n\ndef aeration(evaluation) :\n pourcentage_aeration = evaluation[\"pourcentage d'aeration\"]\n if pourcentage_aeration >= 0.2 :\n return 1\n return pourcentage_aeration * 5\n\ndef plus_d_une_lettre(evaluation) :\n if evaluation[\"nom de variable trop court\"] :\n return 1\n\ndef note_candidat(fichier, fichier_test, autres_fichiers, autres_fichiers_test):\n '''\n :param fichier: fichier du candidat\n :param fichier_test: fichier contenant les tests du candidats\n :param autres_fichiers: liste contenant les autres fichiers de la base de données\n :param autres_fichiers_test: liste contenant les autres fichiers de test de la base de données\n :return: la note du candidat sur 20\n '''\n total = 17.5\n note = 0\n note += resultat_final(fichier, fichier_test, autres_fichiers, autres_fichiers_test)[1][\"rapport nombre de fonctions et nombre de commentaires\"] * 4\n note += resultat_final(fichier, fichier_test, autres_fichiers, autres_fichiers_test)[1][\"rapport nombre de fonctions et nombre de tests\"] * 2\n note += note_assert_par_test(resultat_final(fichier, fichier_test, autres_fichiers, autres_fichiers_test)[1])\n note += note_long_nom_fonction(resultat_final(fichier, fichier_test, autres_fichiers, autres_fichiers_test)[1])\n note += note_long_nom_variables(resultat_final(fichier, fichier_test, autres_fichiers,autres_fichiers_test)[1])\n note += aeration(resultat_final(fichier, fichier_test, autres_fichiers,autres_fichiers_test)[1])\n note += resultat_final(fichier, fichier_test, autres_fichiers, autres_fichiers_test)[1][\"nom de variable correcte\"]\n note += (1-resultat_final(fichier, fichier_test, autres_fichiers, autres_fichiers_test)[1][\"duplication probable\"] )* 4\n return(note / total * 20)\n\n\n","repo_name":"JulietteRietzler/CScodingweeks24team2","sub_path":"MVP4/note.py","file_name":"note.py","file_ext":"py","file_size_in_byte":2443,"program_lang":"python","lang":"fr","doc_type":"code","stars":1,"dataset":"github-code","pt":"17"} +{"seq_id":"25288195283","text":"import discord\nfrom discord.ext import commands, tasks\n\nimport datetime\nimport asyncio\nimport auth_token\nimport traceback\nimport sys\n\n\nclass Reddit(commands.Cog):\n \"\"\"Add or remove subreddits to announce new posts of\"\"\"\n\n def __init__(self, bot):\n self.bot = bot\n\n self.poll.start()\n\n def cog_unload(self):\n self.poll.cancel()\n\n @tasks.loop(seconds=10.0)\n async def poll(self):\n async with self.bot.pool.acquire() as db:\n # loop through all subreddits and check if a new post is up\n subreddits = await db.fetch(\"SELECT * FROM Subreddits\")\n for row in subreddits:\n parsingChannelUrl = f\"https://www.reddit.com/r/{row[1]}/new.json\"\n parsingChannelHeader = {\n 'cache-control': \"no-cache\", \"User-Agent\": auth_token.user_agent}\n parsingChannelQueryString = {\"sort\": \"new\", \"limit\": \"1\"}\n async with self.bot.session.get(parsingChannelUrl, headers=parsingChannelHeader,\n params=parsingChannelQueryString) as resp:\n if resp.status > 400:\n await asyncio.sleep(10)\n continue\n\n try:\n submissions_obj = await resp.json()\n except Exception as ex:\n print(await resp.text())\n print('Ignoring exception in Reddit.poll()',\n file=sys.stderr)\n traceback.print_exception(\n type(ex), ex, ex.__traceback__, file=sys.stderr)\n await asyncio.sleep(1)\n continue\n\n try:\n submission_data = submissions_obj[\"data\"][\"children\"][0][\"data\"]\n except Exception:\n await asyncio.sleep(1)\n continue\n\n # new post found\n if submission_data[\"id\"] != row[2] and submission_data[\"created_utc\"] > row[3]:\n\n # update last post data in database\n await db.execute(\"UPDATE Subreddits SET LastPostID=$1, LastPostTime=$2 WHERE ID=$3\",\n submission_data[\"id\"], submission_data[\"created_utc\"], row[0])\n\n # create message embed\n if len(submission_data[\"title\"]) > 256:\n title = submission_data[\"title\"][:256]\n else:\n title = submission_data[\"title\"]\n emb = discord.Embed(title=title,\n color=discord.Colour.dark_blue(),\n url=\"https://www.reddit.com\" + submission_data[\"permalink\"])\n emb.timestamp = datetime.datetime.utcnow()\n emb.set_author(name=submission_data[\"author\"])\n\n post_content = submission_data[\"selftext\"].replace(\"amp;\", \"\").replace(\n \"​\", \"\").replace(\"<\", \"<\").replace(\">\", \">\")\n # if post content is very big, trim it\n if len(submission_data[\"selftext\"]) > 1900:\n emb.description = post_content[:1900] + \\\n \"... `click title to continue`\"\n else:\n emb.description = post_content\n\n try:\n emb.set_image(\n url=submission_data[\"preview\"][\"images\"][0][\"variants\"][\"gif\"][\"source\"][\"url\"])\n except KeyError:\n try:\n if submission_data[\"thumbnail\"] not in [\"self\", \"default\", \"spoiler\", \"nsfw\"]:\n if submission_data[\"over_18\"]:\n emb.set_image(\n url=submission_data[\"preview\"][\"images\"][0][\"source\"][\"url\"])\n else:\n emb.set_image(\n url=submission_data[\"thumbnail\"])\n elif submission_data[\"over_18\"] and submission_data[\"domain\"] in [\"i.imgur.com\", \"imgur.com\", \"i.redd.it\", \"gfycat.com\"]:\n emb.set_image(url=submission_data[\"url\"])\n except KeyError:\n pass\n\n # send notification to every subscribed server\n channels = await db.fetch(\"SELECT Guilds.RedditNotifChannel, Guilds.ID \\\n FROM SubredditSubscriptions INNER JOIN Guilds \\\n ON SubredditSubscriptions.Guild=Guilds.ID \\\n WHERE Subreddit=$1\", row[0])\n\n for ch in channels:\n announceChannel = self.bot.get_channel(ch[0])\n if announceChannel is None:\n continue\n if submission_data[\"over_18\"] and not announceChannel.is_nsfw():\n try:\n emb.set_image(\n url=submission_data[\"preview\"][\"images\"][0][\"variants\"][\"nsfw\"][\"source\"][\"url\"].replace(\"amp;\", \"\"))\n except KeyError:\n emb.set_image(\n url=\"https://www.digitaltrends.com/wp-content/uploads/2012/11/reddit.jpeg\")\n emb.set_footer(\n text=\"This is an NSFW post, to uncensor posts, please mark the notification channel as NSFW\")\n try:\n await announceChannel.send(\"A new post in /r/\" + row[1] + \" !\", embed=emb)\n except AttributeError:\n guild = self.bot.get_guild(ch[1])\n if guild is None:\n await db.execute(\"DELETE FROM SubredditSubscriptions WHERE Subreddit=$1 AND Guild=$2\", ch[0], ch[1])\n except discord.errors.Forbidden:\n pass\n\n @poll.before_loop\n async def before_printer(self):\n await self.bot.wait_until_ready()\n\n # who and where the commands are permitted to use\n @commands.has_permissions(manage_messages=True)\n @commands.guild_only()\n @commands.group(aliases=[\"rd\"])\n async def reddit(self, ctx):\n \"\"\"(Un)Subscribe to subreddits to announce\"\"\"\n if ctx.invoked_subcommand is None:\n await ctx.send(\"You need to specify an action \\n(use 'help reddit' for more information)\")\n\n @reddit.command()\n async def setchannel(self, ctx, channel=None):\n \"\"\"Sets the channel to announce Reddit posts in\"\"\"\n # get channel obj, depending on if it was mentioned or just the name was specified\n if len(ctx.message.channel_mentions) > 0:\n channel_obj = ctx.message.channel_mentions[0]\n elif channel is not None:\n channel_obj = discord.utils.get(\n ctx.guild.channels, name=channel.replace(\"#\", \"\"))\n if channel_obj is None:\n await ctx.send(f\"No channel named {channel}\")\n return\n else:\n await ctx.send(\"Missing channel parameter\")\n return\n\n bot_member = ctx.guild.get_member(self.bot.user.id)\n permissions = channel_obj.permissions_for(bot_member)\n if not permissions.send_messages or not permissions.embed_links:\n await ctx.send(\"Command failed, please make sure that the bot has both permissions for sending messages and using embeds in the specified channel!\")\n return\n\n async with self.bot.pool.acquire() as db:\n # add channel id for the guild to the database\n await db.execute(\"UPDATE Guilds SET RedditNotifChannel=$1 WHERE ID=$2\",\n channel_obj.id, ctx.guild.id)\n\n await ctx.send(\"Successfully set Reddit notifications to \" + channel_obj.mention)\n\n @reddit.command(aliases=[\"sub\"])\n async def subscribe(self, ctx, *, subreddit=None):\n \"\"\"Subscribes to a subreddit\n\n Its new posts will be announced in the specified channel\"\"\"\n async with self.bot.pool.acquire() as db:\n # check if announcement channel is set up\n rows = await db.fetch(\"SELECT RedditNotifChannel FROM Guilds WHERE ID=$1\", ctx.guild.id)\n if len(rows) == 0 or rows[0][0] is None:\n await ctx.send(\"You need to set up a notifications channel before subscribing! \\nUse either ;setchannel or ;surrenderat20 setchannel\")\n return\n\n if subreddit is None:\n await ctx.send(\"You need to specify a subreddit to subscribe to\")\n return\n\n sr = subreddit.replace(\"/r/\", \"\").replace(\"r/\", \"\")\n\n # search for specified subreddit\n parsingChannelUrl = f\"https://www.reddit.com/subreddits/search.json?q={sr}&include_over_18=on\"\n parsingChannelHeader = {'cache-control': \"no-cache\"}\n parsingChannelQueryString = {\"limit\": \"1\"}\n async with self.bot.session.get(parsingChannelUrl, headers=parsingChannelHeader,\n params=parsingChannelQueryString) as resp:\n subreddits_obj = await resp.json()\n\n if len(subreddits_obj[\"data\"][\"children\"]) == 0:\n await ctx.send(f\"Could not find a subreddit called {sr}\")\n return\n\n subreddit_data = subreddits_obj[\"data\"][\"children\"][0][\"data\"]\n\n if subreddit_data[\"display_name\"].lower() != sr.lower():\n name = subreddit_data[\"display_name\"]\n await ctx.send(f\"Could not find subreddit called '{sr}'. \\nDo you maybe mean '{name}'?\")\n return\n\n announceChannel = self.bot.get_channel(rows[0][0])\n if subreddit_data[\"over18\"] and not announceChannel.is_nsfw():\n await ctx.send(\"This subreddit is NSFW, to subscribe you need to set the announcement channel to NSFW\")\n return\n\n # get last post data\n parsingChannelUrl = f\"https://www.reddit.com/r/{sr}/new.json\"\n parsingChannelHeader = {'cache-control': \"no-cache\"}\n parsingChannelQueryString = {\"sort\": \"new\", \"limit\": \"1\"}\n async with self.bot.session.get(parsingChannelUrl, headers=parsingChannelHeader,\n params=parsingChannelQueryString) as resp:\n submissions_obj = await resp.json()\n\n submission_data = submissions_obj[\"data\"][\"children\"][0][\"data\"]\n\n async with self.bot.pool.acquire() as db:\n # if subreddit is not yet in database, add it\n results = await db.fetch(\"SELECT 1 FROM Subreddits WHERE ID=$1\", submission_data[\"subreddit_id\"])\n if len(results) == 0:\n await db.execute(\"INSERT INTO Subreddits (ID, Name, LastPostID, LastPostTime) VALUES ($1, $2, $3, $4)\",\n submission_data[\"subreddit_id\"], submission_data[\"subreddit\"],\n submission_data[\"id\"], submission_data[\"created_utc\"])\n\n # add subscription to database\n results = await db.fetch(\"SELECT 1 FROM SubredditSubscriptions WHERE Subreddit=$1 AND Guild=$2\",\n submission_data[\"subreddit_id\"], ctx.guild.id)\n if len(results) == 0:\n await db.execute(\"INSERT INTO SubredditSubscriptions (Subreddit, Guild) VALUES ($1, $2)\",\n submission_data[\"subreddit_id\"], ctx.guild.id)\n else:\n await ctx.send(\"You are already subscribed to this Subreddit\")\n return\n\n # create message embed and send it\n emb = discord.Embed(title=\"Successfully subscribed to \" + submission_data[\"subreddit_name_prefixed\"],\n description=subreddit_data[\"public_description\"], color=discord.Colour.green())\n emb.set_thumbnail(url=subreddit_data[\"icon_img\"])\n emb.url = \"https://www.reddit.com\" + subreddit_data[\"url\"]\n\n await ctx.send(embed=emb)\n\n @reddit.command(aliases=[\"unsub\"])\n async def unsubscribe(self, ctx, *, subreddit=None):\n \"\"\"Unsubscripes from a subreddit\n\n New posts will no longer be announced\"\"\"\n if subreddit is None:\n await ctx.send(\"You need to spefify a subreddit to subscribe to\")\n return\n\n sr = subreddit.replace(\"/r/\", \"\").replace(\"r/\", \"\")\n\n # search subreddit\n parsingChannelUrl = f\"https://www.reddit.com/subreddits/search.json?q={sr}&include_over_18=on\"\n parsingChannelHeader = {'cache-control': \"no-cache\"}\n parsingChannelQueryString = {\"limit\": \"1\"}\n async with self.bot.session.get(parsingChannelUrl, headers=parsingChannelHeader,\n params=parsingChannelQueryString) as resp:\n subreddits_obj = await resp.json()\n\n if len(subreddits_obj[\"data\"][\"children\"]) == 0:\n await ctx.send(f\"Could not find a subreddit called {sr}\")\n return\n\n subreddit_data = subreddits_obj[\"data\"][\"children\"][0][\"data\"]\n\n if subreddit_data[\"display_name\"].lower() != sr.lower():\n name = subreddit_data[\"display_name\"]\n await ctx.send(f\"Could not find subreddit called '{sr}'. \\nDo you maybe mean '{name}'?\")\n return\n\n # get latest post data\n parsingChannelUrl = f\"https://www.reddit.com/r/{sr}/new.json\"\n parsingChannelHeader = {'cache-control': \"no-cache\"}\n parsingChannelQueryString = {\"sort\": \"new\", \"limit\": \"1\"}\n async with self.bot.session.get(parsingChannelUrl, headers=parsingChannelHeader,\n params=parsingChannelQueryString) as resp:\n submissions_obj = await resp.json()\n\n submission_data = submissions_obj[\"data\"][\"children\"][0][\"data\"]\n\n async with self.bot.pool.acquire() as db:\n # remove subscription from database\n results = await db.fetch(\"SELECT 1 FROM SubredditSubscriptions WHERE Subreddit=$1 AND Guild=$2\",\n submission_data[\"subreddit_id\"], ctx.guild.id)\n if len(results) == 1:\n await db.execute(\"DELETE FROM SubredditSubscriptions WHERE Subreddit=$1 AND Guild=$2\",\n submission_data[\"subreddit_id\"], ctx.guild.id)\n else:\n await ctx.send(\"You are not subscribed to this Subreddit\")\n return\n\n # remove subreddit from database if no server is subscribed to it anymore\n results = await db.fetch(\"SELECT 1 FROM SubredditSubscriptions WHERE Subreddit=$1\", submission_data[\"subreddit_id\"])\n if len(results) == 0:\n await db.execute(\"DELETE FROM Subreddits WHERE ID=$1\", submission_data[\"subreddit_id\"])\n\n # create message embed and send it\n emb = discord.Embed(title=\"Successfully unsubscribed from \" + submission_data[\"subreddit_name_prefixed\"],\n description=subreddit_data[\"public_description\"], color=discord.Colour.dark_red())\n emb.set_thumbnail(url=subreddit_data[\"icon_img\"])\n emb.url = \"https://www.reddit.com\" + subreddit_data[\"url\"]\n\n await ctx.send(embed=emb)\n\n @reddit.command(name=\"list\")\n async def _list(self, ctx):\n \"\"\"Displays a list of all subscribed subreddits\"\"\"\n names = \"\"\n async with self.bot.pool.acquire() as db:\n # get all subreddits the server is subscribed to\n cursor = await db.fetch(\"SELECT Subreddits.Name \\\n FROM SubredditSubscriptions INNER JOIN Subreddits \\\n ON SubredditSubscriptions.Subreddit=Subreddits.ID \\\n WHERE Guild=$1\", ctx.guild.id)\n\n for row in cursor:\n names = names + row[0] + \"\\n\"\n\n # create message embed and send it\n emb = discord.Embed(title=\"Subreddit subscriptions\",\n color=discord.Colour.dark_blue(), description=names)\n await ctx.send(embed=emb)\n\n\ndef setup(bot):\n bot.add_cog(Reddit(bot))\n","repo_name":"AtomToast/Voice-of-Light","sub_path":"ext/reddit.py","file_name":"reddit.py","file_ext":"py","file_size_in_byte":16442,"program_lang":"python","lang":"en","doc_type":"code","stars":14,"dataset":"github-code","pt":"17"} +{"seq_id":"73189686105","text":"# -*- coding: utf-8 -*-\nimport scrapy\nfrom scrapy.linkextractors import LinkExtractor\nfrom scrapy.spiders import CrawlSpider, Rule\nfrom scrapySpider.items import MeiziItem\nfrom scrapy.loader import ItemLoader\nfrom scrapySpider.utils.common import get_browser\nfrom scrapySpider.pipelines import MongoPipeline\n\n\nclass MeiziSpider(CrawlSpider):\n name = 'meizi'\n allowed_domains = ['www.mzitu.com']\n start_urls = ['https://www.mzitu.com/']\n cookie_dict = {}\n\n rules = (\n Rule(\n LinkExtractor(allow=r'\\d+|\\d+/\\d+', deny=r'zipai/.*/'),\n callback='parse_item',\n follow=True),\n Rule(LinkExtractor(allow=r'.+'), follow=True),\n )\n\n def parse_item(self, response):\n coll = MongoPipeline()\n img_url = response.css('.main-image p a img::attr(src)').extract()\n res = coll.find_one('img_url', img_url)\n if not res:\n item_loader = ItemLoader(item=MeiziItem(), response=response)\n item_loader.add_value('img_url', img_url)\n item_loader.add_css('title', '.main-title::text')\n item_loader.add_value('url', response.url)\n item_loader.add_value('file_path', '')\n return item_loader.load_item()\n\n def parse_start_url(self, response):\n if not self.cookie_dict:\n brower = get_browser()\n brower.get('https://www.mzitu.com')\n cookies = brower.get_cookies()\n for cookie in cookies:\n self.cookie_dict[cookie['name']] = cookie['value']\n yield scrapy.Request(\n self.start_urls[0], dont_filter=True, cookies=self.cookie_dict)\n","repo_name":"yitengcheng/meizi","sub_path":"scrapySpider/spiders/meizi.py","file_name":"meizi.py","file_ext":"py","file_size_in_byte":1644,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"17"} +{"seq_id":"24570508667","text":"#!/usr/bin/env python3\n# -*- coding: utf-8 -*-\n# (c) Shrimadhav U K | gautamajay52 | Amirul Andalib\n\nimport asyncio\nimport logging\nimport os\nimport time\nfrom collections import defaultdict\nfrom logging.handlers import RotatingFileHandler\nfrom sys import exit\nimport urllib.request\nimport dotenv\nimport telegram.ext as tg\n\nfrom pyrogram import Client\n\nif os.path.exists(\"TorrentLeech-Gdrive.txt\"):\n with open(\"Torrentleech-Gdrive.txt\", \"r+\") as f_d:\n f_d.truncate(0)\n\n# the logging things\nlogging.basicConfig(\n level=logging.INFO,\n format=\"%(asctime)s - %(levelname)s - %(message)s [%(filename)s:%(lineno)d]\",\n datefmt=\"%d-%b-%y %H:%M:%S\",\n handlers=[\n RotatingFileHandler(\n \"Torrentleech-Gdrive.txt\", maxBytes=50000000, backupCount=10\n ),\n logging.StreamHandler(),\n ],\n)\nlogging.getLogger(\"pyrogram\").setLevel(logging.ERROR)\nlogging.getLogger(\"urllib3\").setLevel(logging.WARNING)\nlogging.getLogger(\"PIL\").setLevel(logging.WARNING)\n\nLOGGER = logging.getLogger(__name__)\n\nuser_specific_config=dict()\n\ndotenv.load_dotenv(\"config.env\")\n\n# checking compulsory variable\nfor imp in [\"TG_BOT_TOKEN\", \"APP_ID\", \"API_HASH\", \"OWNER_ID\", \"AUTH_CHANNEL\"]:\n try:\n value = os.environ[imp]\n if not value:\n raise KeyError\n except KeyError:\n LOGGER.critical(f\"Oh...{imp} is missing from config.env ... fill that\")\n exit()\n\n# The Telegram API things\nTG_BOT_TOKEN = os.environ.get(\"TG_BOT_TOKEN\", \"\")\n# Get these values from my.telegram.org\nAPP_ID = int(os.environ.get(\"APP_ID\", 12345))\nAPI_HASH = os.environ.get(\"API_HASH\")\n\nOWNER_ID = int(os.environ.get(\"OWNER_ID\", 539295917))\n\n# to store the channel ID where bot is authorized\nAUTH_CHANNEL = [int(x) for x in os.environ.get(\"AUTH_CHANNEL\", \"539295917\").split(' ')]\n# Cuz most ppl dunno AUTH_CHANNEL also works as SUDO\nSUDO_USERS = [int(s) for s in os.environ.get('SUDO_USERS', '').split()]\nAUTH_CHANNEL.append(OWNER_ID)\nAUTH_CHANNEL += SUDO_USERS\n\n# set timeout for subprocess\nPROCESS_MAX_TIMEOUT = 3600\nSP_LIT_ALGO_RITH_M = os.environ.get(\"SP_LIT_ALGO_RITH_M\", \"hjs\")\n# add offensive API\nTG_OFFENSIVE_API = os.environ.get(\"TG_OFFENSIVE_API\", None)\nINDEX_LINK = os.environ.get(\"INDEX_LINK\", \"\")\n#################### Rclone vars ##########################\nRCLONE_CONFIG = os.environ.get(\"RCLONE_CONFIG\", \"\")\nDESTINATION_FOLDER = os.environ.get(\"DESTINATION_FOLDER\", \"TorrentLeechX\")\n\n#################### Telegram Settings ####################\nMAX_FILE_SIZE = 50000000 # Maximum file size to download from direct links/torrents\nFREE_USER_MAX_FILE_SIZE = 50000000\nTG_MAX_FILE_SIZE = 2097152000 # Telegram maximum file upload size\nMAX_TG_SPLIT_FILE_SIZE = int(os.environ.get(\"MAX_TG_SPLIT_FILE_SIZE\", 1072864000))\nMAX_MESSAGE_LENGTH = 4096 # maximum message length in Telegram\n# add config vars for the display progress\nFINISHED_PROGRESS_STR = os.environ.get(\"FINISHED_PROGRESS_STR\", \"█\")\nUN_FINISHED_PROGRESS_STR = os.environ.get(\"UN_FINISHED_PROGRESS_STR\", \"░\")\n# default thumbnail to be used in the videos\nDEF_THUMB_NAIL_VID_S = os.environ.get(\"DEF_THUMB_NAIL_VID_S\", \"https://via.placeholder.com/90.jpg\")\nEDIT_SLEEP_TIME_OUT = int(os.environ.get(\"EDIT_SLEEP_TIME_OUT\", 15))\nCUSTOM_FILE_NAME = os.environ.get(\"CUSTOM_FILE_NAME\", \"\") \nUPLOAD_AS_DOC = os.environ.get(\"UPLOAD_AS_DOC\", \"False\")\nCUSTOM_FILE_CAPTION = os.environ.get('CUSTOM_FILE_CAPTION', '{file_name}')\n\n################ Torrent/Aria2 Settings ################\nMAX_TIME_TO_WAIT_FOR_TORRENTS_TO_START = int(os.environ.get(\"MAX_TIME_TO_WAIT_FOR_TORRENTS_TO_START\", 600))\n# the download location, where the HTTP Server runs\nDOWNLOAD_LOCATION = \"./DOWNLOADS\"\n# chunk size that should be used with requests\nCHUNK_SIZE = int(os.environ.get(\"CHUNK_SIZE\", 128))\nARIA_TWO_STARTED_PORT = int(os.environ.get(\"ARIA_TWO_STARTED_PORT\", 6800))\n\n#################### COMMANDS ####################\nLEECH_COMMAND = os.environ.get(\"LEECH_COMMAND\", \"leech\")\nLEECH_UNZIP_COMMAND = os.environ.get(\"LEECH_UNZIP_COMMAND\", \"extract\")\nLEECH_ZIP_COMMAND = os.environ.get(\"LEECH_ZIP_COMMAND\", \"archive\")\nGLEECH_COMMAND = os.environ.get(\"GLEECH_COMMAND\", \"gleech\")\nGLEECH_UNZIP_COMMAND = os.environ.get(\"GLEECH_UNZIP_COMMAND\", \"gextract\")\nGLEECH_ZIP_COMMAND = os.environ.get(\"GLEECH_ZIP_COMMAND\", \"garchive\")\nYTDL_COMMAND = os.environ.get(\"YTDL_COMMAND\", \"ytdl\")\nGYTDL_COMMAND = os.environ.get(\"GYTDL_COMMAND\", \"gytdl\")\nTELEGRAM_LEECH_COMMAND = os.environ.get(\"TELEGRAM_LEECH_COMMAND\", \"tleech\")\nTELEGRAM_LEECH_UNZIP_COMMAND = os.environ.get(\"TELEGRAM_LEECH_UNZIP_COMMAND\", \"tleechextract\")\nCANCEL_COMMAND_G = os.environ.get(\"CANCEL_COMMAND_G\", \"cancel\")\nGET_SIZE_G = os.environ.get(\"GET_SIZE_G\", \"getsize\")\nSTATUS_COMMAND = os.environ.get(\"STATUS_COMMAND\", \"status\")\nSAVE_THUMBNAIL = os.environ.get(\"SAVE_THUMBNAIL\", \"savethumb\")\nCLEAR_THUMBNAIL = os.environ.get(\"CLEAR_THUMBNAIL\", \"clearthumb\")\nPYTDL_COMMAND = os.environ.get(\"PYTDL_COMMAND\", \"pytdl\")\nGPYTDL_COMMAND = os.environ.get(\"GPYTDL_COMMAND\", \"gpytdl\")\nLOG_COMMAND = os.environ.get(\"LOG_COMMAND\", \"log\")\nCLONE_COMMAND_G = os.environ.get(\"CLONE_COMMAND_G\", \"gclone\")\nUPLOAD_COMMAND = os.environ.get(\"UPLOAD_COMMAND\", \"upload\")\nRENEWME_COMMAND = os.environ.get(\"RENEWME_COMMAND\", \"renewme\")\nRENAME_COMMAND = os.environ.get(\"RENAME_COMMAND\", \"rename\")\nTOGGLE_VID = os.environ.get(\"TOGGLE_VID\", \"togglevid\")\nTOGGLE_DOC = os.environ.get(\"TOGGLE_DOC\", \"toggledoc\")\nRCLONE_COMMAND = os.environ.get(\"RCLONE_COMMAND\", \"rclone\")\nHELP_COMMAND = os.environ.get(\"HELP_COMMAND\", \"help\")\nSPEEDTEST = os.environ.get(\"SPEEDTEST\", \"speedtest\")\nTSEARCH_COMMAND = os.environ.get(\"TSEARCH_COMMAND\", \"tshelp\")\nMEDIAINFO_COMMAND = os.environ.get(\"MEDIAINFO_COMMAND\", \"mediainfo\")\nTG_DL_COMMAND = os.environ.get(\"TG_DL_COMMAND\", \"tgdl\")\nMANNUAL_GUP_COMMAND = os.environ.get(\"MANNUAL_GUP_COMMAND\", \"gupload\") \n################################################\n\nBOT_START_TIME = time.time()\n\n########## GDTOT/APPDRIVE VARS ##########\nAPPDRIVE_EMAIL = os.environ.get('APPDRIVE_EMAIL')\nAPPDRIVE_PASS = os.environ.get('APPDRIVE_PASS')\nAPPDRIVE_SHARED_DRIVE_ID = os.environ.get('APPDRIVE_SHARED_DRIVE_ID')\nAPPDRIVE_FOLDER_ID = os.environ.get('APPDRIVE_FOLDER_ID')\nGDTOT_CRYPT = os.environ.get('GDTOT_CRYPT')\n\nga_vars_list = ['APPDRIVE_EMAIL', 'APPDRIVE_PASS', 'GDTOT_CRYPT', 'APPDRIVE_SHARED_DRIVE_ID', 'APPDRIVE_FOLDER_ID' ]\n\nfor i in ga_vars_list:\n try:\n value = os.environ[i]\n if not value:\n raise KeyError\n except KeyError:\n LOGGER.warning(f\"{i} is not provided!! The respective gdtot/appdrive bypass will not work!!!\")\n#########################################\n\n# dict to control uploading and downloading\ngDict = defaultdict(lambda: [])\n# user settings dict #ToDo\nuser_settings = defaultdict(lambda: {})\ngid_dict = defaultdict(lambda: [])\n_lock = asyncio.Lock()\n\n# Rclone Config Via any raw url\n###########################################################################\ntry: #\n RCLONE_CONF_URL = os.environ.get('RCLONE_CONF_URL', \"\") #\n if len(RCLONE_CONF_URL) == 0: #\n RCLONE_CONF_URL = None #\n else: #\n urllib.request.urlretrieve(RCLONE_CONF_URL, '/app/rclone.conf') #\nexcept KeyError: #\n RCLONE_CONF_URL = None #\n###########################################################################\n\ndef multi_rclone_init():\n if RCLONE_CONFIG:\n LOGGER.warning(\"Don't use this var now, put your rclone.conf in root directory\")\n if not os.path.exists(\"rclone.conf\"):\n LOGGER.warning(\"Sed, No rclone.conf found in root directory\")\n return\n if not os.path.exists(\"rclone_bak.conf\"): # backup rclone.conf file\n with open(\"rclone_bak.conf\", \"w+\", newline=\"\\n\", encoding=\"utf-8\") as fole:\n with open(\"rclone.conf\", \"r\") as f:\n fole.write(f.read())\n LOGGER.info(\"rclone.conf backuped to rclone_bak.conf!\")\n\n\nmulti_rclone_init()\n\napp = Client(\"LeechBot\", bot_token=TG_BOT_TOKEN, api_id=APP_ID, api_hash=API_HASH, workers=343)\n\nupdater = tg.Updater(token=TG_BOT_TOKEN)\nbot = updater.bot\ndispatcher = updater.dispatcher\n","repo_name":"KangersHub/TorrentLeechX","sub_path":"tobrot/__init__.py","file_name":"__init__.py","file_ext":"py","file_size_in_byte":8397,"program_lang":"python","lang":"en","doc_type":"code","stars":204,"dataset":"github-code","pt":"17"} +{"seq_id":"7731100513","text":"#!/usr/bin/env python3\n\nimport asyncio\nfrom pathlib import Path\nimport urllib.parse\n\nfrom aiohttp import web\n\nimport game\n\n\npublic_dir = (Path(__file__) / '../../public').resolve()\n\n\nasync def initialize_handler(request):\n game.initialize()\n return web.HTTPNoContent()\n\n\nasync def index_handler(request):\n return web.FileResponse(public_dir / 'index.html')\n\n\nasync def room_handler(request):\n room_name = request.match_info.get('room_name', '')\n res = {\"host\": \"\", \"path\": \"/ws/\" + urllib.parse.quote(room_name)}\n return web.json_response(res)\n\n\nasync def game_handler(request):\n room_name = request.match_info.get(\"room_name\", \"\")\n ws = web.WebSocketResponse()\n await ws.prepare(request)\n await game.serve(ws, room_name)\n return ws\n\n\ndef main():\n app = web.Application()\n app.router.add_get(\"/initialize\", initialize_handler)\n app.router.add_get(\"/room/{room_name}\", room_handler)\n app.router.add_get(\"/room/\", room_handler)\n app.router.add_get(\"/ws/{room_name}\", game_handler)\n app.router.add_get(\"/ws/\", game_handler)\n app.router.add_get('/', index_handler)\n app.router.add_static('/', path=public_dir, name=\"static\")\n web.run_app(app, host='0.0.0.0', port=5000)\n\n\nif __name__ == '__main__':\n main()\n","repo_name":"isucon/isucon7-final","sub_path":"webapp/python/app.py","file_name":"app.py","file_ext":"py","file_size_in_byte":1266,"program_lang":"python","lang":"en","doc_type":"code","stars":25,"dataset":"github-code","pt":"17"} +{"seq_id":"6350124451","text":"\n# coding: utf-8\n\n# In[10]:\n\n\nimport os\nimport sys\nimport pandas as pd\nimport numpy as np\nimport matplotlib\nimport matplotlib.pylab\nimport matplotlib.pyplot as plt\nsys.path.append('/project/bioinformatics/DLLab/Alex/Projects/utilities/')\nimport network_functions as nf\nimport re\nimport math\n#from machine_learning_stats import metrics_from_confusion_matrix\n#import tensorflow_utilities\nimport seaborn as sns\nfrom sklearn.neighbors import KernelDensity\nimport scipy.stats\nfrom scipy import stats\nfrom matplotlib.colors import ListedColormap\nfrom mpl_toolkits.mplot3d import axes3d\nimport matplotlib.pyplot as plt\nfrom matplotlib import cm\nimport itertools\nimport seaborn as sns\nimport pickle as pkl\nimport numpy as np\nfrom BioMarkerIdentification import fLoadModels\nfrom IMPAC_DenseNetwork import read_config_file\n\ndef fCountHidden(config=None, iModel=None):\n if config == None:\n config = nf.read_config_file('IniFiles/Dense_{0:02d}.ini'.format(iModel))\n intHidden = [xi for xi in config.keys() if 'dense' in xi.lower()].__len__()\n return intHidden\n\ndef fDropout(config=None, iModel=None):\n if config == None:\n config = nf.read_config_file('IniFiles/Dense_{0:02d}.ini'.format(iModel))\n flDropout = float(config['layer/Dropout0']['rate'])\n return (flDropout)\n\ndef fBottomLayerSizeLog2(config=None, iModel=None):\n if config == None:\n config = nf.read_config_file('IniFiles/Dense_{0:02d}.ini'.format(iModel))\n intLayerSize = int(config['layer/input']['units'])\n\n return (math.log(intLayerSize, 2.0))\n\ndef fRegularization(config=None, iModel=None):\n if config == None:\n config = nf.read_config_file('IniFiles/Dense_{0:02d}.ini'.format(iModel))\n flRegularization = float(config['layer/input']['regularizer'])\n return (flRegularization)\n\ndef plt2DKDEs(dfModelMetrics, lComparison, flPercent):\n topModels = dfModelMetrics.head(int(dfModelMetrics.shape[0] * (flPercent / 100.)))\n bottomModels = dfModelMetrics.tail(int(dfModelMetrics.shape[0] * (flPercent / 100.)))\n\n Zdata = [np.array(topModels[lComparison]), np.array(bottomModels[lComparison])]\n xmin = np.min([Zi[:, 0].min() for Zi in Zdata]) * .8\n xmax = np.max([Zi[:, 0].max() for Zi in Zdata]) * 1.2\n ymin = np.min([Zi[:, 1].min() for Zi in Zdata]) * .8\n ymax = np.max([Zi[:, 1].max() for Zi in Zdata]) * 1.2\n X, Y = np.mgrid[xmin:xmax:100j,\n ymin:ymax:100j]\n kdes = [KernelDensity(kernel='gaussian', bandwidth=1).fit(Zi) for Zi in Zdata]\n Z = [np.exp(kde.score_samples(np.dstack([X.flatten(), Y.flatten()])[0]).reshape(*X.shape)) for kde in kdes]\n\n fPlot2DDist(X, Y, Z, ['Blue', 'Orange'], ['Blues', 'Oranges'], ' vs '.join(lComparison), lComparison[0],\n lComparison[1])\n\ndef fPlot2DDist(X, Y, Zs, colors, cmaps, title, xlabel, ylabel):\n fig = plt.figure(figsize=(10,6))\n #plt.suptitle(title)\n ax = fig.add_subplot(1,1,1,projection='3d')\n\n# ax1 = fig.add_subplot(2,2,1,projection='3d')\n# ax2 = fig.add_subplot(2,2,2,projection='3d')\n# ax3 = fig.add_subplot(2,2,3,projection='3d')\n# ax4 = fig.add_subplot(2,2,4,projection='3d')\n# for ax in [ax1,ax2,ax3,ax4]:\n# ax.view_init(30, 30)\n# ax.set_ylabel(ylabel)\n# ax.set_xlabel(xlabel)\n ax.view_init(30, 30)\n ax.set_ylabel(ylabel)\n ax.set_xlabel(xlabel)\n flMin = np.amin(Zs)\n flMax = np.amax(Zs)\n flMid = (flMin + flMax) / 2\n ax.set_zticks([flMin, flMid, flMax])#, ['Low', 'Med', 'High'])\n # ax.set_zticklabels(['Low', 'Med', 'High'])\n\n fig.tight_layout()\n\n for Zi, Ci, CMi in zip(Zs, colors, cmaps):\n ax.contour3D(X, Y, Zi, 30, cmap=CMi)\n cset = ax.contour(X, Y, Zi, zdir='x', offset=X.min(), cmap=CMi)\n cset = ax.contour(X, Y, Zi, zdir='y', offset=Y.min(), cmap=CMi)\n ax.set_zticks([flMin, flMid, flMax])#, ['Low', 'Med', 'High'])\n #ax.set_zticklabels(['Low', 'Med', 'High'])\n\n ax.set_zticks([flMin, flMid, flMax])#, ['Low', 'Med', 'High'])\n #ax.set_zticklabels(['Low', 'Med', 'High'])\n ax.set_zlabel('Density')\n ax.view_init(elev=30, azim=30)\n plt.show()\n\ndef fFetchList(sType, sModality='combined', sAtlas='basc122'):\n if sType=='LSTM' or sType=='Dense':\n # initialize dataframe\n pdPerformance=pd.DataFrame(index=range(50), columns=['Performance','Hidden Layers',\n r'$log_{2}(First Layer Size)$',\n 'Dropout Fraction','Regularization'])\n # load results and parameters for each model\n for i in range(50):\n sIniLoc='/project/bioinformatics/DLLab/Cooper/Code/AutismProject/' \\\n f'Parallelization/IniFiles/{sType}_{i:02}.ini'\n lsPerf=[]\n\n # Take average of performance across cross validation folds\n for iCV in range(1,4):\n sPerfLoc='/project/bioinformatics/DLLab/Cooper/Code/AutismProject/' \\\n f'Parallelization/TrainedModels/ISBIRerun/{sType}/'\\\n f'{sType}_{i:02}{sModality}{sAtlas}ROCScoreCrossVal{iCV}.p'\n lsPerf.append(pkl.load(open(sPerfLoc, 'rb')))\n flPerf=np.mean(lsPerf)\n\n # put in pd dataframe\n pdPerformance.loc[i, 'Performance']=flPerf\n\n config = read_config_file(sIniLoc)\n pdPerformance.loc[i,r'$log_{2}$(First Layer Size)']=math.log(int(config['layer/input']['units']),2)\n pdPerformance.loc[i,'Hidden Layers']=len([x for x in config if x.__contains__(f'layer/{sType}')])\n pdPerformance.loc[i,'Dropout Fraction']=float(config['layer/Dropout0']['rate'])\n pdPerformance.loc[i,'Regularization']=float(config['layer/input']['regularizer'])\n pdPerformance=pdPerformance.sort_values(by=['Performance'], ascending=False)\n\n return pdPerformance, ['Hidden Layers',r'$log_{2}$(First Layer Size)',\n 'Dropout Fraction','Regularization']\n\n else:\n cModel=fLoadModels(sType, sModality, sAtlas)[0]\n # TODO only works for Logistic Regression for now\n pdPerformance=pd.DataFrame(index=range(50), columns=['Performance','Maximum Iterations (x10,000)', r'$log_{10}(\\alpha)$'])\n for i in range(50):\n pdPerformance.loc[i,'Performance']=cModel.grid_scores_[i].mean_validation_score\n pdPerformance.loc[i,'Maximum Iterations (x10,000)']=cModel.grid_scores_[i].parameters['max_iter']/10000\n pdPerformance.loc[i,r'$log_{10}(\\alpha)$']=math.log(cModel.grid_scores_[i].parameters['alpha'],10)\n pdPerformance=pdPerformance.sort_values(by=['Performance'], ascending=False)\n\n return pdPerformance, ['Maximum Iterations (x10,000)', r'$log_{10}(\\alpha)$']\n\n\nif __name__=='__main__':\n lsAtlases=['basc064', 'basc122', 'basc197']\n for sAtlas in lsAtlases:\n sModality='combined'\n pdPerformance, lToTest = fFetchList('Dense', sModality='combined', sAtlas=sAtlas)\n plt.style.use('seaborn')\n for lComparison in itertools.combinations(lToTest, 2):\n plt2DKDEs(pdPerformance, list(lComparison), 15)\n plt.savefig(\n '/project/bioinformatics/DLLab/Cooper/Code/AutismProject/Parallelization/KDEs/{}{}{}vs{}.png'\\\n .format(sModality, sAtlas, lComparison[0].replace(\"\\'\", \"\").replace(\" \",\"\"), lComparison[1].replace(\n \"\\'\", \"\").replace(\" \",\"\")))\n","repo_name":"DeepLearningForPrecisionHealthLab/ConsistentASDCorrelates","sub_path":"KDEVisualization.py","file_name":"KDEVisualization.py","file_ext":"py","file_size_in_byte":7467,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"17"} +{"seq_id":"34999668253","text":"\"\"\" JWT module \"\"\"\n\nimport os\nimport sys\nfrom datetime import datetime, timedelta\nfrom uuid import uuid4\n\nimport jwt\n\nDEFAULT_SECRET_KEY = 'secret'\nDEFAULT_ACCESS_TOKEN_LIFETIME = '1'\nDEFAULT_FESRESH_TOKEN_LIFETIME = '60'\n\n# Define the environment variables when the tornado/testing.py is called.\nif sys.argv[0].split('/')[-1] == 'testing.py':\n os.environ['ACCESS_TOKEN_LIFETIME'] = '0.5'\n os.environ['REFRESH_TOKEN_LIFETIME'] = '1'\n os.environ['SECRET_KEY'] = DEFAULT_SECRET_KEY\n\n\nclass ExpiredTokenException(Exception):\n \"\"\"Exception raised when token is expired. \"\"\"\n\nclass InvalidTokenException(Exception):\n \"\"\"Exception raised when token is not valid. \"\"\"\n\nclass Token():\n \"\"\"Abstract class for the token instance. \"\"\"\n\n token_type = None\n lifetime = None\n\n def __init__(self, token=None):\n self.token = token\n self.current_time = datetime.now()\n\n self.secret = os.getenv('SECRET_KEY', DEFAULT_SECRET_KEY)\n if token is not None:\n self.decode(token)\n else:\n self.payload = {'token-type': self.token_type}\n self.payload['jti'] = uuid4().hex\n self.payload['exp'] = self.current_time + timedelta(\n minutes=float(self.lifetime))\n\n def decode(self, token):\n \"\"\"Decodes the given token. \"\"\"\n\n try:\n self.payload = jwt.decode(token, self.secret, algorithms='HS256')\n except jwt.ExpiredSignatureError:\n raise ExpiredTokenException\n\n except (jwt.InvalidSignatureError, jwt.DecodeError):\n raise InvalidTokenException\n\n exp_datetime = datetime.utcfromtimestamp(self.payload['exp'])\n\n if exp_datetime < self.current_time:\n raise ExpiredTokenException\n\n @classmethod\n def for_user(cls, user_id):\n \"\"\"\n Returns an authorization token for the given user that will be provided\n after authenticating the user's credentials.\n \"\"\"\n\n token = cls()\n token.payload['user_id'] = user_id\n\n return token\n\n def __str__(self):\n token = jwt.encode(self.payload, self.secret, algorithm='HS256')\n return token.decode('utf-8')\n\n\nclass AccessToken(Token):\n \"\"\"Class implementing access token instance. \"\"\"\n\n token_type = 'access'\n lifetime = os.getenv('ACCESS_TOKEN_LIFETIME', DEFAULT_ACCESS_TOKEN_LIFETIME)\n\n\nclass RefreshToken(Token):\n \"\"\"Class implementing refresh token instance. \"\"\"\n\n token_type = 'refresh'\n lifetime = os.getenv('REFRESH_TOKEN_LIFETIME', DEFAULT_FESRESH_TOKEN_LIFETIME)\n no_copy_claims = ('token-type', 'exp', 'jti')\n\n def access_token(self):\n \"\"\"\n Returns an access token created from this refresh token.\n \"\"\"\n access = AccessToken()\n\n access.payload['exp'] = self.current_time + timedelta(\n minutes=float(access.lifetime))\n\n no_copy = self.no_copy_claims\n for claim, value in self.payload.items():\n if claim in no_copy:\n continue\n access.payload[claim] = value\n\n return access\n","repo_name":"tolstoyevsky/hubot-huntflow-reloaded","sub_path":"server/huntflow_reloaded/tokens.py","file_name":"tokens.py","file_ext":"py","file_size_in_byte":3084,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"17"} +{"seq_id":"7472984164","text":"import cgi\nfrom google.appengine.ext import webapp, db\nfrom google.appengine.ext.webapp import util, template\nfrom google.appengine.api import urlfetch, memcache, users, mail\n\nimport logging, urllib, os\nfrom datetime import datetime, timedelta\n\nfrom models import Issue, Choice, Vote\n\n\nclass MainPage(webapp.RequestHandler):\n\tdef get(self):\n\t\tuser = users.get_current_user()\n\t\tif user:\n\t\t\tlogout_url = users.create_logout_url('/')\n\t\telse:\n\t\t\tlogin_url = users.create_login_url('/')\n\t\tissues = Issue.all().order('creation_date').fetch(30)\n\t\tsuccess_type = self.request.get('success')\n\t\tsuccess_msg = None\n\t\tif success_type == 'vote':\n\t\t\tsuccess_msg = 'Your vote was successfully cast!'\n\t\tif success_type == 'updated':\n\t\t\tsuccess_msg = 'Your vote was successfully updated!'\n\t\tcreated_by = Issue.issues_created_by(member=user,limit=20)\n\t\tvoted_on = Issue.issues_voted_on(member=user,limit=20)\n\t\t#recent_results = [issue for issue in voted_on if issue.has_results]\n\t\trecent_voted = [issue for issue in voted_on if issue.is_active()]\n\t\trecent_results = Issue.recent_results(limit=20)\n\t\tself.response.out.write(template.render('templates/overview.html', locals()))\n\t\t\n\t\t\n\t\t\nclass NewHandler(webapp.RequestHandler):\n\tdef get(self):\n\t\tuser = users.get_current_user()\n\t\tif user:\n\t\t\tlogout_url = users.create_logout_url('/')\n\t\telse:\n\t\t\tself.redirect(users.create_login_url(self.request.uri))\n\t\t\treturn\n\t\toption_one = \"Yes\"\n\t\toption_two = \"No\"\n\t\tself.response.out.write(template.render('templates/new.html', locals()))\n\n\tdef post(self):\n\t\tuser = users.get_current_user()\n\t\tif not user:\n\t\t\tself.redirect(users.create_login_url(self.request.uri))\n\t\t\treturn\n\t\t\n\t\tduration_amount = int(self.request.get('duration_amount'))\n\t\tmultiplier = int(self.request.get('duration_multiplier'))\n\t\tissue = Issue(\n\t\t\ttitle = cgi.escape(self.request.get('title')),\n\t\t\tdescription = cgi.escape(self.request.get('description')),\n\t\t\tduration = duration_amount * multiplier,\n\t\t\t)\n\t\tissue.put()\n\t\tif self.request.get('option1'):\n\t\t\tissue.add_choice(cgi.escape(self.request.get('option1')))\n\t\tif self.request.get('option2'):\n\t\t\tissue.add_choice(cgi.escape(self.request.get('option2')))\n\t\tif self.request.get('option3'):\n\t\t\tissue.add_choice(cgi.escape(self.request.get('option3')))\n\t\tif self.request.get('option4'):\n\t\t\tissue.add_choice(cgi.escape(self.request.get('option4')))\n\t\tif self.request.get('option5'):\n\t\t\tissue.add_choice(cgi.escape(self.request.get('option5')))\n\t\t\n\t\tself.redirect('/issue/%s' % (issue.key().id()))\n\n\n\nclass EditHandler(webapp.RequestHandler):\n\tdef get(self,id):\n\t\tuser = users.get_current_user()\n\t\tif user:\n\t\t\tlogout_url = users.create_logout_url('/')\n\t\telse:\n\t\t\tself.redirect(users.create_login_url(self.request.uri))\n\t\t\treturn\n\t\tissue = Issue.get_by_id(int(id))\n\t\tchoices = issue.choices\n\t\tself.response.out.write(template.render('templates/edit.html', locals()))\n\n\tdef post(self,id):\n\t\tuser = users.get_current_user()\n\t\tif user:\n\t\t\tlogout_url = users.create_logout_url('/')\n\t\telse:\n\t\t\tself.redirect(users.create_login_url(self.request.uri))\n\t\t\treturn\n\t\tissue = Issue.get_by_id(int(id))\n\t\t\n\t\t\n\t\tif self.request.get('extend'):#if extending vote\n\t\t\tchoices = issue.choices\n\t\t\textend_amount = int(self.request.get('extend_amount')) * int(self.request.get('extend_multiplier'))\n\t\t\tissue.extend_duration(extend_amount)\n\t\t\tself.response.out.write(template.render('templates/edit.html', locals()))\n\t\t\t\n\t\telse:#otherwise we are saving changes\n\t\t\tduration_amount = int(self.request.get('duration_amount'))\n\t\t\tmultiplier = int(self.request.get('duration_multiplier'))\n\t\t\tissue.duration = duration_amount * multiplier\n\t\t\tif self.request.get('title'):\n\t\t\t\tissue.title = cgi.escape(self.request.get('title'))\n\t\t\tif self.request.get('description'):\n\t\t\t\tissue.description = cgi.escape(self.request.get('description'))\n\t\t\tif self.request.get('option1') and self.request.get('option2'):\n\t\t\t\tchoices = issue.choices\n\t\t\t\tdb.delete(choices)\n\t\t\t\tissue.add_choice(cgi.escape(self.request.get('option1')))\n\t\t\t\tissue.add_choice(cgi.escape(self.request.get('option2')))\n\t\t\t\tif self.request.get('option3'):\n\t\t\t\t\tissue.add_choice(cgi.escape(self.request.get('option3')))\n\t\t\t\tif self.request.get('option4'):\n\t\t\t\t\tissue.add_choice(cgi.escape(self.request.get('option4')))\n\t\t\t\tif self.request.get('option5'):\n\t\t\t\t\tissue.add_choice(cgi.escape(self.request.get('option5')))\n\t\t\tissue.put()\n\t\t\t#choices = issue.choices\n\t\t\tself.redirect('/issue/%s' % (id))\n\t\t\t#self.response.out.write(template.render('templates/edit.html', locals()))\n\t\t\t\n\n\nclass IssueHandler(webapp.RequestHandler):\n\tdef get(self,id):\n\t\tuser = users.get_current_user()\n\t\tif user:\n\t\t\tlogout_url = users.create_logout_url('/')\n\t\telse:\n\t\t\tself.redirect(users.create_login_url(self.request.uri))\n\t\t\treturn\n\t\t\n\t\tissue = Issue.get_by_id(int(id))\n\t\tissue.update_status()\n\t\t\n\t\tvote = issue.vote_for_member(user)\n\n\t\tissueUrl = self.request.uri\n\t\tself.response.out.write(template.render('templates/Issue.html', locals()))\n\t\t\n\t\t\n\tdef post(self,id):\n\t\tuser = users.get_current_user()\n\t\tif not user: #don't want someone who is not authenticated to be able to vote\n\t\t\tself.redirect(users.create_login_url(self.request.uri))\n\t\t\treturn\n\t\t\n\t\tissue = Issue.get_by_id(int(id))\n\t\t#vote = issue.vote_for_member()\n\t\t\n\t\tnew_choice = Choice.get_by_id(int(self.request.get('choice')))\n\t\twas_updated = issue.register_vote(new_choice)\n\t\t\n\t\tif was_updated:\n\t\t\tself.redirect('/?success=updated')\n\t\telse:\n\t\t\tself.redirect('/?success=vote')\n\t\t\n\n\n\ndef main():\n\tapplication = webapp.WSGIApplication([\n\t\t('/',MainPage),\n\t\t('/new',NewHandler),\n\t\t('/issue/(\\d+).*',IssueHandler),\n\t\t('/edit/(\\d+).*',EditHandler)],\n\t\tdebug=True)\n\tutil.run_wsgi_app(application)\n\t\nif __name__ == '__main__':\n main()\n","repo_name":"jonhull/hd-vote","sub_path":"main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":5689,"program_lang":"python","lang":"en","doc_type":"code","stars":2,"dataset":"github-code","pt":"17"} +{"seq_id":"12714675214","text":"\n#href: https://zhuanlan.zhihu.com/p/393058336 Python编程与Office办公自动化\n\n#1.将列表转化为字典\nkeys = ['one','two','three']\nvalues = [1,2,3]\n\ndic = dict(zip(keys,values)) # {'one': 1, 'two': 2, 'three': 3}\n\n\n#2.将下面的两个Python词典合并\n#注:字典可用**拆解,拆解出来就是字典的每一项\ndic1 = {'one': 1, 'two': 2, 'three': 3}\ndic2 = {'three': 3, 'four': 4, 'five': 5}\ndic3 = {**dic1,**dic2} #{'one': 1, 'two': 2, 'three': 3, 'four': 4, 'five': 5}\n\n#3.获取字典中的值:获取下列字典键为'history'的值\nsampleDict = {\n \"class\":{\n \"student\":{\n \"name\":\"Mike\",\n \"marks\":{\n \"physics\":70,\n \"history\":80\n }\n }\n }\n}\n\nsampleDict[\"class\"][\"student\"][\"marks\"][\"history\"] #80\n\n\n#4:将下面字典中部分件提取出来成为新的字典\n\nsampleDict = {\n \"name\": \"Kelly\",\n \"age\": 25,\n \"salary\": 8000,\n \"city\": \"New york\"\n\n}\n\nkeys = [\"name\", \"salary\"]\n\nnewDict = {key:sampleDict[key] for key in keys} #{'name': 'Kelly', 'salary': 8000}\n\n\n#5. 从字典中删除一组键\nsampleDict = {\n \"name\": \"Kelly\",\n \"age\": 25,\n \"salary\": 8000,\n \"city\": \"New york\"\n\n}\nkeysToRemove = [\"name\", \"salary\"]\n\nnewDict = {key:sampleDict[key] for key in sampleDict.keys()- keysToRemove } #{'age': 25, 'city': 'New york'}\n\n#6.反转给定列表中的各元素\naLsit = [100, 200, 300, 400, 500]\naLsit[::-1] #[500、400、300、200、100]\n\n\n#7.按索引连接两个列表\nlist1 = [\"M\", \"na\", \"i\", \"Ke\"]\nlist2 = [\"y\", \"me\", \"s\", \"lly\"]\nl = [i + j for i,j in zip(list1,list2)] #['My', 'name', 'is', 'Kelly']\n\n\n#8.给定一个数字列表,将列表中的每一项的平方数\naList = [1, 2, 3, 4, 5, 6, 7]\nl = [a**2 for a in aList] #[1, 4, 9, 16, 25, 36, 49]\nprint(l)\n\n#9.依次按顺序连接两个列表\nlist1 = [\"Hello \", \"take \"]\nlist2 = [\"Dear\", \"Sir\"]\n#['Hello Dear', 'Hello Sir', 'take Dear', 'take Sir']\n\nl = [a+b for a in list1 for b in list2]\n\n#10.同时迭代两个列表,以便 list1 应按原始顺序显示元素,而 list2 应按相反顺序显示元素\nlist1 = [10, 20, 30, 40]\nlist2 = [100, 200, 300, 400]\n\nfor x,y in zip(list1,list2[::-1]):\n print(x,y)\n\n\n#11.给定一个字符串和一个整数 n,从字符串中删除从 0 到 n 的字符并返回一个新字符串\n#例如,removeChars(\"人生苦短,我爱Python\", 5)因此输出必须为我爱Python.注意:n必须小于字符串的长度\ndef removeChars(s,n):\n return s[n:]\n\n\nprint(removeChars(\"人生苦短,我爱Python\", 5)) #我爱Python\n\n#12.输出偶数索引号处的字符\n#给定一个字符串,只显示出现在偶数索引号处的那些字符 例如:str = \"Python\"您应该显示p、t、o\ns = 'hellopython'\nfor i in range(0,len(s),2):\n print(s[i])\n\n","repo_name":"Poirot-World/Advanced-Python","sub_path":"Python_Exercises/Exercise_1.py","file_name":"Exercise_1.py","file_ext":"py","file_size_in_byte":2772,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"17"} +{"seq_id":"37269191488","text":"from threading import Thread, Lock\r\n\r\n\r\nclass BankAccount:\r\n def __init__(self):\r\n self.balance = 0\r\n self.lock = Lock()\r\n\r\n def earn(self):\r\n for _ in range(10_000_000):\r\n self.lock.acquire()\r\n self.balance += 1\r\n # this operation has three sub operations ... get, increase, assign.\r\n # these sub-operations should be atomic, so, they can not be divided\r\n # all these three sub operations should use a LOCK, saying to other\r\n # threads to wait, to do not to anything. After the thread finishes\r\n # its job, it releases the lock, so, now, other threads can do their\r\n # job. so now, we will modify this code using locks\r\n self.lock.release()\r\n print(\"Earned\\n\")\r\n\r\n def spend(self):\r\n for _ in range(10_000_000):\r\n self.lock.acquire()\r\n self.balance -= 1\r\n self.lock.release()\r\n print(\"Spent\")\r\n\r\n def get_balance(self):\r\n return self.balance\r\n\r\n\r\nif __name__ == \"__main__\":\r\n bank_account = BankAccount()\r\n # bank_account.earn()\r\n thread1 = Thread(target=bank_account.earn, args=())\r\n thread1.start()\r\n # bank_account.spend()\r\n thread2 = Thread(target=bank_account.spend, args=())\r\n thread2.start()\r\n thread1.join()\r\n thread2.join()\r\n # so, two sub-threads, one for spend and earn method\r\n # using 1_000_000 in the for loop, I find that the balance is 44_204, a clear error!\r\n # using instead 1_000 in the for loop, I find that the balance is 0 (w/o locks)\r\n # using Lock, acquire and release encapsulating the operation, we will obtain as a result 0\r\n current_balance = bank_account.get_balance()\r\n print(current_balance)\r\n","repo_name":"LorenzoBaggi/Parallel-Programming-and-HPC","sub_path":"main_lecture_4.py","file_name":"main_lecture_4.py","file_ext":"py","file_size_in_byte":1763,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"17"} +{"seq_id":"71447737304","text":"#!/usr/bin/env python3\n\"\"\"Reverse Beacon Network (www.reversebeacon.net) logging and filter tool\"\"\"\nimport argparse\nimport re\nimport telnetlib\nimport textwrap\n\n\nHOST = 'telnet.reversebeacon.net'\nPORT = 7000\nTIMEOUT = 5\n\nRGX = r'^DX de (.*?):\\s*(\\d+\\.\\d+)\\s*(\\S+)\\s+' +\\\n r'(\\S+)\\s+(\\d+) dB\\s+(\\d+)\\s+(\\S+)\\s+(\\S.*\\S)\\s+(\\d+)(\\d\\d)Z\\s*$'\n\nBANDS = [\n (160, 2500),\n (80, 5000),\n (60, 6000),\n (40, 8500),\n (30, 12000),\n (20, 16000),\n (17, 19500),\n (15, 22500),\n (12, 26500),\n (10, 40000),\n (6, 65000),\n (4, 120000),\n (2, 160000),\n (1.25, 300000),\n (0.7, 600000),\n (0.33, 1000000),\n (0.23, 1400000)]\n\ndef band_to_str(band):\n if band < 0:\n return str(band * 100) + 'cm'\n else:\n return str(band) + 'm'\n\n\ndef matches(key, val, regex=False):\n \"\"\"Check if a value matches a filter\n\n The filter can be one of the following:\n\n - None (always True)\n - Value, equatable to val (True on equality)\n - Regex (with regex=True) (True if str(val) matches key)\n - Function from type(val) to bool\n - A tuple of a key and a boolean, true iff the match should be inverted\n - A list of the above (at least one should match)\n \"\"\"\n if key is None:\n return True\n if regex:\n val = str(val)\n if type(key) is list:\n for subkey in key:\n if matches(subkey, val, regex=regex):\n return True\n return False\n if type(key) is tuple:\n match = matches(key[0], val, regex=regex)\n return not match if key[1] else match\n if regex:\n return re.match(key, val)\n if callable(key):\n return key(val)\n return key == val\n\ndef parse_range_filter(arg):\n if arg[0:2] == '<=':\n return lambda x : x <= float(arg[2:].strip())\n if arg[0:2] == '>=':\n return lambda x : x >= float(arg[2:].strip())\n if arg[0:2] == '/=':\n return lambda x : x != float(arg[2:].strip())\n if arg[0:1] == '=':\n return lambda x : x == float(arg[1:].strip())\n if arg[0:1] == '<':\n return lambda x : x < float(arg[1:].strip())\n if arg[0:1] == '>':\n return lambda x : x > float(arg[1:].strip())\n match = re.match(r'(\\d+(?:\\.\\d+)?)-(\\d+(?:\\.\\d+))', arg)\n if match is not None:\n return lambda x : float(match.group(1)) <= x <= float(match.group(2))\n raise ValueError('Could not parse \"' + arg + '\" as a range')\n\nclass Record:\n \"\"\"A record fetched from RBN\"\"\"\n def __init__(self, line):\n self.parse(line)\n\n def parse(self, line):\n \"\"\"Parse a line from the telnet server\"\"\"\n match = re.match(RGX, line)\n if match is None:\n raise ValueError('Could not parse: \"' + line + '\"')\n self.station_dx = match.group(1)\n self.frequency = float(match.group(2))\n self.station_de = match.group(3)\n self.mode = match.group(4)\n self.signal_strength = int(match.group(5))\n self.speed = (int(match.group(6)), match.group(7))\n self.record_type = match.group(8)\n self.time = (int(match.group(9)), int(match.group(10)))\n\n def band(self):\n for (band, freq) in BANDS:\n if self.frequency < freq:\n return band\n return None\n\n def match(self,\n dx=None, de=None, band=None, frequency=None, mode=None,\n signal_strength=None, speed=None, record_type=None):\n \"\"\"Does this record match filters?\n \n For filter documentation see matches().\n\n dx, de: string (regex search)\n mode, record_type: string\n band, signal_strength: int\n frequency: float\n speed: (int, string)\n \"\"\"\n filters = [\n (dx, self.station_dx, True),\n (de, self.station_de, True),\n (band, self.band(), False),\n (frequency, self.frequency, False),\n (mode, self.mode, False),\n (signal_strength, self.signal_strength, False),\n (speed, self.speed, False),\n (record_type, self.record_type, False)]\n for key, val, rgx in filters:\n if key is not None and not matches(key, val, regex=rgx):\n return False\n return True\n\n def __str__(self):\n return ('%02d'%self.time[0]) + ':' + ('%02d'%self.time[1]) + 'Z ' +\\\n 'DX de ' + (self.station_dx + ':').ljust(12) + ' ' +\\\n band_to_str(self.band()).rjust(4) + ' ' +\\\n str(self.frequency).rjust(10) + ' ' +\\\n self.station_de.ljust(14) + ' ' + self.mode.ljust(8) + ' ' +\\\n (str(self.signal_strength) + ' dB').rjust(6) + ' ' +\\\n str(self.speed[0]) + ' ' + self.speed[1] + '\\t' +\\\n self.record_type\n\ndef connect(call, host, port, timeout):\n \"\"\"Connect to an RBN server\"\"\"\n conn = telnetlib.Telnet(host, port, timeout)\n conn.read_until('Please enter your call:'.encode('ascii'))\n conn.write((call + '\\n').encode('ascii'))\n return conn\n\ndef main():\n \"\"\"Main program\"\"\"\n prs = argparse.ArgumentParser(\n formatter_class=argparse.RawDescriptionHelpFormatter,\n description='''Reverse Beacon Network logger''',\n epilog=textwrap.dedent('''\\\n All non-range filter arguments can be prepended with ~ to invert them.\n\n Range filters:\n - =x Value should be equal to x\n - /=x Value should not be equal to x\n - x Value should be greater than x\n - <=x Value should be smaller than or equal to x\n - >=x Value should be greater than or equal to x\n - x-y Value should be between x and y (inclusive)\n - A comma-separated list of range filters\n '''))\n\n prs.add_argument('-c', '--call', help='Your identification', required=True)\n prs.add_argument('-H', '--host', help='Telnet host', default=HOST)\n prs.add_argument('-p', '--port', help='Telnet port', default=PORT)\n prs.add_argument('--timeout', help='Connection timeout', default=TIMEOUT)\n\n prs.add_argument('--de', help='Filter transmitting station (regex)')\n prs.add_argument('--dx', help='Filter skimming station (regex)')\n prs.add_argument('-b', '--band',\n help='Filter band (comma-separated integers)')\n prs.add_argument('-m', '--mode',\n help='Filter mode (comma-separated strings)')\n prs.add_argument('-f', '--frequency',\n help='Filter frequency in MHz (range filter, see below)')\n prs.add_argument('-s', '--speed',\n help='Filter transmission speed (range filter, see below)')\n prs.add_argument('-S', '--signal',\n help='Filter signal strength in dB (range filter, see below)')\n prs.add_argument('-t', '--type', dest='record_type',\n help='Filter record type (comma-separated; e.g. CQ or BEACON)')\n\n prs.add_argument('-M', '--no-mark',\n dest='mark', action='store_false', default=True,\n help='Do not mark entries with your callsign (uses ANSI escape codes)')\n\n args = prs.parse_args()\n\n conn = connect(args.call, args.host, args.port, args.timeout)\n\n filters = dict(de=args.de, dx=args.dx)\n if args.band is not None:\n invert = args.band[0] == '~'\n if invert:\n args.band = args.band[1:]\n filters['band'] = (list(map(int, args.band.split(','))), invert)\n if args.mode is not None:\n invert = args.mode[0] == '~'\n if invert:\n args.mode = args.mode[1:]\n filters['mode'] = (args.mode.split(','), invert)\n if args.record_type is not None:\n invert = args.record_type[0] == '~'\n if invert:\n args.record_type = args.record_type[1:]\n filters['record_type'] = (args.record_type.split(','), invert)\n if args.frequency is not None:\n filters['frequency'] = list(map(\n parse_range_filter, args.frequency.split(',')))\n if args.speed is not None:\n speed_filters = list(map(parse_range_filter, args.speed.split(',')))\n filters['speed'] = lambda x : matches(speed_filters, x[0])\n if args.signal is not None:\n filters['signal'] = list(map(\n parse_range_filter, args.signal.split(',')))\n\n line = None\n while line is None or line != '':\n line = conn.read_until('\\r\\n'.encode('ascii'))\n try:\n rec = Record(line.decode('ascii').strip())\n if rec.match(**filters):\n if args.mark and args.call in rec.station_de.split('/'):\n print('\\033[1;33m{}\\033[m'.format(rec))\n elif args.mark and args.call in rec.station_dx.split('-'):\n print('\\033[1;36m{}\\033[m'.format(rec))\n else:\n print(rec)\n except ValueError:\n pass\n\nif __name__ == '__main__':\n try:\n main()\n except KeyboardInterrupt:\n print()\n except EOFError as exc:\n print(exc)\n","repo_name":"camilstaps/RBNLogger","sub_path":"rbn.py","file_name":"rbn.py","file_ext":"py","file_size_in_byte":9145,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"17"} +{"seq_id":"4687351975","text":"import re, os\n\n\ndef do_get_light_config(value, TelegramResponder):\n \"\"\"Light? - Gives you the possible light configurations\"\"\"\n for val in value.values():\n if val.strip() == \"Light?\":\n if (\n \"433MHz_Transiever\"\n in TelegramResponder.main.default_values_dict[\"settings\"]\n ):\n TelegramResponder.answer += \"All possible light configurations: \\n\\n\"\n for light in TelegramResponder.main.default_values_dict[\"settings\"][\n \"433MHz_Transiever\"\n ][\"Codes\"].keys():\n TelegramResponder.answer += \"{}\\n\".format(light)\n else:\n TelegramResponder.answer += (\n \"No transiever defined. Cannot do what you asked.\"\n )\n\n\ndef do_send_RF_code(value, TelegramResponder):\n \"\"\"Switch ConfigName - Turns light ON or OFF\"\"\"\n\n for val in value.values():\n light = re.findall(r\"Switch\\b\\s*(\\w*)\", val)\n parts = val.split()\n if light and len(parts) > 2: # Turn on or off if the command is correct\n if (\n \"433MHz_Transiever\"\n in TelegramResponder.main.default_values_dict[\"settings\"]\n ):\n if (\n light[0]\n in TelegramResponder.main.default_values_dict[\"settings\"][\n \"433MHz_Transiever\"\n ][\"Codes\"].keys()\n ):\n onoff = 1 if parts[-1].upper() == \"ON\" else 0\n path = os.path.normpath(\n TelegramResponder.main.default_values_dict[\"settings\"][\n \"433MHz_Transiever\"\n ][\"path\"]\n )\n for switch in TelegramResponder.main.default_values_dict[\n \"settings\"\n ][\"433MHz_Transiever\"][\"Codes\"][light[0]]:\n code = switch\n cmd = \"{} {} {}\".format(path, code, onoff)\n os.system(cmd)\n if onoff:\n old_light = TelegramResponder.current_light\n TelegramResponder.current_light = light[0]\n else:\n old_light = None # Because everything is off\n TelegramResponder.current_light = None\n\n # Switch the old one off, which are not included in the new one\n if old_light and TelegramResponder.settings.get(\n \"Exclusive_Light_Switching\", True\n ):\n path = os.path.normpath(\n TelegramResponder.main.default_values_dict[\"settings\"][\n \"433MHz_Transiever\"\n ][\"path\"]\n )\n onoff = 0\n for switch in TelegramResponder.main.default_values_dict[\n \"settings\"\n ][\"433MHz_Transiever\"][\"Codes\"][old_light]:\n if (\n switch\n not in TelegramResponder.main.default_values_dict[\n \"settings\"\n ][\"433MHz_Transiever\"][\"Codes\"][\n TelegramResponder.current_light\n ]\n ):\n code = switch\n cmd = \"{} {} {}\".format(path, code, onoff)\n os.system(cmd)\n\n TelegramResponder.answer += \"Done and enjoy.\"\n else:\n TelegramResponder.answer += (\n \"This light configuration is not defined.\"\n )\n else:\n TelegramResponder.answer += (\n \"No transiever defined. Cannot do what you asked.\"\n )\n\n elif light and len(parts) == 2: # if no on or off is defined\n TelegramResponder.answer = {\n \"CALLBACK\": {\n \"info\": \"Would you like to turn {} ON or OFF\".format(light[0]),\n \"keyboard\": {\n \"ON\": \"Switch {} ON\".format(light[0]),\n \"OFF\": \"Switch {} OFF\".format(light[0]),\n },\n \"arrangement\": [\"ON\", \"OFF\"],\n }\n }\n elif light and len(parts) == 1: # If just the switch command was send\n if (\n \"433MHz_Transiever\"\n in TelegramResponder.main.default_values_dict[\"settings\"]\n ):\n keyboard = {}\n arrangement = []\n for light in TelegramResponder.main.default_values_dict[\"settings\"][\n \"433MHz_Transiever\"\n ][\"Codes\"]:\n keyboard[light] = \"Switch {}\".format(light)\n arrangement.append([light])\n TelegramResponder.answer = {\n \"CALLBACK\": {\n \"info\": \"Possible light configurations:\",\n \"keyboard\": keyboard,\n \"arrangement\": arrangement,\n }\n }\n\n\ndef send_info(value, TelegramResponder):\n \"\"\"Info - Sends some infos to the user\"\"\"\n # create an exporter instance, as an argument give it\n # the item you wish to export\n for val in value.values(): # Todo: add the temperature and humidity response\n if re.findall(r\"Info\\b\\s*\", val):\n text = \"Temperature and Humidity: \\n\\n\"\n","repo_name":"Chilldose/COMET","sub_path":"COMET/misc_plugins/TelegramResponderPlugins/RaspberryPiPlugins.py","file_name":"RaspberryPiPlugins.py","file_ext":"py","file_size_in_byte":5760,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"17"} +{"seq_id":"70787101144","text":"import commands\nimport database_manager\nimport collections\nimport os\n\n''' Presentation Layer for the CLI Bookmark App'''\n\nclass Option:\n def __init__(self, name:str, command, prep_call = None):\n self.name = name\n self.command = command\n self.prep_call = prep_call\n\n def choose(self):\n data = self.prep_call() if self.prep_call else None\n message = self.command.execute(data)\n print(message)\n\n def __str__(self):\n return self.name\n\n\ndef print_options(options:dict):\n for key, option_text in options.items():\n print(f'({key}) {option_text}')\n print()\n\n\ndef get_user_choice(user_options:dict):\n user_input = input(\"Choose an option: \").upper()\n while (user_input not in user_options.keys()):\n print(\"\\nInvalid Option, try again\\n\")\n print_options(user_options)\n user_input = input(\"Choose an option: \").upper()\n return user_options[user_input]\n\n\ndef get_data(request:str, required:bool):\n user_input = input(f'{request}')\n while (required and not user_input):\n print(\"\\nInvalid Input: \")\n user_input = input(f'{request}')\n return user_input\n\ndef get_add_data() -> dict:\n title = get_data(\"Enter Bookmark Title: \", True)\n url = get_data(\"Enter Bookmark URL: \", True)\n notes = get_data(\"Enter Bookmark Notes: \", False)\n return {'title': title, 'url': url, 'notes': notes}\n\ndef get_delete_data() -> dict:\n id = get_data(\"Enter ID to delete: \", True)\n while (not isinstance(id,int)):\n id = get_data(\"Enter ID to delete: \", True)\n return {'id': int(id)}\n\ndef get_github_import_options():\n return {'github_username' : get_data('GitHub username: ', required=True),\n 'preserve_timestamps': get_data('Preserve timestamps [Y/N]: ', required=False) in {'Y', 'y', None}}\n\n\ndef clear_screen():\n print()\n print()\n input(\"Enter any key to return to the Menu: \")\n print()\n print()\n\n\ndef application_loop():\n user_options = {'A': Option(\"Add a bookmark\", commands.AddBookmarkCommand(), prep_call=get_add_data),\n 'B': Option(\"List bookmarks by Date\", commands.ShowBookmarksCommand()),\n 'T': Option(\"List bookmarks by Title\", commands.ShowBookmarksCommand(order_by=\"title\")),\n 'D': Option(\"Delete a bookmark\", commands.DeleteBookmardCommand(), prep_call=get_delete_data),\n 'G': Option(\"Import GitHub stars\", commands.ImportGitHubStarsCommand(), prep_call=get_github_import_options),\n 'Q': Option(\"Quit\", commands.QuitCommand())\n }\n\n print_options(user_options)\n user_option = get_user_choice(user_options)\n user_option.choose()\n clear_screen()\n\n\n\nif __name__ == '__main__':\n print('Welcome to BookMark App!')\n commands.CreateBookmarksTableCommand().execute()\n\n while True:\n application_loop()\n\n","repo_name":"JSheldon3488/Bookmark_App","sub_path":"presentation.py","file_name":"presentation.py","file_ext":"py","file_size_in_byte":2898,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"17"} +{"seq_id":"20666156406","text":"import sqlite3\nfrom prettytable import PrettyTable\n\n\ndb = sqlite3.connect(\"company.db\")\ndb.row_factory = sqlite3.Row\ncursor = db.cursor()\n\nprint(\"You can use the following commands:\\nlist_employees\\n\\\nmonthly_spending\\nyearly_spending\\nadd_employee\\n\\\ndelete_employee \\nupdate_employee \")\ncommand = input(\"command> :\")\n\n\ndef list_employees():\n table = PrettyTable([\"id\", \"name\", \"position\"])\n info = cursor.execute(\"SELECT id, name, position FROM users\")\n for row in info:\n table.add_row([row[\"id\"], row[\"name\"], row[\"position\"]])\n print(table)\n\n\ndef monthly_spending():\n info = cursor.execute(\"SELECT monthly_salary FROM users\")\n salary = sum([row[\"monthly_salary\"] for row in info])\n print(\"The company is spending ${} every month!\".format(salary))\n\n\ndef yearly_spending():\n info = cursor.execute(\"SELECT monthly_salary, yearly_bonus FROM users\")\n total = sum(\n [12 * row[\"monthly_salary\"] + row[\"yearly_bonus\"] for row in info])\n print(total)\n\n\ndef add_employee():\n name = input(\"name> \")\n salary = int(input(\"monthly_salary> \"))\n bonus = int(input(\"yearly_bonus> \"))\n position = input(\"position> \")\n cursor.execute(\"\"\"INSERT INTO users(name, monthly_salary, yearly_bonus, position)\n VALUES(?,?,?,?)\"\"\", (name, salary, bonus, position))\n db.commit()\n\n\ndef delete_employee(num):\n cursor.execute(\"DELETE FROM users WHERE id = ?\", (num))\n db.commit()\n\n\ndef update_employee(num):\n name = input(\"name> \")\n salary = int(input(\"monthly_salary> \"))\n bonus = int(input(\"yearly_bonus> \"))\n position = input(\"position> \")\n cursor.execute(\"\"\"UPDATE users SET name = ?,\n monthly_salary = ?,\n yearly_bonus = ?,\n position = ?\n WHERE id = ?\"\"\", (name, salary, bonus, position, num))\n db.commit()\n\ncommands = {\n \"list_employees\": list_employees,\n \"monthly_spending\": monthly_spending,\n \"yearly_spending\": yearly_spending,\n \"add_employee\": add_employee,\n \"delete_employee\": delete_employee,\n \"update_employee\": update_employee\n }\n\n\ndef main():\n user_command = command.split()[0]\n try:\n user_id = command.split()[1]\n commands[user_command](user_id)\n print(\"i deleted\")\n except:\n commands[user_command]()\n\nif __name__ == '__main__':\n main()\n","repo_name":"pgergov/Programming101-v3","sub_path":"week7/2-SQL-Starter/manage_company.py","file_name":"manage_company.py","file_ext":"py","file_size_in_byte":2482,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"17"} +{"seq_id":"72896045144","text":"import pygame, math\nfrom draw import make_stars, swap_settings, query_input, get_input_object, star_map, load_inputs\nimport tkinter as tk\nfrom tkinter import filedialog\n\nroot = tk.Tk()\nroot.withdraw()\nroot.overrideredirect(True)\nroot.geometry('0x0+0+0')\n\ndef perform_action(action, settings):\n if action == \"reset\" or action == \"textString\":\n perform_action(\"rewrite\", settings)\n make_stars(settings)\n elif action == \"settings\":\n swap_settings()\n elif action == \"R\" or action == \"G\" or action == \"B\":\n color_r = query_input(\"R\")\n color_g = query_input(\"G\")\n color_b = query_input(\"B\")\n get_input_object(\"colorbox\").color = (color_r, color_g, color_b)\n get_input_object(\"colorbox\").color_active = (color_r, color_g, color_b)\n elif action == \"starcolor\":\n settings.star_color = get_input_object(\"colorbox\").color\n get_input_object(\"starcolor\").color = get_input_object(\"colorbox\").color\n get_input_object(\"starcolor\").color_active = get_input_object(\"colorbox\").color\n elif action == \"backgroundcolor\":\n settings.back_color = get_input_object(\"colorbox\").color\n get_input_object(\"backgroundcolor\").color = get_input_object(\"colorbox\").color\n get_input_object(\"backgroundcolor\").color_active = get_input_object(\"colorbox\").color\n elif action == \"starcount\":\n temp_num, temp_text = query_input(\"starcount\"), ''\n for char in temp_num:\n if char.isdigit():\n temp_text += char\n if temp_text:\n settings.number_of_stars = int(temp_text)\n else:\n settings.number_of_stars = 0\n temp_text = \"0\"\n change_textbox(\"starcount\", temp_text.strip())\n elif action == \"showgrid\":\n settings.show_grid = not settings.show_grid\n if settings.show_grid:\n get_input_object(\"showgrid\").display_text_color = (0, 0, 0)\n else:\n get_input_object(\"showgrid\").display_text_color = (63, 63, 63)\n elif action == \"showconstellations\":\n settings.show_constellations = not settings.show_constellations\n if settings.show_constellations:\n get_input_object(\"showconstellations\").display_text_color = (0, 0, 0)\n else:\n get_input_object(\"showconstellations\").display_text_color = (63, 63, 63)\n elif action == \"textSizeUp\":\n settings.text_size = min((settings.text_size + 5), settings.max_constellation_size)\n perform_action(\"constellation_density\", settings)\n perform_action(\"rewrite\", settings)\n elif action == \"textSizeDown\":\n settings.text_size = max((settings.text_size - 5), settings.min_constellation_size)\n perform_action(\"constellation_density\", settings)\n perform_action(\"rewrite\", settings)\n elif action == \"rewrite\":\n temp_string = query_input(\"textString\")\n temp_text = \"\"\n for char in temp_string:\n if char.isalpha() or char == \" \":\n temp_text += char\n settings.text_input = temp_text.strip()\n change_textbox(\"textString\", temp_text.strip())\n perform_action(\"starcount\", settings)\n perform_action(\"textPosX\", settings)\n elif action == \"textPosX\" or action == \"textPosY\":\n strX = \"\"\n posX = query_input(\"textPosX\")\n for char in posX:\n if char.isdigit() or char == \"-\":\n strX += char\n if not strX:\n strX = \"0\"\n change_textbox(\"textPosX\", str(int(strX)))\n if abs(int(strX)) > 100:\n if int(strX) < 0:\n strX = \"-100\"\n else:\n strX = \"100\"\n change_textbox(\"textPosX\", str(int(strX)))\n strY = \"\"\n posY = query_input(\"textPosY\")\n for char in posY:\n if char.isdigit() or char == \"-\":\n strY += char\n if not strY:\n strY = \"0\"\n change_textbox(\"textPosY\", str(int(strY)))\n if abs(int(strY)) > 100:\n if int(strY) < 0:\n strY = \"-100\"\n else:\n strY = \"100\"\n change_textbox(\"textPosY\", str(int(strY)))\n settings.text_location = star_map.coerce_to_center(int(strX),int(strY))\n elif action == \"savefile\":\n save_file(settings)\n elif action == \"constellation_density\":\n settings.number_of_constellations = int((40/3 - (settings.text_size/12)) * (query_input(\"constellation_density\") + 1))\n elif action == \"reset_default\":\n load_inputs(settings)\n\ndef change_textbox(textbox, string):\n textbox = get_input_object(textbox)\n textbox.text_object.input_string = string\n textbox.text_object.cursor_position = len(string)\n textbox.text_object.update([])\n\ndef save_file(settings):\n #pygame.display.iconify()\n file_path = filedialog.asksaveasfilename(parent=root,title = \"Select file\", filetypes = ((\"jpeg files\",\"*.jpg\"),(\"all files\",\"*.*\")))\n if file_path:\n pygame.image.save(settings.starfield, file_path + \".jpg\")\n\n\n","repo_name":"stephenfinch/Star-Map-Generator_v2","sub_path":"backend.py","file_name":"backend.py","file_ext":"py","file_size_in_byte":5026,"program_lang":"python","lang":"en","doc_type":"code","stars":6,"dataset":"github-code","pt":"17"} +{"seq_id":"1103378894","text":"import cv2\nimport numpy as np\nimport rospy\nfrom sensor_msgs.msg import CompressedImage\nfrom std_msgs.msg import Header\n\n__isRetrieved = False\n\nheader = Header()\nformat = \"\"\ndata = b\"\"\n\n\ndef __setCamera(res): # type: (CompressedImage) -> None\n global __isRetrieved, header, format, data\n __isRetrieved = True\n header = res.header\n format = res.format\n data = res.data\n\n\ndef getImage():\n if __isRetrieved == False:\n return None\n np_arr = np.frombuffer(data, dtype=np.uint8)\n return cv2.imdecode(np_arr, cv2.IMREAD_COLOR)\n\n\nrospy.Subscriber(\"/image_jpeg/compressed\", CompressedImage, __setCamera)\n","repo_name":"Doge-Driver/AutoDrive","sub_path":"src/wecar_ros/scripts/Subscribers/Camera.py","file_name":"Camera.py","file_ext":"py","file_size_in_byte":626,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"17"} +{"seq_id":"35370944566","text":"\"\"\" Plotting helpers. \"\"\"\n\nimport pandas as pd\nimport numpy as np\nimport tensorly as tl\nfrom tensorly.cp_tensor import cp_flip_sign\nfrom tensorly.decomposition import parafac\nfrom tensorpack.cmtf import cp_normalize\nimport seaborn as sns\nfrom .dataHelpers import reorder_table\n\n\ndef plot_heatmaps(tensor, ax, comps=5):\n \"\"\" Plots all the components across all factors for the MEMA datasets. \"\"\"\n fac = parafac(tensor.to_numpy(), comps, n_iter_max=2000, linesearch=True, tol=1e-9) # tensor is xarray type\n fac = cp_flip_sign(fac, 0)\n fac = cp_normalize(fac)\n\n labels = [f\"Cmp. {i}\" for i in np.arange(1, fac.factors[0].shape[1] + 1)]\n print(\"R2X: \", 1.0 - np.linalg.norm(tl.cp_to_tensor(fac) - tensor)**2.0 / np.linalg.norm(tensor)**2.0)\n\n for ii in range(tensor.ndim):\n facZero = pd.DataFrame(fac.factors[ii], columns=labels, index=tensor.coords[tensor.dims[ii]])\n facZero = reorder_table(facZero)\n sns.heatmap(facZero.T, ax=ax[ii], cmap=\"PRGn\", center=0)\n\ndef plot_components_MEMA(tensor, ax):\n \"\"\" Plots most significant components separately in the supplementary figures. \"\"\"\n tFac = parafac(tensor.to_numpy(), 5, n_iter_max=2000, linesearch=True, tol=1e-9) # tensor is xarray type\n tFac = cp_flip_sign(tFac, 0)\n tFac = cp_normalize(tFac)\n labels = [f\"Cmp. {i}\" for i in np.arange(1, tFac.factors[0].shape[1] + 1)]\n\n k = 0\n for ii in range(tensor.ndim):\n facZero = pd.DataFrame(tFac.factors[ii], columns=labels, index=tensor.coords[tensor.dims[ii]])\n facZero = reorder_table(facZero)\n\n for c, col in enumerate(facZero.keys()):\n feature = facZero[[col]]\n\n feature_l_ind = feature.abs().nlargest(10, col).index\n\n g0 = sns.heatmap(feature.loc[feature_l_ind].sort_values([col]), ax=ax[c + k], cmap=\"PRGn\", center=0, vmin=-1, vmax=1)\n g0.set_title(f\"Proteins, {col}\")\n k += 5\n","repo_name":"meyer-lab/tfac-ccle","sub_path":"tfac/plotHelpers.py","file_name":"plotHelpers.py","file_ext":"py","file_size_in_byte":1909,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"17"} +{"seq_id":"41128905888","text":"import json\n\nfrom flask import Flask, request\nfrom flask.templating import render_template\nfrom slacker import Slacker\n\nfrom comics_generator import parse_comics_message\nfrom meme_generator import *\nfrom slack_communicator import get_direct_messages, get_user_map, get_user\n\napp = Flask(__name__)\nSLACK_API_TOKEN = os.environ.get(\"SLACK_API_TOKEN\")\nSLACK_MEME_WEBHOOK_URL = os.environ.get(\"SLACK_MEME_WEBHOOK_URL\")\nSLACK_COMICS_WEBHOOK_URL = os.environ.get(\"SLACK_COMICS_WEBHOOK_URL\")\n\n\n@app.route(\"/meme\")\ndef meme():\n text = request.args[\"text\"]\n channel_id = request.args[\"channel_id\"]\n user_id = request.args[\"user_id\"]\n\n if text.startswith(\"list\"):\n return list_memes()\n\n meme, top, bottom = parse_message(text)\n\n meme_url = build_url(meme, top, bottom)\n\n payload = get_user(user_id)\n payload[\"channel\"] = channel_id\n\n attachments = [{\"image_url\": meme_url, \"fallback\": \"Oops. Try again.\"}]\n payload.update({\"attachments\": attachments})\n\n try:\n requests.post(SLACK_MEME_WEBHOOK_URL, data=json.dumps(payload))\n except Exception as e:\n return e\n\n return \"Success!\", 200\n\n\n@app.route(\"/comics\")\ndef comics():\n channel_id = request.args[\"channel_id\"]\n user_id = request.args[\"user_id\"]\n payload = get_user(user_id)\n payload[\"channel\"] = channel_id\n\n attachments = [{\"image_url\": \"http://freehtmltopdf.com/?convert=http://comics-slack.herokuapp.com/\", \"fallback\": \"Oops. Try again.\"}]\n payload.update({\"attachments\": attachments})\n\n try:\n requests.post(SLACK_COMICS_WEBHOOK_URL, data=json.dumps(payload))\n except Exception as e:\n return e\n\n return \"Success!\", 200\n\n\n@app.route(\"/\")\ndef hello():\n text = request.args[\"text\"]\n messages_count, scenes, title = parse_comics_message(text)\n\n slack = Slacker(SLACK_API_TOKEN)\n user_id_name_map = get_user_map(slack)\n user_name_id = {v: k for k, v in user_id_name_map.items()}\n\n messages = get_direct_messages(slack, user_id_name_map, 'ktisha')\n messages = messages[-messages_count:]\n\n messages_list = []\n for i in range(scenes):\n messages_list.append(messages[(len(messages)//scenes) *i: (len(messages)//scenes) * (i + 1)])\n\n comix = render_template(\"base.html\", title=title, messages=messages_list, user1=user_name_id['stan'],\n user2=user_name_id['ktisha'], id1=1, id2=2, id3=3, scenes=scenes)\n return comix\n\n","repo_name":"ktisha/ComicSlack","sub_path":"views.py","file_name":"views.py","file_ext":"py","file_size_in_byte":2438,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"17"} +{"seq_id":"37416751443","text":"\nfrom sklearn import tree\nimport pandas as pd\n\n\nurl=\"https://gwprojectflask.herokuapp.com/api/data/raw_results\"\ndf = pd.read_json(url)\ndf.head()\n\n\ndf_data=df[['Data_Type','Correct']]\ndf_target=df['Chart_Type']\ndf_target.unique()\n\n\ndf_data_dummies = pd.get_dummies(df_data)\ndf_data_dummies.head()\n\n\ndata_names = ['Number Correct','DimensionVsMeasure','Comparison','Dimension(Location)VsMeasure','Dimension(Time)VsMeasure','MeasureVsMeasure']\ntarget_names = df_target.unique()\n\n\nclf = tree.DecisionTreeClassifier()\nclf = clf.fit(df_data_dummies, df_target)\n\nprediction = clf.predict([[1,0,0,1,0,0]])\n\nprint(prediction)\n\n\n\n","repo_name":"justinmthomas/GW_Project2","sub_path":"decision_tree.py","file_name":"decision_tree.py","file_ext":"py","file_size_in_byte":620,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"17"} +{"seq_id":"37176171464","text":"from django.urls import path\nfrom rest_framework_simplejwt.views import TokenRefreshView\n\nfrom .views import AuthTokenObtainPairView, LoginAPIView, SignUpAPIView\n\napp_name = \"user\"\n\nurlpatterns = [\n path(\"token/\", AuthTokenObtainPairView.as_view(), name=\"token_obtain_pair\"),\n path(\"token/refresh/\", TokenRefreshView.as_view(), name=\"token_refresh\"),\n path(\"login/\", LoginAPIView.as_view(), name=\"login\"),\n path(\"signup/\", SignUpAPIView.as_view(), name=\"signup\"),\n]\n","repo_name":"julkaar9/django-projects","sub_path":"phonebook/user/urls.py","file_name":"urls.py","file_ext":"py","file_size_in_byte":478,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"17"} +{"seq_id":"37268425016","text":"class CustomNoItemsException(Exception):\r\n def __init__(self):\r\n pass\r\n\r\n\r\nclass ListQueue:\r\n def __init__(self):\r\n self.__array = []\r\n\r\n def put(self, element):\r\n self.__array.append(element)\r\n\r\n def size(self):\r\n return len(self.__array)\r\n\r\n def get(self):\r\n if self.size() == 0:\r\n raise CustomNoItemsException\r\n else:\r\n return self.__array.pop(0)\r\n\r\n\r\nn = int(input())\r\ns = ListQueue()\r\n\r\nfor _ in range(n):\r\n try:\r\n command = input().split(' ')\r\n if len(command) == 1:\r\n print(getattr(s, command[0])())\r\n else:\r\n getattr(s, command[0])(command[1])\r\n except CustomNoItemsException:\r\n print('error')\r\n","repo_name":"SergeiZharkovsky/algorithms","sub_path":"Алгоритмы и структуры данных/sprint_2/Списочная очередь.py","file_name":"Списочная очередь.py","file_ext":"py","file_size_in_byte":738,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"17"} +{"seq_id":"74565150425","text":"\"\"\"\n\nEstruturas Usadas:\n- Dicionário para simular um banco de dados de usuários\n\"\"\"\n\ndef register_user():\n \"\"\"\n Registra um novo usuário com os campos solicitados na inicialização do programa.\n Pergunta se o usuário gostaria de inserir mais campos, até que ele peça para sair.\n \"\"\"\n id = len(banco_usuarios) + 1\n banco_usuarios[id] = dict.fromkeys(campos, \"\")\n for i in campos:\n banco_usuarios[id][i] = input(f\"Digite {i} do usuário: \")\n\n campo_extra = input(\"Digite o campo extra a ser inserido: \")\n while(campo_extra != \"sair\"):\n banco_usuarios[id][campo_extra] = input(f\"Digite {campo_extra} do usuario: \")\n campo_extra = input(\"Digite o campo extra a ser inserido: \")\n \ndef print_users(*args, **kwargs):\n \"\"\"\n Imprime as informações do usuário de acordo com a opção de filtro selecionada no menu.\n \"\"\"\n if not args and not kwargs:\n for i in banco_usuarios:\n print(banco_usuarios.values())\n elif args and not kwargs:\n for data in banco_usuarios.items():\n if data[\"nome\"] in args:\n print(data)\n elif not args and kwargs:\n filtered_users = []\n for data in banco_usuarios.values():\n match = True\n for chave, valor in kwargs.items():\n if chave not in data or data[chave] != valor:\n match = False\n break\n if match:\n filtered_users.append(data)\n \n if filtered_users:\n for data in filtered_users:\n print(data)\n else:\n print(\"Nenhum usuário encontrado com os critérios especificados.\")\n elif args and kwargs:\n for data in banco_usuarios.values():\n if data[\"nome\"] in args:\n match = True\n for chave, valor in kwargs.items():\n if chave not in data or data[chave] != valor:\n match = False\n break\n if match:\n print(data)\n\nbanco_usuarios = { }\n\ncampos = list(input(\"Digite os campos obrigatórios (separados por ,): \").split(\",\"))\nwhile(True):\n print(\"1-Cadastrar Usuário\")\n print(\"2-Imprimir Usuários\")\n print(\"0-Encerrar\")\n\n option = int(input(\"Selecione uma opção: \"))\n if option == 0:\n break\n elif option == 1:\n register_user()\n\n elif option == 2:\n print(\"1-Imprimir todos\")\n print(\"2-Filtrar por nomes\")\n print(\"3-Filtrar por campos\")\n print(\"4-Filtra por nome e campos\")\n option = int(input(\"Selecione uma opção: \"))\n if option == 1:\n print_users()\n elif option == 2:\n names = input(\"Digite os nomes (separados por ,): \").split(\",\")\n print_users(*names)\n elif option == 3:\n campos = { }\n \n campo = input(\"Digite o campo de busca: \")\n while(campo != \"sair\"):\n valor = input(f\"Digite {campo}: \")\n campos[campo] = valor\n campo = input(\"Digite o campo de busca: \")\n \n print_users(**campos)\n elif option == 4:\n names = input(\"Digite os nomes (separados por ,): \").split(\",\") \n campos = { }\n \n campo = input(\"Digite o campo de busca: \")\n while(campo != \"sair\"):\n valor = input(f\"Digite {campo}: \")\n campos[campo] = valor\n campo = input(\"Digite o campo de busca: \")\n \n print_users(*names, **campos)","repo_name":"luanpozzobon/Lista","sub_path":"ex4.py","file_name":"ex4.py","file_ext":"py","file_size_in_byte":3631,"program_lang":"python","lang":"pt","doc_type":"code","stars":0,"dataset":"github-code","pt":"17"} +{"seq_id":"21329529416","text":"from .Base import Base\n\n\nclass TapChangerTablePoint(Base):\n\t'''\n\t\n\n\t:b: The magnetizing branch susceptance deviation in percent of nominal value. The actual susceptance is calculated as follows: calculated magnetizing susceptance = b(nominal) * (1 + b(from this class)/100). The b(nominal) is defined as the static magnetizing susceptance on the associated power transformer end or ends. This model assumes the star impedance (pi model) form. Default: 0.0\n\t:g: The magnetizing branch conductance deviation in percent of nominal value. The actual conductance is calculated as follows: calculated magnetizing conductance = g(nominal) * (1 + g(from this class)/100). The g(nominal) is defined as the static magnetizing conductance on the associated power transformer end or ends. This model assumes the star impedance (pi model) form. Default: 0.0\n\t:r: The resistance deviation in percent of nominal value. The actual reactance is calculated as follows: calculated resistance = r(nominal) * (1 + r(from this class)/100). The r(nominal) is defined as the static resistance on the associated power transformer end or ends. This model assumes the star impedance (pi model) form. Default: 0.0\n\t:ratio: The voltage ratio in per unit. Hence this is a value close to one. Default: 0.0\n\t:step: The tap step. Default: 0\n\t:x: The series reactance deviation in percent of nominal value. The actual reactance is calculated as follows: calculated reactance = x(nominal) * (1 + x(from this class)/100). The x(nominal) is defined as the static series reactance on the associated power transformer end or ends. This model assumes the star impedance (pi model) form. Default: 0.0\n\t\t'''\n\n\tcgmesProfile = Base.cgmesProfile\n\n\tpossibleProfileList = {'class': [cgmesProfile.EQ.value, ],\n\t\t\t\t\t\t'b': [cgmesProfile.EQ.value, ],\n\t\t\t\t\t\t'g': [cgmesProfile.EQ.value, ],\n\t\t\t\t\t\t'r': [cgmesProfile.EQ.value, ],\n\t\t\t\t\t\t'ratio': [cgmesProfile.EQ.value, ],\n\t\t\t\t\t\t'step': [cgmesProfile.EQ.value, ],\n\t\t\t\t\t\t'x': [cgmesProfile.EQ.value, ],\n\t\t\t\t\t\t }\n\n\tserializationProfile = {}\n\n\t\n\n\tdef __init__(self, b = 0.0, g = 0.0, r = 0.0, ratio = 0.0, step = 0, x = 0.0, ):\n\t\n\t\tself.b = b\n\t\tself.g = g\n\t\tself.r = r\n\t\tself.ratio = ratio\n\t\tself.step = step\n\t\tself.x = x\n\t\t\n\tdef __str__(self):\n\t\tstr = 'class=TapChangerTablePoint\\n'\n\t\tattributes = self.__dict__\n\t\tfor key in attributes.keys():\n\t\t\tstr = str + key + '={}\\n'.format(attributes[key])\n\t\treturn str\n","repo_name":"sogno-platform/cimpy","sub_path":"cimpy/cgmes_v2_4_15/TapChangerTablePoint.py","file_name":"TapChangerTablePoint.py","file_ext":"py","file_size_in_byte":2416,"program_lang":"python","lang":"en","doc_type":"code","stars":40,"dataset":"github-code","pt":"17"} +{"seq_id":"27885113039","text":"import time\nimport xlsxwriter\nfrom pymongo import MongoClient\nfrom connect.timer import Timer\n\n\nclass MongoExport(object):\n\n def __init__(self, path, fileName):\n self.path = path + fileName\n self.client = MongoClient()\n self.workbook = xlsxwriter.Workbook(self.path, {'nan_inf_to_errors': True}) # 处理无穷大\n\n def buildSheet(self, name='sheet0'):\n worksheet = self.workbook.add_worksheet(name)\n # 设置行头\n for j in range(len(self.fields)):\n worksheet.write(0, j, self.fields[j])\n j = j + 1\n return worksheet\n\n def export(self, dbName, colName, fields ,filter={},sort =[('_id',1)]):\n start = time.time()\n self.fields = fields\n worksheet = self.buildSheet()\n db = self.client.get_database(dbName)\n col = db.get_collection(colName)\n rlist = col.find(filter).sort(sort)\n rowNum = 1\n for r in rlist:\n rowNum = self.write(r, worksheet, rowNum)\n self.workbook.close()\n print('耗时:', time.time() - start)\n\n def write(self, record, worksheet, rowNum):\n j = 0\n for j in range(len(fields)):\n worksheet.write(rowNum, j, record[fields[j]])\n\n return rowNum + 1\n\n def exportGroupByField(self, dbName, colName, fields, fieldName):\n self.fields = fields\n start = time.time()\n d = {}\n rowNumD = {}\n db = self.client.get_database(dbName)\n col = db.get_collection(colName)\n rlist = col.find()\n for r in rlist:\n key = r[fieldName]\n if (key not in d.keys()):\n d[key] = self.buildSheet(key)\n rowNumD[key] = 1\n rowNumD[key] = self.write(r, d[key], rowNumD[key])\n self.workbook.close()\n print('耗时:', time.time() - start)\n\nif __name__ == '__main__':\n export = MongoExport(\"E:/Python练习/excel/\",\"job2.xlsx\")\n fields = ['jobId', 'jobName', 'arera', 'cAdress', 'cName', 'wage']\n export.buildBook(fields)\n export.export('spider','job')","repo_name":"yliu19930120/mongoExcel","sub_path":"connect/mongoExport.py","file_name":"mongoExport.py","file_ext":"py","file_size_in_byte":2071,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"17"} +{"seq_id":"23773181910","text":"def main():\n n = int(input())\n print('Weird' if(n % 2 != 0 or 6 <= n <= 20 ) else 'Not Weird')\n\nif __name__ == '__main__':\n main()\n'''\n#Solution 2:\n\nn = int(input())\nif n % 2 == 1:\n print(\"Weird\")\nelif n % 2 == 0 and 2 <= n <= 5:\n print(\"Not Weird\")\nelif n % 2 == 0 and 6 <= n <= 20:\n print(\"Weird\")\nelse:\n print(\"Not Weird\")\n\n '''","repo_name":"avish0694/HackerrankSolutions","sub_path":"Python/Ifelse.py","file_name":"Ifelse.py","file_ext":"py","file_size_in_byte":352,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"17"} +{"seq_id":"38594742883","text":"import cv2\nimport numpy as np\n\n## Tutorial based on\n## https://opencv-python-tutroals.readthedocs.io/en/latest/py_tutorials/py_imgproc/py_filtering/py_filtering.html\n\n\ndef stackImages(scale,imgArray):\n rows = len(imgArray)\n cols = len(imgArray[0])\n rowsAvailable = isinstance(imgArray[0], list)\n width = imgArray[0][0].shape[1]\n height = imgArray[0][0].shape[0]\n if rowsAvailable:\n for x in range ( 0, rows):\n for y in range(0, cols):\n if imgArray[x][y].shape[:2] == imgArray[0][0].shape [:2]:\n imgArray[x][y] = cv2.resize(imgArray[x][y], (0, 0), None, scale, scale)\n else:\n imgArray[x][y] = cv2.resize(imgArray[x][y], (imgArray[0][0].shape[1], imgArray[0][0].shape[0]), None, scale, scale)\n if len(imgArray[x][y].shape) == 2: imgArray[x][y]= cv2.cvtColor( imgArray[x][y], cv2.COLOR_GRAY2BGR)\n imageBlank = np.zeros((height, width, 3), np.uint8)\n hor = [imageBlank]*rows\n hor_con = [imageBlank]*rows\n for x in range(0, rows):\n hor[x] = np.hstack(imgArray[x])\n ver = np.vstack(hor)\n else:\n for x in range(0, rows):\n if imgArray[x].shape[:2] == imgArray[0].shape[:2]:\n imgArray[x] = cv2.resize(imgArray[x], (0, 0), None, scale, scale)\n else:\n imgArray[x] = cv2.resize(imgArray[x], (imgArray[0].shape[1], imgArray[0].shape[0]), None,scale, scale)\n if len(imgArray[x].shape) == 2: imgArray[x] = cv2.cvtColor(imgArray[x], cv2.COLOR_GRAY2BGR)\n hor= np.hstack(imgArray)\n ver = hor\n return ver\n\nkernel = np.ones((7,7),np.float32)\nimg = cv2.imread('Resource/images/girl_face_01.PNG')\n\n\nimgGray = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)\nimgBlur = cv2.filter2D(img,-1,kernel/30)\nimgCanny= cv2.Canny(imgGray, 200, 100)\n\nimgErod = cv2.erode(img,kernel,iterations = 1)\n\nstackedImg = stackImages(0.6, ([img, imgGray, imgBlur, imgErod]))\ncv2.imshow(\"Stacked Images \", stackedImg)\n\ncv2.waitKey(0)\n\n","repo_name":"zafrulumar/opencv_zu_code","sub_path":"opencv/zu_blur_image_01.py","file_name":"zu_blur_image_01.py","file_ext":"py","file_size_in_byte":2034,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"17"} +{"seq_id":"19793856657","text":"'''\nCreated on 3 de ago de 2017\n\n@author: weslley\n'''\n\nfrom dolfin.cpp.mesh import Point, MeshFunction, SubDomain\nfrom dolfin.cpp.function import near\nfrom dolfin.cpp.io import File\nfrom numpy import array\n\nclass Geometry():\n \"\"\"Geometry class\"\"\"\n \n def __init__(self, points, faces):\n self._points = points # Points used for face elements\n self._faces = faces # Face elements\n if len(self._faces) > 0:\n if len(self._faces[0]) == 2:\n self._nDim = 2 # Topological dimension\n else:\n self._nDim = 3 # Topological dimension\n \n def getNoFaces(self):\n return len(self._faces)\n \n def getNormals(self):\n geoNormals = [Point() for i in range(self.getNoFaces())]\n if self._nDim == 2:\n for i in range(self.getNoFaces()):\n v = self._points[self._faces[i][1]]-self._points[self._faces[i][0]]\n geoNormals[i] = Point(v[1],-v[0])\n elif self._nDim == 3:\n geoNormals = [\n (self._points[face[1]]-self._points[face[0]]).cross(self._points[face[2]]-self._points[face[0]]) for face in self._faces\n ]\n else:\n print(\"Invalid dimension!\")\n exit(1)\n return geoNormals\n\ndef markBoundariesOfMesh(mesh, geo, **kwargs):\n '''Mark the boundaries of a mesh given a geometry\n \n All interior faces are marked with zero\n \n If the geometry has no marks, it will be mared using the convention:\n face[0] = 1\n face[1] = 2\n ...\n face[N] = N+1\n '''\n \n # Reference point indexes in each face\n geoBndPoints = [ face[0] for face in geo._faces ]\n\n # Face normals\n geoNormals = geo.getNormals()\n\n # Create mesh functions over the cell facets\n faceSubdomains = MeshFunction(\"size_t\", mesh, geo._nDim-1)\n\n # Mark all facets of the domain as 0\n faceSubdomains.set_all(0)\n\n # Mark boundary faces for face elements\n for i in range(geo.getNoFaces()):\n class BndSubDomain(SubDomain):\n def inside(self, x, on_boundary):\n return near( geoNormals[i].dot(Point(x)-geo._points[geoBndPoints[i]]), 0.0 ) and on_boundary\n aSubDomain = BndSubDomain()\n label = i+1\n if hasattr(geo, 'facesMarkers'):\n label = geo.facesMarkers[i]\n aSubDomain.mark(faceSubdomains, label)\n \n # Save Dolfin XML format of the subdomains\n if 'outputXmlGz' in kwargs:\n File(kwargs['outputXmlGz']) << faceSubdomains\n \n # Save sub domains to VTK files\n if 'outputPvd' in kwargs:\n File(kwargs['outputPvd']) << faceSubdomains\n \n return faceSubdomains\n\ndef markBoundarySubdomains(mesh, boundaries, **kwargs):\n '''Mark the boundaries of a mesh given a geometry\n \n All interior faces are marked with zero\n \n boundaries is a dictionary {label: definition of boundary}\n '''\n \n bndSubdomains = MeshFunction(\"size_t\", mesh, mesh.geometry().dim()-1)\n bndSubdomains.set_all(0)\n \n for i in boundaries:\n class BndSubDomain(SubDomain):\n def inside(self, x, on_boundary):\n value = array([0.0])\n boundaries[i].eval(value, x)\n return (value==1.0) and on_boundary\n aux = BndSubDomain()\n aux.mark(bndSubdomains, i)\n \n # Save Dolfin XML format of the subdomains\n if 'outputXmlGz' in kwargs:\n File(kwargs['outputXmlGz']) << bndSubdomains\n \n # Save sub domains to VTK files\n if 'outputPvd' in kwargs:\n File(kwargs['outputPvd']) << bndSubdomains\n \n return bndSubdomains\n \n## If there exist dirichlet boundary\n#if hasDirichlet:\n# if os.path.isfile(dirichletPath):\n# dirichletSubdomain = MeshFunction(\"bool\", mesh, dirichletPath)\n# else:\n# # Mark faces\n# dirichletSubdomain.set_all(False)\n# class Aux(SubDomain):\n# def inside(self, x, on_boundary):\n# value = array([0.0])\n# physics.dirichletBnd.eval(value, x)\n# return (value==1.0) and on_boundary\n# aux = Aux()\n# aux.mark(dirichletSubdomain, True)\n# aux.mark(bndSubdomains, 0)","repo_name":"weslleyspereira/mhm_fenics","sub_path":"demos/meshes/geometry.py","file_name":"geometry.py","file_ext":"py","file_size_in_byte":4210,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"17"} +{"seq_id":"34803733954","text":"from django.conf.urls import url\nfrom . import views\n\nurlpatterns = [\n url(r'^$', views.index),\n url(r'^register_process$' , views.register_process),\n url(r'^login_process$' , views.login_process),\n url(r'^quotes$' , views.quotes),\n url(r'^quotes/(?P\\d+)$' , views.quotes),\n url(r'^logout$', views.logout),\n url(r'^add_my_quote_process$', views.add_my_quote_process),\n url(r'^add_my_fave/(?P\\d+)$', views.add_my_fave),\n url(r'^users/(?P\\d+)$', views.users),\n url(r'^remove_my_fave/(?P\\d+)$', views.remove_my_fave),\n]","repo_name":"marjansgithub/testing","sub_path":"apps/login/urls.py","file_name":"urls.py","file_ext":"py","file_size_in_byte":562,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"17"} +{"seq_id":"8357805862","text":"#OS - Crime Keys Creation\n#Author: Nic Gardin\n\nimport pandas as pd\nimport numpy as np\nimport time\n\n\ndef createCrimeDim():\n\n\tcrimeVan = pd.read_csv(\"/Users/nicgardin/Documents/2020_Classes_Master/DataScience/outputCSV/van_crimeDim/van_crimeDim.csv\", encoding=\"UTF-8\", names=[\"crimeCategory\", \"crimeSeverity\", \"reportedTime\", \"timeOfDay\", \"crimeStartTime\", \"crimeEndTime\", \"crimeDetails\"])\n\tcrimeDen = pd.read_csv(\"/Users/nicgardin/Documents/2020_Classes_Master/DataScience/outputCSV/den_crimeDim/den_crimeDim.csv\", encoding=\"UTF-8\")\n\tcrimeVan = crimeVan.drop_duplicates()\n\tcrimeDen = crimeDen.drop_duplicates()\n\tcrimeDim = crimeVan.append(crimeDen)\n\tcrimeDim = crimeDim.reset_index(drop=True)\n\tcrimeDim.index.names =['crimeID']\n\treturn crimeDim\n\n\ndef getCrimeKeysVan(df):\n\n\tstartTime = time.perf_counter()\n\tvanc = pd.read_csv(\"/Users/nicgardin/Documents/2020_Classes_Master/DataScience/crime_datasets/crimeVan.csv\", encoding=\"UTF-8\")\n\tcrimeKeys = pd.DataFrame(-1, index=np.arange(len(vanc)),columns=['crimeKey', 'isNighttime'])\n\n\t#1. for Van\n\tfor i in range(len(vanc)):\n\t\thour = vanc.iloc[i][\"HOUR\"]\n\t\tminute = vanc.iloc[i][\"MINUTE\"]\n\n\t\tif pd.isnull(hour) or pd.isnull(minute):\n\t\t\tcrimeKeys['crimeKey'].loc[i] = -1\n\t\t\tcrimeKeys['isNighttime'].loc[i] = -1\n\t\t\tcontinue\n\n\t\trepTime = str(int(hour)) + \":\" + str(int(minute))\n\t\tdetails = vanc.iloc[i][\"TYPE\"]\n\n\t\t#get specific van crime from crimeDim.csv\n\t\tsCrime = df.loc[(df['reportedTime'] == repTime) & (df['crimeDetails'] == details)]\n\n\t\tkey = sCrime['crimeID'].iloc[0]\n\t\tcrimeKeys.loc[i] = key\n\n\t\tisNight = sCrime['timeOfDay'].iloc[0]\n\n\t\tif (isNight==0) or (isNight == 3):\n\t\t\tcrimeKeys['isNighttime'].loc[i] = 1\n\t\telse:\n\t\t\tcrimeKeys['isNighttime'].loc[i] = 0\n\n\t\tif(i%10000 == 0):\n\t\t\t# endTime = time.perf_counter()\n\t\t\tprint(i)\n\t\t\tprint(repTime + \" \" + details + \" \" + str(key))\n\n\treturn crimeKeys\n\n\ndef getCrimeKeysDen(df):\n\n\tstartTimeCounter = time.perf_counter()\n\tdenc = pd.read_csv(\"/Users/nicgardin/Documents/2020_Classes_Master/DataScience/crime_datasets/crimeDen.csv\", encoding=\"UTF-8\")\n\tdenc.dropna(subset=['FIRST_OCCURRENCE_DATE'])\n\n\tdenc['REPORTED_DATE'] = pd.to_datetime(denc['REPORTED_DATE'], format='%m/%d/%Y %I:%M:%S %p')\n\tdenc['REPORTED_DATE'] = denc['REPORTED_DATE'].astype(str)\n\n\tcrimeKeys = pd.DataFrame(-1, index=np.arange(len(denc)),columns=['crimeKey', 'isNighttime'])\n\n\tdf.dropna(subset=['crimeStartTime'])\n\n\tfor i in range(len(denc)):\n\n\t\ttry:\n\t\t\treportedTime = denc.iloc[i][\"REPORTED_DATE\"]\n\t\t\tif pd.isnull(reportedTime):\n\t\t\t\tcontinue\n\n\t\t\tstartTime = denc.iloc[i]['FIRST_OCCURRENCE_DATE']\n\n\t\t\tstartTime = startTime.split(\" \")[0]\n\n\t\t\tstartTimeSpl = startTime.split(\"/\")\n\t\t\t#append leading 0s\n\t\t\tif (len(startTimeSpl[0]) == 1):\n\t\t\t\tstartTime = \"0\" + startTime\n\n\t\t\tif (len(startTimeSpl[1]) == 1):\n\t\t\t\tstartTime = startTime[0:3] + \"0\" + startTime[3:]\n\n\t\t\trepTime = reportedTime.split(\" \")[1]\n\t\t\trepTime = repTime[:-3]\n\t\t\tdetails = denc.iloc[i][\"OFFENSE_TYPE_ID\"]\n\n\t\t\t# print(repTime + \" \" + details + \" \" + startTime)\n\n\t\t\t#get specific crime from denCrimeDim.csv\n\t\t\t# if (pd.isnull((df.loc[df['crimeStartTime']]))):\n\t\t\t# \tcontinue\n\t\t\tsCrime = df.loc[(df['reportedTime'] == repTime) & (df['crimeStartTime'] == startTime) & (df['crimeDetails'] == details)]\n\n\t\t\tkey = sCrime['crimeID'].iloc[0]\n\t\t\tcrimeKeys.loc[i] = key\n\n\t\t\tisNight = sCrime['timeOfDay'].iloc[0]\n\t\t\tif pd.isnull(isNight):\n\t\t\t\tcontinue\n\n\t\t\tif (isNight==0) or (isNight == 3):\n\t\t\t\tcrimeKeys['isNighttime'].loc[i] = 1\n\t\t\telse:\n\t\t\t\tcrimeKeys['isNighttime'].loc[i] = 0\n\n\t\t\t# print(\"Row \" + str(i) + \" info: \" + repTime + \" \" + details + \" \" + startTime + \"\\nKey found: \" + str(key) + \"\\n\") # + \"\\nKey found: \" + str(key) + \"\\n\"\n\n\n\t\t\tif(i%20000 == 0):\n\t\t\t\tendTimeCounter = time.perf_counter()\n\t\t\t\tprint(endTimeCounter-startTimeCounter)\n\t\t\t\tprint(\"Row \" + str(i) + \" info: \" + repTime + \" \" + details + \" \" + startTime + \"\\nKey found: \" + str(key) + \"\\n\") # + \"\\nKey found: \" + str(key) + \"\\n\"\n\n\t\texcept:\n\t\t\tcontinue\n\n\treturn crimeKeys\n\n\nif __name__ == '__main__':\n\n\t# create crimeDim\n\tcrimeDim = createCrimeDim()\n\tcrimeDim.to_csv('/Users/nicgardin/Documents/2020_Classes_Master/DataScience/crimeDim/crimeDim.csv')\n\n\t# read crimeDim, select needed cols, split into van and den sets\n\tcrimeDim = pd.read_csv(\"/Users/nicgardin/Documents/2020_Classes_Master/DataScience/crimeDim/crimeDim.csv\", encoding=\"UTF-8\")\n\tcrimeDim = crimeDim[[\"crimeID\", \"reportedTime\", \"timeOfDay\", \"crimeStartTime\", \"crimeDetails\"]]\n\tcrimeDim = crimeDim.drop_duplicates()\n\tvanCrimeDim = crimeDim.head(11456)\n\tdenCrimeDim = crimeDim.tail(461699)\n\n\t# create and write vanCrimeKeys.csv\n\tvanCrimeKeys = getCrimeKeysVan(vanCrimeDim)\n\tvanCrimeKeys.to_csv('/Users/nicgardin/Documents/2020_Classes_Master/DataScience/newCrimeKeys/vanCrimeKeysTHREE.csv', index=False)\n\n\t# create and write denCrimeKeys.csv (SLOW)\n\tdenCrimeKeys = getCrimeKeysDen(denCrimeDim)\n\tdenCrimeKeys.to_csv('/Users/nicgardin/Documents/2020_Classes_Master/DataScience/newCrimeKeys/denCrimeKeys.csv', index=False)\n\n\t# append van and den key sets\n\tcrimeKeysDen = pd.read_csv(\"/Users/nicgardin/Documents/2020_Classes_Master/DataScience/newCrimeKeys/vanCrimeKeys.csv\", encoding=\"UTF-8\")\n\tcrimeKeysVan = pd.read_csv(\"/Users/nicgardin/Documents/2020_Classes_Master/DataScience/newCrimeKeys/crimeKeysDENV.csv\", encoding=\"UTF-8\")\n\tcrimeKeys = crimeDimVan.append(crimeDimDen)\n\tcrimeKeys.to_csv('/Users/nicgardin/Documents/2020_Classes_Master/DataScience/newCrimeKeys/crimeKeys.csv', index=False)\n","repo_name":"maxFredenburgh/CSI4142_Group16_CrimeDataProject","sub_path":"crimeKeysScript.py","file_name":"crimeKeysScript.py","file_ext":"py","file_size_in_byte":5475,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"17"} +{"seq_id":"70807709784","text":"import sys\nimport heapq\nsys.stdin = open(\"input.txt\", 'r')\ninput = sys.stdin.readline\nINF = sys.maxsize\n\nif __name__ == \"__main__\":\n v,e = map(int,input().split())\n k = int(input())\n graph = [[] for _ in range(v+1)]\n for _ in range(e):\n s,e,w = map(int,input().split())\n graph[s].append((w,e)) #가중치 목적지 노드 형식으로 저장 > 우선순위 힙 사용하기 위해서\n dp = [INF] *(v+1) #최소값을 업데이트 할 가중치 테이블\n heap = [] #힙 -> 최소값을 구할 때 시간을 줄여주기 위한 자료구조\n\n def dijkstra(start):\n dp[start] = 0 #dp를 다 INF로 초기화 해놨으니 처음에 가중치를 0으로 세팅한다.\n heapq.heappush(heap,(0,start)) #heap에 (가중치,도착점)으로 세팅한다 > 가중치로 최소힙 만들려고\n\n while heap: #모든 정점을 체크해준다.\n w,cur = heapq.heappop(heap) #가중치, 도착점\n if dp[cur] < w: #현재 도착점에 누적된 값보다 가중치가 크면 그냥 pass\n continue\n for ww,vv in graph[cur]: #현재 도착점과 연결된 값을 체크해준다.\n next_w = w + ww #시작점 ~ 도착점(w) ~ 새로운 도착점(ww) 으로 세팅하면 시작점에서 > 새로운 도착점으로 가는 방법이다.\n if dp[vv] > next_w: #현재 도착점으로 가는 가중치과 하나 거쳐서 가는 가중치 비교\n dp[vv] = next_w #더 작으면 변경하기 dp값 변경!\n heapq.heappush(heap,(next_w ,vv)) #최소힙에 새로운 도착점과 가중치를 넣어서 탐색 대상으로 넣어준다.\n dijkstra(k)\n for i in range(1,v+1): #IF\n print(\"INF\" if dp[i]==INF else dp[i]) #이렇게 안해주면 sys.maxsize 9223372036854775807 출력됨\n\n ","repo_name":"soyeong125/Algorithm","sub_path":"BaekJoon/1753.py","file_name":"1753.py","file_ext":"py","file_size_in_byte":1849,"program_lang":"python","lang":"ko","doc_type":"code","stars":0,"dataset":"github-code","pt":"17"} +{"seq_id":"4486094418","text":"import re\nfrom itertools import product\nfrom collections import Counter\n\n\ndef read_lines(fn):\n lines = [g for g in open(fn).read().split('\\n')]\n return lines\n\n\ndef step1(line, bitmask, mem):\n if 'mask' in line:\n bitmask = line[7:]\n return bitmask, mem\n else:\n mem_ind = int(re.search(r'mem\\[(\\d+)\\]', line).group(1))\n mem_val = '{0:b}'.format(int(line.split(' = ')[1])).zfill(36)\n write_mem = ''\n for m, v in zip(bitmask, mem_val):\n if m == 'X':\n write_mem += v\n else:\n write_mem += m\n mem[mem_ind] = int(write_mem, 2)\n return bitmask, mem\n\n\ndef gen_masked_inds(mem_ind, bitmask):\n inds = ''\n for m, v in zip(bitmask, mem_ind):\n if m in '1X':\n inds += m\n elif m == '0':\n inds += v\n n_x = Counter(bitmask)['X']\n inds = inds.replace('X', '{}')\n for x in product('01', repeat=n_x):\n yield inds.format(*x)\n\n\ndef step2(line, bitmask, mem):\n if 'mask' in line:\n bitmask = line[7:]\n return bitmask, mem\n else:\n mem_ind = re.search(r'mem\\[(\\d+)\\]', line).group(1)\n mem_ind = '{0:b}'.format(int(mem_ind)).zfill(36)\n mem_val = int(line.split(' = ')[1])\n\n for write_ind in gen_masked_inds(mem_ind, bitmask):\n mem[int(write_ind, 2)] = mem_val\n return bitmask, mem\n\n\ndef run_program(lines, part=1):\n mem = {}\n bitmask = ''.join(['X' for _ in range(36)])\n part_funcs = {1: step1, 2: step2}\n step = part_funcs[part]\n for line in lines:\n bitmask, mem = step(line, bitmask, mem)\n return sum([val for val in mem.values()])\n\n\n# Part 1\nlines = read_lines('14.txt')\nprint(f\"Part 1:\\t{run_program(lines, 1)}\")\n# Part 2\nlines = read_lines('14.txt')\nprint(f\"Part 2:\\t{run_program(lines, 2)}\")\n","repo_name":"elmolinoviejo/adventofcode","sub_path":"2020/14/14.py","file_name":"14.py","file_ext":"py","file_size_in_byte":1838,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"17"} +{"seq_id":"1477681723","text":"import streamlit as st\nfrom streamlit_chat import message\n\n# Setting page title and header\nst.set_page_config(page_title=\"Evernote Semenatic Search\", page_icon=\":robot_face:\")\nst.markdown(\"

Evernote AI Chatbot Powered by Apache NiFi using OpenAI, Pinecone & Langchain

\", unsafe_allow_html=True)\n\nimport requests\nimport re\n\n\nAPI_ENDPOINT = \"http://127.0.0.1:9898/evernotechatbot\"\n\n\n# Initialise session state variables\nif 'chat_history' not in st.session_state:\n st.session_state['chat_history'] = []\n\n\n# Sidebar - let user choose model, show total cost of current conversation, and let user clear the current conversation\nst.sidebar.title(\"Sidebar\")\ncounter_placeholder = st.sidebar.empty()\nclear_button = st.sidebar.button(\"Clear Conversation\", key=\"clear\")\n\n\n# reset everything\nif clear_button:\n st.session_state['chat_history'] = []\n\n\ndef generate_response(query, chat_history):\n\n # Convert the chat_history tuple array into a single string\\\n chat_history_string = None\n if chat_history:\n chat_history_string = ' '.join([f'(\"{item[0]}\", \"{item[1]}\")' for item in chat_history])\n\n\n\n params = {\n \"question\": query,\n \"chat_history\": chat_history_string\n }\n response = requests.post(API_ENDPOINT, params=params)\n response.raise_for_status()\n\n return response.text\n\ndef parse_response(response):\n\n if 'SOURCES' in response:\n\n answer, source = response.split('SOURCES', 1)\n print(\"Answer is: \" + answer)\n print(\"Source is: \" + source)\n\n pattern = r\"Notebook__(.*?)__Note__(.*?)__Id__(.*?)\\.enex\"\n matches = re.findall(pattern, source)\n\n # Create a list of formatted strings\n formatted_sources = []\n for match in matches:\n notebook_value = match[0]\n note_value = match[1]\n formatted_string = f\"Note: {note_value} (Notebook: {notebook_value}), \"\n formatted_sources.append(formatted_string)\n\n formatted_sources_string = ', '.join(formatted_sources)\n\n return {\"answer\": answer, \"source\":source , \"sources_parsed\": formatted_sources_string}\n else:\n return {\"answer\" : response, \"source\" : ''}\n\n\n\n\n# container for chat history\nresponse_container = st.container()\n# container for text box\ncontainer = st.container()\n\nwith container:\n with st.form(key='my_form', clear_on_submit=True):\n user_input = st.text_area(\"You:\", key='input', height=100)\n submit_button = st.form_submit_button(label='Send')\n\n if submit_button and user_input:\n chat_history = st.session_state['chat_history']\n response = generate_response(user_input, chat_history)\n chat_history.append((user_input, response))\n\n\nif st.session_state['chat_history']:\n with response_container:\n for index, tuple_items in enumerate(st.session_state['chat_history']):\n question = tuple_items[0]\n answer = tuple_items[1]\n answer_and_source = parse_response(answer)\n message(question, is_user=True, key=str(index) + '_user')\n message(answer_and_source['answer'], key=str(index))\n source = answer_and_source['source']\n # if source is not None and len(source) > 0 and source != ':' and question != 'What can you help with?' :\n if source is not None and len(source) > 0 and source != ':' :\n st.markdown(\"Evernote Source: \" + answer_and_source['sources_parsed'], unsafe_allow_html=True)\n\n\n\n\n\n","repo_name":"georgevetticaden/evernote-ai-chatbot","sub_path":"chat-ui/evernote-semantic-search-ui-v2i.py","file_name":"evernote-semantic-search-ui-v2i.py","file_ext":"py","file_size_in_byte":3503,"program_lang":"python","lang":"en","doc_type":"code","stars":10,"dataset":"github-code","pt":"17"} +{"seq_id":"40776354305","text":"from datetime import datetime as dt\nfrom datetime import timezone, timedelta\nfrom bs4 import BeautifulSoup as b\nimport requests as req\nimport sqlite3 as sql\n# lxml 라이브러리 인스톨 하기\n\nfrom .LOC_TO_XY import *\n\ndef get_now(): # 현재 시간을 필요한 포맷으로 반환\n # 데이터를 가져오는 시간에 따라 가장 최근 예보 데이터를 가져올 수 있도록 한다.\n now = dt.now(timezone(timedelta(hours=9)))\n date = now.date()\n time = now.time()\n\n date = date.strftime(\"%Y%m%d\")\n hour = time.strftime(\"%H\")\n minute = time.strftime(\"%M\")\n\n sf_hour = hour\n sn_hour = hour\n\n if int(minute) <= 20: sn_hour = f\"{int(sn_hour) - 1:02d}\"\n\n if int(minute) <= 55: sf_hour = f\"{int(sf_hour) - 1:02d}\"\n\n return date, sn_hour, sf_hour\n\ndef get_tomm():\n\n now = dt.now()\n\n tomm1 = now + timedelta(days=1) \n tomm2 = now + timedelta(days=2)\n \n tomm1 = tomm1.strftime(\"%Y년 %m월 %d일\")\n tomm2 = tomm2.strftime(\"%Y년 %m월 %d일\")\n\n return tomm1, tomm2 \n\n # gf_hour = 단기예보는 예보시간이 정해져있고 그 시간 + 10 분에 업데이트 되기에 업데이트 되기전이라면 전시간을 반환\n # sn_hour = 초단기 실황은 예보시간이 정각이고 + 10 분에 업데이트 되기에 업데이트 되기전이라면 시간을 -1 하여 반환\n # sf_hour = 초단기예보 예보시간은 단기예보나 초단기실황과 달리 정각이 아니기에 기준을 +35 분으로 잡아 따로 반환\n\n# cst --------> vFcst = 단기예보 / sFcst = 초단기예보 / sNcst = 초단기실황\n\ndef get_data(cst, ad_thr): # api에서 데이터 가져오기\n\n date, sn_time, sf_time = get_now()\n\n api_key = \"%2FsB%2B4nyywlmejmA0rBxb02w%2BxrxK3P17tIQb5iDWiPsMOB1Hzpm%2BvNDN%2BYg2pBtldu9aDkNHZ9N9KKGGgf6BCw%3D%3D\"\n\n address = \"\"\n x, y = 0, 0\n\n if type(ad_thr) == dict: # ip 주소로 조회 시 ad_thr 가 {'ip' : ip} 형식으로 들어옴\n\n lat, lng = ip_to_loc(ad_thr['ip']) # ip 주소에 따른 위도, 경도 값 받아오기\n address, x, y = loc_to_xy(lat, lng) # 주소, x, y 값 받아오기\n # 요청된 cst에 따라 api에서 가져오는 데이터가 다르도록 지정. \n elif type(ad_thr) == str: # 지역 주소로 조회 시 ad_thr 가 문자열로 들어옴\n\n x, y = ad_to_xy(ad_thr)\n\n if cst == \"vFcst\": url = f\"https://apis.data.go.kr/1360000/VilageFcstInfoService_2.0/getVilageFcst?serviceKey={api_key}&pageNo=1&numOfRows=1000&dataType=XML&base_date={date}&base_time=0500&nx={x}&ny={y}\"\n elif cst == \"sFcst\": url = f\"https://apis.data.go.kr/1360000/VilageFcstInfoService_2.0/getUltraSrtFcst?serviceKey={api_key}&pageNo=1&numOfRows=1000&dataType=XML&base_date={date}&base_time={sf_time + '30'}&nx={x}&ny={y}\"\n elif cst == \"sNcst\": url = f\"https://apis.data.go.kr/1360000/VilageFcstInfoService_2.0/getUltraSrtNcst?serviceKey={api_key}&pageNo=1&numOfRows=1000&dataType=XML&base_date={date}&base_time={sn_time + '00'}&nx={x}&ny={y}\"\n\n result = req.get(url, verify = False)\n soup = b(result.text, 'lxml')\n\n items = soup.find_all('item')\n\n lst = []\n\n for i in items:\n\n Date = i.find('basedate').get_text() # 예보 발표 날짜\n Time = i.find('basetime').get_text() # 예보 발표 시간\n category = i.find('category').get_text() # 예보 항목\n Value = \"\"\n\n if (cst == \"vFcst\") or (cst == \"sFcst\"): # 초단기예보, 단기예보에만 예보가 있기에 예보값 추출\n \n Date = i.find('fcstdate').get_text() # 예보 날짜\n Time = i.find('fcsttime').get_text() # 예보 시간\n Value = i.find('fcstvalue').get_text() # 예보 값\n \n elif cst == \"sNcst\": Value = i.find('obsrvalue').get_text()\n # 초단기실황은 따로 관측값 추출\n\n if (Value == '강수없음') or (Value == '적설없음'): Value = \"-\"\n # 강수없음, 적설없음은 - 로 표시\n\n temp = [Date, Time, [category, Value]] # 리스트 형식으로 저장\n\n lst.append(temp)\n\n return lst, address # 전체 리스트 반환\n\n\ndef data_to_DB(lst, cst): # 리스트 형식으로 들어온 데이터를 DB에 저장\n\n con = sql.connect(\"Weather_Data.db\") # DB 연결\n cmd = con.cursor()\n\n if cst == \"vFcst\": cst = \"VilageFcst\" # cst별 테이블 다르게\n elif cst == \"sFcst\": cst = \"SrtFcst\"\n elif cst == \"sNcst\": cst = \"SrtNcst\"\n \n query = f\"DELETE FROM {cst}\" # 이전 기록 초기화\n \n cmd.execute(query)\n cmd.fetchall()\n con.commit()\n\n for i in lst: # 리스트에서 하나씩 가져오면서 중복되지 않게 날짜/시간 넣기\n\n try:\n\n query = f'INSERT INTO {cst}(Datetime) VALUES (\"{i[0]} {i[1]}\")'\n\n cmd.execute(query)\n cmd.fetchall()\n con.commit()\n\n except: continue\n\n for i in lst: # 다시 리스트에서 하나씩 가져오면서 해당 날짜/시간 데이터 행의 항목 값 넣기\n\n query = f'UPDATE {cst} SET {i[2][0]} = \"{i[2][1]}\" WHERE Datetime = \"{i[0]} {i[1]}\"'\n \n if i[2][0].upper() == \"VEC\":\n\n vec_lst = ['N', 'NNE', 'NE', 'ENE', 'E', 'ESE', 'SE', 'SSE', 'S', 'SSW', 'SW', 'WSW', 'W', 'WNW', 'NW', 'NNW', 'N']\n vec = int((float(i[2][1]) + 22.5 * 0.5) / 22.5)\n\n idx = vec_lst[vec]\n query = f'UPDATE {cst} SET {i[2][0]} = \"{idx}\" WHERE Datetime = \"{i[0]} {i[1]}\"'\n\n if i[2][0].upper() == 'SKY':\n\n sky_lst = ['sunny', 'sunny', 'cloudy', 'cloudy', 'cloud']\n sky = int(i[2][1])\n \n idx = sky_lst[sky]\n query = f'UPDATE {cst} SET {i[2][0]} = \"{idx}\" WHERE Datetime = \"{i[0]} {i[1]}\"'\n\n if i[2][0].upper() == 'PTY':\n\n pty_lst = ['-', '비', '비/눈', '눈', '소나기', '빗방울', '빗방울/눈날림', '눈날림']\n pty = int(i[2][1])\n \n idx = pty_lst[pty]\n query = f'UPDATE {cst} SET {i[2][0]} = \"{idx}\" WHERE Datetime = \"{i[0]} {i[1]}\"'\n\n cmd.execute(query)\n cmd.fetchall()\n con.commit()","repo_name":"hello9721/Python_practice","sub_path":"MINI PROJECT/Weather/web/API_TO_DB.py","file_name":"API_TO_DB.py","file_ext":"py","file_size_in_byte":6607,"program_lang":"python","lang":"ko","doc_type":"code","stars":2,"dataset":"github-code","pt":"17"} +{"seq_id":"41188486519","text":"from typing import List\n\nfrom datagen import Trajectory\nfrom memup import UncertaintyDetector\nfrom .memup_trainer import load_model_from_generator_config\nimport torch\nimport numpy as np\n\nclass LegacyQRDQNDetector(UncertaintyDetector):\n \"\"\"\n This class allows to check if new code works with old uncertainty detector.\n\n \"\"\"\n def __init__(self, qrdqn_model, batch_size=1000):\n super(LegacyQRDQNDetector, self).__init__()\n self.model = qrdqn_model\n self.device = next(self.model.parameters()).device\n self.batch_size = batch_size\n\n @torch.no_grad()\n def make_estimate(self, trajectories: List[Trajectory]) -> List[List[float]]:\n uncertainties = []\n for t in trajectories:\n ep_unc = []\n obs = t.data['observation'][:-1]\n acts = t.data['action']\n returns = t.data['return']\n for t in range(0, len(t), self.batch_size):\n curr_unc = self.model.calculate_uncertainty(\n self.adapt_np(obs[t:t+self.batch_size]),\n self.adapt_acts(acts[t:t+self.batch_size]),\n returns,\n method='std'\n )\n ep_unc.extend(curr_unc)\n\n uncertainties.append(np.asarray(ep_unc))\n\n return uncertainties\n\n def adapt_np(self, obs_batch):\n return torch.tensor(obs_batch, dtype=torch.float, device=self.device)\n\n def adapt_acts(self, acts):\n #acts.argmax(1)\n return torch.tensor(acts, device=self.device)","repo_name":"griver/memup","sub_path":"rl/detector.py","file_name":"detector.py","file_ext":"py","file_size_in_byte":1539,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"17"} +{"seq_id":"1999504065","text":"from unittest.mock import patch\nfrom django.test import TestCase\nfrom users.tests.factories import UserFactory\nfrom rest_framework.response import Response\nfrom rest_framework.request import HttpRequest\nfrom amuse.tokens import otp_token_generator\nfrom amuse.tests.cookie_factory import (\n generate_test_client_otp_cookie,\n generate_test_client_access_cookie,\n generate_test_client_refresh_cookie,\n)\nfrom django.test import RequestFactory\nfrom rest_framework.exceptions import AuthenticationFailed\nfrom amuse.api.base.authentication import (\n authenticate_from_otp_cookie,\n JWTCookieAuthentication,\n)\n\n\nclass TestJWTCookieAuthenticationTestCase(TestCase):\n @patch('amuse.tasks.zendesk_create_or_update_user')\n def setUp(self, mock) -> None:\n self.user = UserFactory()\n self.response = Response()\n self.request = HttpRequest()\n\n @patch('rest_framework.request.HttpRequest.get_signed_cookie')\n def test_authenticate_from_otp_cookie(self, mock_fnc):\n mock_fnc.return_value = otp_token_generator.make_token(self.user.pk)\n request = self.request\n u = authenticate_from_otp_cookie(request)\n assert u.pk == self.user.pk\n\n @patch('rest_framework.request.HttpRequest.get_signed_cookie')\n def test_authenticate_from_otp_cookie_failed(self, mock_fnc):\n mock_fnc.return_value = \"wrong-value\"\n request = self.request\n u = authenticate_from_otp_cookie(request)\n assert u is None\n\n @patch('rest_framework.request.HttpRequest.get_signed_cookie')\n def test_authenticate_from_otp_cookie_user_not_found(self, mock_fnc):\n mock_fnc.return_value = otp_token_generator.make_token(user_id=1000000000)\n request = self.request\n u = authenticate_from_otp_cookie(request)\n assert u is None\n\n def test_authenticate_from_access_cookie(self):\n request = RequestFactory()\n request.cookies = generate_test_client_access_cookie(user_id=self.user.pk)\n u, t = JWTCookieAuthentication().authenticate(request.request())\n assert u.pk == self.user.pk\n\n def test_authenticate_from_access_cookie_missing_user(self):\n request = RequestFactory()\n request.cookies = generate_test_client_access_cookie(user_id=1000000000)\n with self.assertRaises(AuthenticationFailed):\n JWTCookieAuthentication().authenticate(request.request())\n\n def test_authenticate_from_access_cookie_missing_cookie(self):\n request = RequestFactory()\n assert JWTCookieAuthentication().authenticate(request.request()) is None\n\n def test_authenticate_from_access_cookie_wrong_token(self):\n request = RequestFactory()\n request.cookies = generate_test_client_refresh_cookie(user_id=self.user.pk)\n assert JWTCookieAuthentication().authenticate(request.request()) is None\n\n def test_authenticate_from_access_cookie_user_deactivated(self):\n user = UserFactory(is_active=False)\n request = RequestFactory()\n request.cookies = generate_test_client_access_cookie(user_id=user.id)\n with self.assertRaises(AuthenticationFailed):\n JWTCookieAuthentication().authenticate(request.request())\n","repo_name":"aamychen/amuse-django-codepipeline-test","sub_path":"src/amuse/tests/test_api/test_authentication.py","file_name":"test_authentication.py","file_ext":"py","file_size_in_byte":3192,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"17"} +{"seq_id":"34917773814","text":"# n진수 -> 10진수\nint('101', 2)\nint('20', 3)\n\n# 10진수 -> 2, 8, 16진수\nbin(16)[2:]\noct(16)[2:]\nhex(16)[2:]\n\n#10진수 -> n진수\ndef notation(n, q):\n result = ''\n\n while n:\n n, mod = divmod(n, q)\n result = str(mod) + result\n\n return result\n\nnotation(6, 3)\n \n#재귀함수 이용\ndef convert(n, base):\n T = \"0123456789ABCDEF\"\n q, r = divmod(n, base)\n if q == 0:\n return T[r]\n else:\n return convert(q, base) + T[r]","repo_name":"pilkyuchoi/programmers","sub_path":"level2/진법변환.py","file_name":"진법변환.py","file_ext":"py","file_size_in_byte":472,"program_lang":"python","lang":"ko","doc_type":"code","stars":1,"dataset":"github-code","pt":"17"} +{"seq_id":"25635692177","text":"import torch\nimport torch.nn.functional as F\nfrom torch import nn\n\nfrom .pooler import RoIAlign\nfrom .utils import Matcher, BalancedPositiveNegativeSampler, roi_align\nfrom .box_ops import BoxCoder, box_iou, process_box, nms\n\n\ndef fastrcnn_loss(class_logit, box_regression, label, regression_target):\n classifier_loss = F.cross_entropy(class_logit, label)\n\n N, num_pos = class_logit.shape[0], regression_target.shape[0]\n box_regression = box_regression.reshape(N, -1, 4)\n box_regression, label = box_regression[:num_pos], label[:num_pos]\n box_idx = torch.arange(num_pos, device=label.device)\n\n box_reg_loss = F.smooth_l1_loss(box_regression[box_idx, label], regression_target, reduction='sum') / N\n\n return classifier_loss, box_reg_loss\n\n\ndef maskrcnn_loss(mask_logit, proposal, matched_idx, label, gt_mask):\n matched_idx = matched_idx[:, None].to(proposal)\n roi = torch.cat((matched_idx, proposal), dim=1)\n \n M = mask_logit.shape[-1]\n gt_mask = gt_mask[:, None].to(roi)\n mask_target = roi_align(gt_mask, roi, 1., M, M, -1)[:, 0]\n\n idx = torch.arange(label.shape[0], device=label.device)\n mask_loss = F.binary_cross_entropy_with_logits(mask_logit[idx, label], mask_target)\n return mask_loss\n \n\nclass RoIHeads(nn.Module):\n def __init__(self, box_roi_pool, box_predictor,\n fg_iou_thresh, bg_iou_thresh,\n num_samples, positive_fraction,\n reg_weights,\n score_thresh, nms_thresh, num_detections):\n super().__init__()\n self.box_roi_pool = box_roi_pool\n self.box_predictor = box_predictor\n \n self.mask_roi_pool = None\n self.mask_predictor = None\n \n self.proposal_matcher = Matcher(fg_iou_thresh, bg_iou_thresh, allow_low_quality_matches=False)\n self.fg_bg_sampler = BalancedPositiveNegativeSampler(num_samples, positive_fraction)\n self.box_coder = BoxCoder(reg_weights)\n \n self.score_thresh = score_thresh\n self.nms_thresh = nms_thresh\n self.num_detections = num_detections\n self.min_size = 1\n \n def has_mask(self):\n if self.mask_roi_pool is None:\n return False\n if self.mask_predictor is None:\n return False\n return True\n \n def select_training_samples(self, proposal, target):\n gt_box = target['boxes']\n gt_label = target['labels']\n proposal = torch.cat((proposal, gt_box))\n \n iou = box_iou(gt_box, proposal)\n pos_neg_label, matched_idx = self.proposal_matcher(iou)\n pos_idx, neg_idx = self.fg_bg_sampler(pos_neg_label)\n idx = torch.cat((pos_idx, neg_idx))\n \n regression_target = self.box_coder.encode(gt_box[matched_idx[pos_idx]], proposal[pos_idx])\n proposal = proposal[idx]\n matched_idx = matched_idx[idx]\n label = gt_label[matched_idx]\n num_pos = pos_idx.shape[0]\n label[num_pos:] = 0\n \n return proposal, matched_idx, label, regression_target\n \n def fastrcnn_inference(self, class_logit, box_regression, proposal, image_shape):\n N, num_classes = class_logit.shape\n \n device = class_logit.device\n pred_score = F.softmax(class_logit, dim=-1)\n box_regression = box_regression.reshape(N, -1, 4)\n \n boxes = []\n labels = []\n scores = []\n for l in range(1, num_classes):\n score, box_delta = pred_score[:, l], box_regression[:, l]\n\n keep = score >= self.score_thresh\n box, score, box_delta = proposal[keep], score[keep], box_delta[keep]\n box = self.box_coder.decode(box_delta, box)\n \n box, score = process_box(box, score, image_shape, self.min_size)\n \n keep = nms(box, score, self.nms_thresh)[:self.num_detections]\n box, score = box[keep], score[keep]\n label = torch.full((len(keep),), l, dtype=keep.dtype, device=device)\n \n boxes.append(box)\n labels.append(label)\n scores.append(score)\n\n results = dict(boxes=torch.cat(boxes), labels=torch.cat(labels), scores=torch.cat(scores))\n return results\n \n def forward(self, feature, proposal, image_shape, target):\n if self.training:\n proposal, matched_idx, label, regression_target = self.select_training_samples(proposal, target)\n \n box_feature = self.box_roi_pool(feature, proposal, image_shape)\n class_logit, box_regression = self.box_predictor(box_feature)\n \n result, losses = {}, {}\n if self.training:\n classifier_loss, box_reg_loss = fastrcnn_loss(class_logit, box_regression, label, regression_target)\n losses = dict(roi_classifier_loss=classifier_loss, roi_box_loss=box_reg_loss)\n else:\n result = self.fastrcnn_inference(class_logit, box_regression, proposal, image_shape)\n \n if self.has_mask():\n if self.training:\n num_pos = regression_target.shape[0]\n \n mask_proposal = proposal[:num_pos]\n pos_matched_idx = matched_idx[:num_pos]\n mask_label = label[:num_pos]\n \n '''\n # -------------- critial ----------------\n box_regression = box_regression[:num_pos].reshape(num_pos, -1, 4)\n idx = torch.arange(num_pos, device=mask_label.device)\n mask_proposal = self.box_coder.decode(box_regression[idx, mask_label], mask_proposal)\n # ---------------------------------------\n '''\n \n if mask_proposal.shape[0] == 0:\n losses.update(dict(roi_mask_loss=torch.tensor(0)))\n return result, losses\n else:\n mask_proposal = result['boxes']\n \n if mask_proposal.shape[0] == 0:\n result.update(dict(masks=torch.empty((0, 28, 28))))\n return result, losses\n \n mask_feature = self.mask_roi_pool(feature, mask_proposal, image_shape)\n mask_logit = self.mask_predictor(mask_feature)\n \n if self.training:\n gt_mask = target['masks']\n mask_loss = maskrcnn_loss(mask_logit, mask_proposal, pos_matched_idx, mask_label, gt_mask)\n losses.update(dict(roi_mask_loss=mask_loss))\n else:\n label = result['labels']\n idx = torch.arange(label.shape[0], device=label.device)\n mask_logit = mask_logit[idx, label]\n\n mask_prob = mask_logit.sigmoid()\n result.update(dict(masks=mask_prob))\n \n return result, losses","repo_name":"Okery/PyTorch-Simple-MaskRCNN","sub_path":"pytorch_mask_rcnn/model/roi_heads.py","file_name":"roi_heads.py","file_ext":"py","file_size_in_byte":6864,"program_lang":"python","lang":"en","doc_type":"code","stars":251,"dataset":"github-code","pt":"17"} +{"seq_id":"14560394586","text":"from collections import deque\n\ngame_map = [\n [\"#\", \"#\", \"#\", \"#\", \"#\"],\n [\"#\", \".\", \".\", \"B\", \"#\"],\n [\"#\", \".\", \"#\", \".\", \"#\"],\n [\"#\", \"R\", \"O\", \".\", \"#\"],\n [\"#\", \".\", \".\", \".\", \"#\"],\n [\"#\", \"#\", \"#\", \"#\", \"#\"],\n]\ndr = [-1, 0, 1, 0]\ndc = [0, 1, 0, -1]\n\n\ndef move_until_to_wall_or_hole(r, c, d, game_map):\n move_count = 0\n\n while game_map[r + dr[d]][c + dc[d]] != '#' and game_map[r][c] != 'O':\n r += dr[d]\n c += dc[d]\n move_count += 1\n\n return r, c, move_count\n\n\ndef is_available_to_take_out_only_red_marble(game_map):\n n = len(game_map)\n m = len(game_map[0])\n queue = deque()\n visited = [[[[False] * m for _ in range(n)] for _ in range(m)] for _ in range(n)]\n red_row, red_col, blue_row, blue_col = -1, -1, -1, -1\n\n for i in range(1, n - 1):\n for j in range(1, m - 1):\n if game_map[i][j] == 'R':\n red_row, red_col = i, j\n elif game_map[i][j] == 'B':\n blue_row, blue_col = i, j\n\n queue.append((red_row, red_col, blue_row, blue_col, 1))\n visited[red_row][red_col][blue_row][blue_col] = True\n\n while queue:\n red_row, red_col, blue_row, blue_col, try_count = queue.popleft()\n\n if try_count > 10:\n break\n\n for i in range(4):\n new_red_row, new_red_col, red_move_count = move_until_to_wall_or_hole(red_row, red_col, i, game_map)\n new_blue_row, new_blue_col, blue_move_count = move_until_to_wall_or_hole(blue_row, blue_col, i, game_map)\n\n if game_map[new_blue_row][new_blue_col] == 'O':\n continue\n elif game_map[new_red_row][new_red_col] == 'O':\n return True\n else:\n if new_red_row == new_blue_row and new_red_col == new_blue_col:\n if red_move_count > blue_move_count:\n new_red_row -= dr[i]\n new_red_col -= dc[i]\n else:\n new_blue_row -= dr[i]\n new_blue_col -= dc[i]\n\n if not visited[new_red_row][new_red_col][new_blue_row][new_blue_col]:\n visited[new_red_row][new_red_col][new_blue_row][new_blue_col] = True\n queue.append((new_red_row, new_red_col, new_blue_row, new_blue_col, try_count + 1))\n\n return False\n\n\nprint(is_available_to_take_out_only_red_marble(game_map)) # True 를 반환해야 합니다\n\ngame_map = [\n [\"#\", \"#\", \"#\", \"#\", \"#\", \"#\", \"#\", \"#\", \"#\", \"#\"],\n [\"#\", \".\", \"O\", \".\", \".\", \".\", \".\", \"R\", \"B\", \"#\"],\n [\"#\", \"#\", \"#\", \"#\", \"#\", \"#\", \"#\", \"#\", \"#\", \"#\"]\n]\nprint(\"정답 = False / 현재 풀이 값 = \", is_available_to_take_out_only_red_marble(game_map))\n\n\ngame_map = [\n [\"#\", \"#\", \"#\", \"#\", \"#\", \"#\", \"#\"],\n [\"#\", \".\", \".\", \"R\", \"#\", \"B\", \"#\"],\n [\"#\", \".\", \"#\", \"#\", \"#\", \"#\", \"#\"],\n [\"#\", \".\", \".\", \".\", \".\", \".\", \"#\"],\n [\"#\", \"#\", \"#\", \"#\", \"#\", \".\", \"#\"],\n [\"#\", \"O\", \".\", \".\", \".\", \".\", \"#\"],\n [\"#\", \"#\", \"#\", \"#\", \"#\", \"#\", \"#\"]\n]\nprint(\"정답 = True / 현재 풀이 값 = \", is_available_to_take_out_only_red_marble(game_map))\n","repo_name":"jhs851/algorithm","sub_path":"sparta/week_5/05_is_available_to_take_out_only_red_marble.py","file_name":"05_is_available_to_take_out_only_red_marble.py","file_ext":"py","file_size_in_byte":3131,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"17"} +{"seq_id":"34864538797","text":"\nfor tc in range(1, int(input())+1):\n N, M = map(int, input().split()) # 화덕크기 피자 갯수\n pizza_cheese = list(map(int, input().split()))\n oven = []\n\n for i in range(N):\n oven.append((i+1, pizza_cheese[i])) # 피자번호는 1번부터 시작 (피자번호와 치즈 튜플로 묶음)\n\n next_pizza = N\n # last_pizza = -1\n\n while len(oven) > 1: # 모든 피자가 녹을 때까지 하지 않고 피자 하나 남으면 끝내도 됨\n # while oven:\n num, cheese = oven.pop(0) # num: 피자번호, cheese: 남은 치즈\n\n cheese //= 2\n # last_pizza = num\n # 치즈의 양이 남아있다면 다시 화덕에 넣는다. 맨 뒷순서로\n if cheese:\n oven.append((num, cheese))\n else:\n if next_pizza < M: # 피자 남았다면\n oven.append((next_pizza+1, pizza_cheese[next_pizza]))\n next_pizza += 1\n\n # print('#{} {}'.format(tc, last_pizza))\n print('#{} {}'.format(tc, oven[0][0]))","repo_name":"oihater95/Study_CS_Code","sub_path":"Code/Python/algorithm/Queue_practice/SWEA_5099_피자굽기_sol.py","file_name":"SWEA_5099_피자굽기_sol.py","file_ext":"py","file_size_in_byte":1022,"program_lang":"python","lang":"ko","doc_type":"code","stars":2,"dataset":"github-code","pt":"17"} +{"seq_id":"1350218848","text":"#!/usr/local/bin/python3\nimport numpy as np\nfrom standardize import standard\nfrom buildData import buildData as bd\nfrom mpp import MPP\nimport validation as vd\nimport evaluation as ev\nfrom pca import pca\nfrom fld import fld\n\ndef MPP_Validate(dataName, grpName, folds, case = 3, priors = None, trans = None):\n\t\"\"\"\n\t\tparams: dataName := file with the data set\n\t\t\t\tgrpName := file with the different groupings\n\t\t\t\tfolds\t\t := number of folds\n\t\t\t\ttrans := transformation function to do dimensionality reduction\n\t\t\t\tcase\t\t := case of the discriminant function to use\n\t\t\t\t\t\t\tdefaulted to case 3\n\t\t\t\tpriors := the prior probabilities for the two classes. Defaulted to None\n\t\tobjective: performs cross validation using mpp as classifier\n\t\t\t\twith the discriminant function cases\n\t\treturns: a dictionary with performance evaluation data \n\t\"\"\"\n\tvalid = vd.Validate(grpName, folds)\n\tdata, labels = bd(dataName)\n\tresults = [] #stores tuples: (list_predicted, list_groundTruth)\n\tfor i in range(valid.getFoldCount()):\n\t\tprint(\"Iteration %d\" % i)\n\t\t#get the train and test indices of the data set\n\t\ttestIndex, trainIndex = valid.getTest(i), valid.getTrain(i)\n\t\t#build the test set and test labels\n\t\ttestSet, testLabels = data[testIndex, :], labels[testIndex]\n\t\t#build the train set and training labels\n\t\ttrainSet, trainLabels = data[trainIndex, :], labels[trainIndex]\n\t\t#if the data is to be transformed\n\t\tif trans is not None:\n\t\t\tif trans is fld:\n\t\t\t\ttmp = trans(trainSet, trainLabels)\n\t\t\t\ttrainSet = np.matmul(trainSet, tmp).reshape(-1,1).astype(np.float64)\n\t\t\t\ttestSet = np.matmul(testSet, tmp).reshape(-1,1).astype(np.float64)\n\t\t\telse:\n\t\t\t\ttmp = trans(trainSet).transpose()\n\t\t\t\ttrainSet = np.matmul(trainSet, tmp)\n\t\t\t\ttestSet = np.matmul(testSet, tmp)\n\t\t#standardize the training and test set\n\t\ttrainSet, testSet = standard(trainSet, testSet)\n\t\t#classify test set and add it to the results list\n\t\tresults.append((MPP(trainSet, testSet, trainLabels, case, priors), testLabels))\n\t\n\tresults = ev.buildConfusionMatrices(results)\t\n\tresults = ev.normalizeConfMat(results)\n\tresults = ev.getAvgProbMatrix(results)\n\tprint(results)\n\tresults = ev.rocData(results)\n\tprint(\"Case %i Accuracy: %f\" % (case, results[\"Acc\"]))\n\treturn results\t\n\t\t\nif __name__ == \"__main__\":\n\tMPP_Validate(\"../data/EEG_dropcat.csv\", \"../data/folds.grp\", 23, 1)\n","repo_name":"Wyrine/finalProject-PatternRec","sub_path":"code/src/mppValidate.py","file_name":"mppValidate.py","file_ext":"py","file_size_in_byte":2312,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"17"} +{"seq_id":"28386897749","text":"#!/usr/bin/env python3\n\nfrom os import path\nfrom src.HoleFinder import HoleAnalyzer\nfrom typing import List, Dict\n\nif __name__ == '__main__':\n data_path = path.join(path.dirname(__file__), 'data')\n h = HoleAnalyzer(data_path, 30)\n \n output_path = path.join(path.dirname(__file__), 'output')\n h.output_csv(path.join(output_path, 'output.csv'))\n h.output_json(path.join(output_path, 'output.json'))\n h.print_table()\n\n","repo_name":"SoroushGit/SummerCup2023-Tournament-Runner","sub_path":"HoleAnalyzer/main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":436,"program_lang":"python","lang":"en","doc_type":"code","stars":3,"dataset":"github-code","pt":"17"} +{"seq_id":"41927305877","text":"print('**** conversor de temperatura °C x °F ****')\ntempconv = 0\nescala = ''\nwhile True:\n temp = float(input('Informe a temperatura:'))\n escala = str(input('Em qual escala está esta temperatura? use F ou C: ')).strip().upper()\n while escala not in 'FC':\n print('\\033[31mERRO! digite F ou C.\\033[m')\n escala = str(input('Em qual escala está esta temperatura? use F ou C: ')).strip().upper()\n if escala == 'F':\n tempconv = 5 * ((temp - 32) / 9)\n print(f'O valor em gráus Celsius é: {tempconv:.2f}°C')\n elif escala == 'C':\n tempconv = (1.8 * temp) + 32\n print(f'O valor em Fahrenheit é: {tempconv:.2f}°F')\n print()\n resp = str(input('Do you wish to continue, type it S/N')).strip().upper()\n while resp not in 'SN':\n print('\\033[31mInvalid answer, type it S ou N\\033[m')\n resp = str(input(\"Do you wish to continue, S/N\"))\n if resp == 'N':\n break\nprint()\nprint('\\033[33mFinish... By TecVander.')\n","repo_name":"tecvieira/pythonbrasilExerc","sub_path":"EstSeq009.py","file_name":"EstSeq009.py","file_ext":"py","file_size_in_byte":991,"program_lang":"python","lang":"pt","doc_type":"code","stars":0,"dataset":"github-code","pt":"17"} +{"seq_id":"38473063506","text":"'''\nRemeber when you create this pkg you have to use --dependencies rclpy ae_custom_interface_cpp because you are using the msg that you built in that pkg\n\nRecall that interfaces can currently only be defined in CMake packages. \nIt is possible, however, to have Python libraries and nodes in CMake packages (using ament_cmake_python),\nso you could define interfaces and Python nodes together in one package\n\nRemeber when you build a message the build system creates header files as well as the python files so you can import you message in python environment too\n\n\nI asked chatGPT whats in ament_index folder?\nThe ament_index folder is a directory created by ROS 2 build system (Colcon) during the build process, \nwhich contains an index of all the installed packages and their resources. \nThe purpose of the ament_index is to provide a way for packages to find resources in other packages. \nFor example, when a ROS 2 package depends on another package that provides custom messages, \nthe ament_index is used to locate the installed message package and the message files.\nThe ament_index folder is typically located in the install directory of a ROS 2 workspace, \nand contains a set of YAML files that describe the resources provided by each installed package, \nincluding messages, services, actions, and launch files. The ament_index also includes an interfaces \nsubdirectory that contains the generated Python code for custom message types, as well as a set of index files \nthat provide a mapping between message type names and the Python modules that define them.\nThe ament_index folder contains a collection of files that are used for package discovery and management in ROS 2.\nSome of the files in this folder are empty by default, as they are intended to be populated with package information by \nthe build system during package compilation and installation. For example, the resources.ros2-.cmake file in the \nament_index/resource_index/ directory is empty by default, but it will be populated with the paths to the installed resources \nof each package during the build process.\nOther files, such as the resource_index.yaml file in the ament_index/resource_index/ directory, may be populated \nwith default values or manually edited to include package information.\n\nand interestingly enough there is also ament_index in the local workspace in the share folder of your Ros2Basics WS. so maybe you should add the path to the setup.py \n\n'''\n\nimport rclpy\nfrom rclpy.node import Node\nfrom ae_custom_interface_cpp.msg import Person\n\nclass CustomPub(Node):\n def __init__(self):\n super().__init__(\"PersonPublisherNode\")\n self.pub_ = self.create_publisher(Person,\"/person\" , 10)\n self.timer_ = self.create_timer(0.2 , self.TimerCallback)\n self.msg = Person()\n \n \n \n \n\n def TimerCallback(self):\n self.msg.age = 10.0\n self.msg.name = str(\"soheil\")\n self.get_logger().info(\"Age %f\" %self.msg.age)\n self.pub_.publish(self.msg)\n def onShutDown(self):\n self.get_logger().info(\"Shuting down!\")\n\n\ndef main(args=None):\n rclpy.init(args=args)\n node = CustomPub()\n rclpy.get_default_context().on_shutdown(node.onShutDown) # pause the program execution, waits for a request to kill the node (ctrl+c)\n try:\n rclpy.spin(node)\n except KeyboardInterrupt:\n pass\n node.destroy_node()\n rclpy.shutdown()\n\nif __name__ == '__main__':\n main()\n\n","repo_name":"sohail70/Ros2Basics","sub_path":"ae_custom_interface_py/ae_custom_interface_py/person_publisher.py","file_name":"person_publisher.py","file_ext":"py","file_size_in_byte":3465,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"17"} +{"seq_id":"15823161209","text":"import numpy as np\r\nimport pylab as plt\r\n\r\n\r\ndef plot_image(img, mask=None, ax=None, vertical=False, title=''):\r\n img = img.copy()\r\n img = np.log10(img + 1e-16)\r\n if not ax:\r\n fig, ax = plt.subplots(figsize=(30, 30), facecolor='w')\r\n \r\n cmap = plt.cm.YlOrBr_r\r\n cmap.set_bad('green', 1.)\r\n \r\n if isinstance(mask, np.ndarray):\r\n if not (img.shape == mask.shape):\r\n raise RuntimeError('mask must have the same shape. IMG shape {}, MASK shape {}'.format(img.shape, mask.shape))\r\n \r\n img = np.ma.masked_where(mask, img)\r\n \r\n n0, n1 = img.shape\r\n if n0 > n1:\r\n img = img.T\r\n \r\n if vertical:\r\n img = img.T\r\n \r\n ax.imshow(img, cmap=cmap)\r\n ax.set_title(title)\r\n \r\n \r\ndef plot_dashboard(img, mask=None, ncols=6, vertical=True):\r\n img = np.asarray(img).copy()\r\n \r\n if isinstance(mask, type(None)):\r\n mask = img.copy() * 0\r\n else:\r\n mask = np.asarray(mask).copy()\r\n if not (img.shape == mask.shape):\r\n raise RuntimeError('mask must have the same shape. IMG shape {}, MASK shape {}'.format(img.shape, mask.shape))\r\n \r\n\r\n for i in range(0, len(img), ncols):\r\n fig, axs = plt.subplots(nrows=1, ncols=ncols, facecolor='w', figsize=(10,5), sharey=True)\r\n axs = np.asarray(axs).ravel()\r\n \r\n for j in range(ncols):\r\n idx = i + j\r\n if idx >= len(img):\r\n axs[j].axis('off')\r\n continue\r\n plot_image(img[idx], mask=mask[idx], ax=axs[j], vertical=vertical, title=idx)\r\n plt.show()","repo_name":"kdanilovskiy/image-interpretation","sub_path":"src/plot_model.py","file_name":"plot_model.py","file_ext":"py","file_size_in_byte":1633,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"17"} +{"seq_id":"8947550875","text":"#math 함수 사용\nimport math\n\nt = int(input())\nfor _ in range(t):\n n, m = map(int,input().split())\n bridge = math.factorial(m) // (math.factorial(n) * math.factorial(m - n))\n print(bridge)\n#math 함수를 사용할수 없는 경우 직접 구현\n\n#def factorial(n):\n# num = 1\n# for i in range(1, n+1):\n# num *= i\n# return num\n\n\n#T = int(input())\n\n#for _ in range(T):\n# n, m = map(int, input().split())\n# bridge = factorial(m) // (factorial(n) * factorial(m - n))\n# print(bridge)\n","repo_name":"calmkeen/algorithm_study","sub_path":"baekjoon/Sliver/다리놓기.py","file_name":"다리놓기.py","file_ext":"py","file_size_in_byte":515,"program_lang":"python","lang":"ko","doc_type":"code","stars":0,"dataset":"github-code","pt":"17"} +{"seq_id":"72624077784","text":"# https://leetcode.com/problems/number-of-islands/\n\nclass Solution:\n def numIslands(self, grid: List[List[str]]) -> int:\n n, m = len(grid), len(grid[0])\n islandCount = 0\n\n def DFS(row, col):\n # Out of Bounds or already visited\n if row < 0 or row >=n or col < 0 or col >= m or grid[row][col] != \"1\":\n return\n\n # Mark as visited\n grid[row][col] = \"0\"\n\n # visit four directions\n DFS(row-1, col) # UP\n DFS(row+1, col) # DOWN\n DFS(row, col-1) # LEFT\n DFS(row, col+1) # RIGHT\n\n # find the islands\n for row in range(0, n):\n for col in range(0, m):\n # un-visited Island found\n if grid[row][col] == \"1\":\n islandCount += 1\n DFS(row, col) # Visit all the continous islands\n\n return islandCount\n","repo_name":"VishnuThangaraj/Leetcode-Solutions","sub_path":"Python/0151-0200/200. Number of Islands.py","file_name":"200. Number of Islands.py","file_ext":"py","file_size_in_byte":921,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"17"} +{"seq_id":"7818716408","text":"# Create your views here.\nfrom django.http import HttpResponse\nfrom django.shortcuts import render\nfrom rest_framework import viewsets\n\nfrom . import models, serializer\nfrom rest_framework.response import Response\nfrom rest_framework import status\nfrom . import constants, util\n\nclass UserViewSet(viewsets.ModelViewSet):\n queryset = models.User.objects.all()\n serializer_class = serializer.UserSerializer\n\nclass GroupViewSet(viewsets.ViewSet):\n \n def list(self, request):\n queryset = models.Group.objects.all()\n resp = serializer.GroupSerializer(queryset, many=True)\n return Response(resp.data)\n\n def create(self, request):\n reqParams = constants.Group[constants.Create]\n missingParams = util.checkRequired(reqParams, request.data)\n if len(missingParams) > 0:\n return Response({\n 'error' : 'missing params',\n 'params' : missingParams}, \n status.HTTP_400_BAD_REQUEST)\n\n\n group = models.Group(name=request.data['name'])\n group.save()\n\n ledgerEntry = []\n users = models.User.objects.all()\n for lender in users:\n for borrower in users:\n if lender != borrower:\n ledgerEntry.append(models.Ledger(\n group=group,\n lender=lender,\n borrower=borrower,\n amount=0\n ))\n models.Ledger.objects.bulk_create(ledgerEntry)\n return Response(status.HTTP_200_OK)\n\nclass EventViewSet(viewsets.ViewSet):\n \n def list(self, request):\n queryset = models.Event.objects.all()\n resp = serializer.EventSerializer(queryset, many=True)\n return Response(resp.data)\n\n def create(self, request):\n group = models.Group.objects.get(id=request.data['group'])\n event = models.Event(\n name=request.data['name'],\n type=request.data['type'],\n group=group\n )\n event.save()\n\n contribs = []\n for user in request.data['user']:\n userObj = models.User.objects.get(id=user.get['id'])\n\n contribs.append(\n models.Contributions(\n event=event,\n user=userObj,\n amount=user['amount'],\n percent= user[models.Event.Percent] if models.Event.Percent in user else 0,\n fixed=user[models.Event.Fixed] if models.Event.Fixed in user else 0\n )\n )\n\n # get Shares\n shares = group.getShares(event, contribs)\n for index, contrib in enumerate(contribs):\n contrib.share = shares[index]\n\n models.Contributions.objects.bulk_create(contribs)\n group.UpdateLedger(event, contribs, shares)\n\n return Response(status.HTTP_200_OK)\n\n\n def destroy(self, request, pk=None):\n \n event = models.Event.objects.get(id=pk)\n contribs = models.Contributions.objects.filter(event=event)\n event.group.UpdateLedger(event, contribs, revert=True)\n event.delete()\n return Response(status.HTTP_200_OK)\n\nclass TransactionsViewSet(viewsets.ViewSet):\n \n def list(self, request):\n user = models.User.objects.get(id=request.query_params['user'])\n data = models.Contributions.objects.filter(user=user)\n resp = serializer.ContributionsSerializer(data, many=True)\n return Response(resp.data)\n\nclass SettleViewSet(viewsets.ViewSet):\n \n def list(self, request):\n \n ledger = models.Ledger.objects.filter(\n lender=request.query_params['lender'],\n borrower=request.query_params['borrower'],\n group=request.query_params['group']\n ).first()\n ledger.amount = ledger.amount - int(request.query_params['amount'])\n ledger.save()\n return Response(status.HTTP_200_OK)\n \nclass SummaryViewSet(viewsets.ViewSet):\n \n def list(self, request):\n data = models.Ledger.objects.filter(group=request.query_params['group'])\n resp = serializer.LedgerSerializer(data, many=True)\n return Response(resp.data)\n\nclass AddUserViewSet(viewsets.ViewSet):\n \n def list(self, request):\n import ipdb; ipdb.set_trace()\n group = models.Group.objects.filter(id=request.query_params['group']).first()\n user = models.User.objects.filter(id=request.query_params['user']).first()\n \n group.users.add(user)\n\n return Response(status.HTTP_200_OK)","repo_name":"utkarsharma2/Sliptwise","sub_path":"spliwise/ledger/views.py","file_name":"views.py","file_ext":"py","file_size_in_byte":4589,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"17"} +{"seq_id":"8376278189","text":"#\n#This code functions as intended\n#\nclass Morse():\n import time\n\n def __int__(self,input=[],output=[]):\n self.input = input\n self.output = result\n\n def translate_input(self):\n temp_letter = []\n temp_word = []\n letters = {\n (\"dot\", \"dash\") : \"a\",\n (\"dash\", \"dot\", \"dot\", \"dot\") : \"b\",\n (\"dash\", \"dot\", \"dash\", \"dot\") : \"c\",\n (\"dash\", \"dot\", \"dot\") : \"d\",\n (\"dot\",) : \"e\",\n (\"dot\", \"dot\", \"dash\", \"dot\") : \"f\",\n (\"dash\", \"dash\", \"dot\") : \"g\",\n (\"dot\", \"dot\", \"dot\", \"dot\") : \"h\",\n (\"dot\", \"dot\") : \"i\",\n (\"dot\", \"dash\", \"dash\", \"dash\") : \"j\",\n (\"dash\", \"dot\", \"dash\") : \"k\",\n (\"dot\", \"dash\", \"dot\", \"dot\") : \"l\",\n (\"dash\", \"dash\") : \"m\",\n (\"dash\", \"dot\") : \"n\",\n (\"dash\", \"dash\", \"dash\") : \"o\",\n (\"dot\", \"dash\", \"dash\", \"dot\") : \"p\",\n (\"dash\", \"dash\", \"dot\", \"dash\") : \"q\",\n (\"dot\", \"dash\", \"dot\") : \"r\",\n (\"dot\", \"dot\", \"dot\") : \"s\",\n (\"dash\") : \"t\",\n (\"dot\", \"dot\", \"dash\") : \"u\",\n (\"dot\", \"dot\", \"dot\", \"dash\") : \"v\",\n (\"dot\", \"dash\", \"dash\") : \"w\",\n (\"dash\", \"dot\", \"dot\", \"dash\") : \"x\",\n (\"dash\", \"dot\", \"dash\", \"dash\") : \"y\",\n (\"dash\", \"dash\", \"dot\", \"dot\") : \"z\"\n }\n\n while len(self.input) > 0:\n while not self.input[0] == \"eow\" and len(self.input) > 0:\n if not self.input[0] == \"eol\":\n temp_letter.append(self.input.pop(0))\n else:\n temp_letter_tuple = tuple(temp_letter)\n temp_word.append(letters[temp_letter_tuple])\n self.input.pop(0)\n temp_letter = []\n word = ''.join(temp_word)\n temp_word = []\n self.output.append(word)\n self.input.pop(0)\n return word\n\n def output_result(self):\n import sys\n if not sys.warnoptions:\n import warnings\n warnings.simplefilter(\"ignore\")\n import Language_Translate\n english_text = ' '.join(self.output)\n final_output = Language_Translate.translate_text(english_text)\n return final_output\n\n def get_letter_input(self, time_units):\n if time_units == 1:\n input.append( \"dot\" )\n elif time_units == 3:\n input.append( \"dash\" )\n\n def get_space_input(self, time_units):\n if time_units == 3:\n input.append( \"eol\" )\n elif time_units == 7:\n input.append( \"eow\" )\n","repo_name":"alexrrobbins/HackPSU-Spring-2019","sub_path":"Morse_Translate.py","file_name":"Morse_Translate.py","file_ext":"py","file_size_in_byte":2562,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"17"} +{"seq_id":"24377640962","text":"import torch\nfrom torch import nn, einsum\n\nfrom einops import rearrange, repeat\nfrom einops.layers.torch import Rearrange\n\ndef pair(t):\n return t if isinstance(t, tuple) else (t, t)\n\n\nclass PreNorm(nn.Module):\n def __init__(self, dim, function):\n super().__init__()\n self.norm = nn.LayerNorm(dim) \n self.function = function \n\n def forward(self, x):\n return self.function(self.norm(x))\n\n\nclass FeedForward(nn.Module):\n def __init__(self, dim, hidden_dim, dropout = 0.0):\n super().__init__()\n self.net = nn.Sequential(\n nn.Linear(dim, hidden_dim),\n nn.GELU(), \n nn.Dropout(dropout), \n nn.Linear(hidden_dim, dim), \n nn.Dropout(dropout)\n )\n \n def forward(self, x):\n return self.net(x)\n\nclass Attention(nn.Module):\n def __init__(self, dim, heads, dim_head, dropout = 0.0):\n super().__init__()\n all_head_size = heads * dim_head \n project_out = not (heads == 1 and dim_head == dim)\n\n self.heads = heads \n self.scale = dim_head ** -0.5 \n\n self.softmax = nn.Softmax(dim = -1)\n self.to_qkv = nn.Linear(dim, all_head_size * 3, bias = False)\n\n self.to_out = nn.Sequential(\n nn.Linear(all_head_size, dim),\n nn.Dropout(dropout)\n ) if project_out else nn.Identity() \n\n def forward(self, x):\n qkv = self.to_qkv(x).chunk(3, dim = -1)\n #(batch, heads * dim_head) -> (batch, all_head_size)\n q, k, v = map(lambda t: rearrange(t, 'b n (h d) -> b h n d', h = self.heads), qkv)\n \n dots = torch.matmul(q, k.transpose(-1, -2)) * self.scale \n\n atten = self.softmax(dots)\n\n out = torch.matmul(atten, v)\n out = rearrange(out, 'b h n d -> b n (h d)')\n return self.to_out(out)\n\nclass Transformer(nn.Module):\n def __init__(self, dim, depth, heads, dim_head, mlp_dim, dropout = 0.0):\n super().__init__()\n self.layers = nn.ModuleList([])\n for _ in range(depth):\n self.layers.append(nn.ModuleList([\n PreNorm(dim, Attention(dim, heads, dim_head, dropout)), \n PreNorm(dim, FeedForward(dim, mlp_dim, dropout))\n ]))\n def forward(self, x):\n for attention, feedforward in self.layers:\n x = attention(x) + x \n x = feedforward(x) + x \n return x\n\nclass FixedPositionalEncoding(nn.Module):\n def __init__(self, embedding_dim, max_length=768):\n super(FixedPositionalEncoding, self).__init__()\n\n pe = torch.zeros(max_length, embedding_dim)\n position = torch.arange(0, max_length, dtype=torch.float).unsqueeze(1)\n div_term = torch.exp(\n torch.arange(0, embedding_dim, 2).float()\n * (-torch.log(torch.tensor(10000.0)) / embedding_dim)\n )\n pe[:, 0::2] = torch.sin(position * div_term)\n pe[:, 1::2] = torch.cos(position * div_term)\n pe = pe.unsqueeze(0).transpose(0, 1)\n self.register_buffer('pe', pe)\n\n def forward(self, x):\n x = x + self.pe[: x.size(0), :]\n return x\n\n\nclass LearnedPositionalEncoding(nn.Module):\n def __init__(self, embedding_dim, seq_length):\n super(LearnedPositionalEncoding, self).__init__()\n self.seq_length = seq_length\n self.position_embeddings = nn.Parameter(torch.zeros(1, seq_length, embedding_dim)) #8x\n\n def forward(self, x, position_ids=None):\n position_embeddings = self.position_embeddings\n# print(x.shape, self.position_embeddings.shape)\n return x + position_embeddings\n","repo_name":"itruonghai/SegTransVAE","sub_path":"models/Transformer.py","file_name":"Transformer.py","file_ext":"py","file_size_in_byte":3608,"program_lang":"python","lang":"en","doc_type":"code","stars":6,"dataset":"github-code","pt":"17"} +{"seq_id":"6415959519","text":"import random\n\nimport mock\nimport pytest\n\nfrom app import app\n\n\n@pytest.fixture\ndef mock_computations(monkeypatch):\n mocked_computations = {\n \"id123\": mock.MagicMock(),\n \"id345\": mock.MagicMock(),\n }\n monkeypatch.setattr(\"app.ACTIVE_COMPUTATIONS\", mocked_computations)\n return mocked_computations\n\n\n@pytest.fixture\ndef mock_render_template():\n with mock.patch(\"app.render_template\") as mocked_render:\n yield mocked_render\n\n\ndef test_home_get(mock_render_template, mock_computations):\n with app.test_client() as client:\n response = client.get(\"/\")\n assert response.status_code == 200\n mock_render_template.assert_called_once()\n mock_call = mock_render_template.call_args_list.pop()\n assert mock_call.args == (\"home.html\",)\n assert list(mock_call.kwargs.get(\"computations\")) == list(mock_computations.values())\n\n\n@mock.patch(\"app.base64.b64encode\")\ndef test_status(mock_base64, mock_computations, mock_render_template):\n c_id = random.choice(list(mock_computations.keys()))\n mock_base64.return_value = \"some_bytes_as_b_64\".encode()\n\n with app.test_client() as client:\n response = client.get(f\"/{c_id}\")\n assert response._status_code == 200\n\n mock_render_template.assert_called_once()\n mock_render_template.assert_called_with(\n \"status.html\", computation=mock_computations[c_id], image_bytes=\"some_bytes_as_b_64\"\n )\n\n\ndef test_status_404():\n with app.test_client() as client:\n response = client.get(\"/non_existant_id}\")\n assert response._status_code == 404\n","repo_name":"jonasbrauer/messaging-demo","sub_path":"web/tests/test_routes.py","file_name":"test_routes.py","file_ext":"py","file_size_in_byte":1575,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"17"} +{"seq_id":"15603813131","text":"import requests\nfrom bs4 import BeautifulSoup\n\nuserName = input(\"If You don't have Internet this program will automatically shutDown\\nEnter CodeChef UserName: \")\n\n\nwhile(True):\n url = \"https://www.codechef.com/users/\"+userName\n html = requests.get(url)\n \n soup = BeautifulSoup(html.text,'html.parser')\n title = str(soup.title.string)\n orTitle=title.strip()\n\n if(str(orTitle) ==\"Competitive Programming | Participate & Learn | CodeChef\"):\n print(\"Please Enter a valid username!!\\n\\n\")\n userName = input(\"\\n(If want to quit enter q else provide valid username) UserName: \")\n if(userName=='q'):\n break\n else:\n print(\"You have entered a valid username!!\")\n #find all list element and parse them\n lis=soup.find_all('li')\n for li in lis:\n if(li.label!=None):\n if(li.span!=None and (li.label.string)!=\"Country:\" and (li.label.string)!=\"Username:\"):\n print(str(li.label.string)+\" \"+str(li.span.string))\n if(str(li.label.string)==\"Country:\"):\n print(str(li.label.string)+\" \"+str(li.span.span.string))\n if(str(li.label.string)==\"Username:\"):\n print(\"Username: \"+userName)\n\n #Getting User-Rating:\n temp = str(soup.find_all(\"div\",class_='rating-number'))\n ntemp =[]\n ntemp+=temp\n rating=''\n if(len(ntemp)==39):\n newLis = ntemp[28:32]\n rating = ''.join(newLis)\n elif(len(ntemp)==36):\n rating='0'\n \n print(\"Your rating is: \"+rating)\n userName = input(\"\\n(If want to quit enter q else provide valid username) UserName: \")\n if(userName=='q' or userName=='Q'):\n break\n else:\n print(\"Continuing...\\n\")\n \n\n","repo_name":"amigo564/CodeChef_Details","sub_path":"CodeChef_DetailsViaUsername.py","file_name":"CodeChef_DetailsViaUsername.py","file_ext":"py","file_size_in_byte":1838,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"17"} +{"seq_id":"20498655491","text":"#!/usr/bin/env python3\n# -*- coding: utf-8 -*-\n\"\"\"\nCreated on Wed Nov 17 09:21:47 2021\n\n@author: muzian\n\"\"\"\n\nimport glob\nimport os,shutil\nfrom time import sleep\nfrom bs4 import BeautifulSoup as bs\n\n#清空文件夹\ndef emptydir(dirname):\n if os.path.isdir(dirname): #如果文件夹存在,则删除资料夹\n shutil.retree(dirname)\n sleep(2) #必要延迟,避免出错\n os.mkdir(dirname) #建立文件夹\n \n#分类标签标记处\nclasses = ['1','2','3']\n \nprint('Start Building Training Data')\nemptydir('yolodata') #建立训练资料夹\nimgfiles = glob.glob('xxxxxxx\\\\yyyyyyy\\\\*.png') #读取图形文件\n\n#复制图形文件\nfor fimg in imgfiles:\n fname = fimg.split('\\\\')[-1] #获取文件名称\n shutil.copyfile(fimg,'yolodata\\\\' + fname) #复制文件\n\n#转换PascalVOC格式至Yolo格式\nlbfiles = glob.glob('xxxx\\\\yyyyyy\\\\*.xml') #获取已标记的文件\nfor flb in lbfiles:\n fxml = open(flb)\n content = fxml.read()\n sp = bs(content,'html.parser') #转换为BeautifulSoup格式\n imgW = float(sp.find('width').text) #图形宽度\n imgH = float(sp.find('height').text) #图形高度\n objs = sp.find_all('object')\n out = ''\n \n for obj in objs:\n name = obj.find('name').text #标记\n xmin = float(obj.find('xmin').text) #左上角x坐标\n ymin = float(obj.find('ymin').text) #左上角y坐标\n xmax = float(obj.find('xmax').text) #右下角x坐标\n ymax = float(obj.find('ymax').text) #右下角y坐标\n x = (xmin + (xmax - xmin)/2)/imgW #中心点x坐标比例\n y = (ymin + (ymax - ymin)/2)/imgH #中心点y坐标比例\n w = (xmax - xmin)/imgW #图形宽度比例\n h = (ymax - ymin)/imgH #图形高度比例\n out += str(classes.index(name)) + '' + str(x) + '' + str(y) + '' + str(w) + '' + str(h) + '\\n'\n fname = flb.replace('vocdata\\\\annotations', 'yolodata').replace('.xml','.txt') #存档路径\n ftxt = open(fname,'w')\n ftxt.write(out) #写入存档\n \nfxml.close()\nftxt.close()\nprint('===Building Training Data Success===')\n","repo_name":"muzian666/Yolo-Model-for-Don-t-Strave-together","sub_path":"PascalVOC2Yolo.py","file_name":"PascalVOC2Yolo.py","file_ext":"py","file_size_in_byte":2098,"program_lang":"python","lang":"zh","doc_type":"code","stars":13,"dataset":"github-code","pt":"17"} +{"seq_id":"71169360983","text":"\nfrom sklearn.linear_model import LinearRegression\nfrom sklearn.metrics import mean_squared_error\nfrom math import sqrt\n\n\nclass HoltSmoothing(object):\n \"\"\"\n Holt Smoothing that smoothes over level by a factor of alpha.\n Parameters\n ----------\n alpha: float, required, default=0.1\n smoothing constant alpha,\n Methods\n ----------\n initialize():\n fit():\n predict():\n score():\n\n Notes\n -----\n This class is an example of coding to an interface, it implements the\n standard sklearn fit, predict, score interface.\n \"\"\"\n\n def __init__(self):\n pass\n\n def initialize(self, pretrain, label):\n \"\"\"\n Takes in a dataset and initializes first data point in simple\n exponential smoothing.\n Parameters\n ---------\n pretrain : dataset\n label: object, required\n Label of the column containing \n \"\"\"\n X=pretrain.index\n y=pretrain[label]\n lin_model = LinearRegression()\n lin_model.fit(X,y)\n\n level = lin_model.intercept_\n trend = lin_model.coef_\n t = 1\n a_hat_zero = float(t* trend + level)\n b_hat_zero = float(trend)\n first_forecast = a_hat_zero + b_hat_zero\n return first_forecast\n\n def fit_predict(self, pretrain, train, alpha, pred_n):\n \"\"\"\n Fit linear model.\n Parameters\n ----------\n train :\n alpha: float, required, default=0.1\n smoothing constant alpha,\n pred_n:\n Number of predictions\n Returns\n -------\n result :\n \"\"\"\n result = [series[0]] # first value is same as series\n lin_model = LinearRegression()\n lin_model.fit(X, y)\n\n level = lin_model.intercept_\n trend = lin_model.coef_\n for n in range(1, len(series)+1):\n if n == 1:\n level, trend = series[0], series[1] - series[0]\n if n >= len(series): # we are forecasting\n value = result[-1]\n else:\n value = series[n]\n last_level, level = level, alpha*value + (1-alpha)*(level+trend)\n trend = beta*(level-last_level) + (1-beta)*trend\n result.append(level+trend)\n return result\n### old code\n result = []\n result.append(self.initialize(pretrain))\n for n in range(1, pred_n):\n result.append(alpha * train[n] + (1 - alpha) * result[n-1])\n return result\n\n def predict(self, X, y, sample_weight=None):\n \"\"\"\n Fit linear model.\n Parameters\n ----------\n X : numpy array or sparse matrix of shape [n_samples,n_features]\n Training data\n y : numpy array of shape [n_samples, n_targets]\n Target values. Will be cast to X's dtype if necessary\n sample_weight : numpy array of shape [n_samples]\n Individual weights for each sample\n .. versionadded:: 0.17\n parameter *sample_weight* support to LinearRegression.\n Returns\n -------\n self : returns an instance of self.\n \"\"\"\n pass\n\n\n def score(self, pretrain, train, test, alpha, pred_n):\n \"\"\"Return RMSE score on new data.\n Parameters\n ----------\n test: A series of true values.\n \"\"\"\n result = self.fit_predict(pretrain, train, alpha, pred_n)\n rms = sqrt(mean_squared_error(test, result))\n return rms\n","repo_name":"fabryandrea/dsi-project","sub_path":"Holt_class.py","file_name":"Holt_class.py","file_ext":"py","file_size_in_byte":3476,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"17"} +{"seq_id":"21568476736","text":"#!/usr/bin/env python3\n# -*- coding: utf-8 -*-\n\"\"\"\nCreated on Wed Mar 15 16:03:11 2023\n\n@author: johnmorgan\n\"\"\"\n\ndef min_minutes_to_rot(grid):\n rotten = []\n good = 0\n for row_index, row in enumerate(grid):\n for col_index, val in enumerate(row):\n if val == 2:\n rotten += [[row_index, col_index]]\n elif val == 1:\n good += 1\n minutes = 0\n while rotten and good > 0:\n newly_rotten = []\n for bad in rotten:\n if bad[0] > 0:\n if grid[bad[0] - 1][bad[1]] == 1:\n grid[bad[0] - 1][bad[1]] = 2\n newly_rotten.append([bad[0] - 1, bad[1]])\n good -= 1\n if bad[0] < len(grid) - 1:\n if grid[bad[0] + 1][bad[1]] == 1:\n grid[bad[0] + 1][bad[1]] = 2\n newly_rotten.append([bad[0] + 1, bad[1]])\n good -= 1\n if bad[1] > 0:\n if grid[bad[0]][bad[1] - 1] == 1:\n grid[bad[0]][bad[1] - 1] = 2\n newly_rotten.append([bad[0], bad[1] - 1])\n good -= 1\n if bad[1] < len(grid[0]) - 1:\n if grid[bad[0]][bad[1] + 1] == 1:\n grid[bad[0]][bad[1] + 1] = 2\n newly_rotten.append([bad[0], bad[1] + 1])\n good -= 1\n rotten = newly_rotten\n minutes += 1\n if good == 0:\n return minutes\n return -1\n\ngrid = [[2,1,1],[1,1,0],[0,1,1]]\nprint(min_minutes_to_rot(grid))\n","repo_name":"johntmorgan/coding_coursework_public","sub_path":"python_practice_problems_2/41_challenge_problems/rotting_oranges.py","file_name":"rotting_oranges.py","file_ext":"py","file_size_in_byte":1561,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"17"} +{"seq_id":"16924823806","text":"#coding=utf-8\n'''\nCreated on Jan 10, 2017\n\n@author: Felix\n'''\nfrom collections import defaultdict\nimport getopt\nimport itertools\nimport json\nimport logging\nimport multiprocessing.dummy\nimport os\nimport sys\nimport time\n\nfrom db import DB\nfrom storage.es import ES\nfrom computation.hive import Hive\nfrom computation.presto import Presto\nfrom elasticsearch.exceptions import NotFoundError\nfrom analysis_generator import ALL_ANALYSIS\n\nclass ETLEngine(object):\n '''ETL execution engine'''\n def __init__(self, **kwargs):\n logging.info('init engine...')\n \n self.cylinder_num = 4\n self.db = DB()\n self.to_update = kwargs.get('update', False)\n self.specify_date = kwargs.get('specify_date', None)\n self.delete = kwargs.get('delete', False)\n self.no_insert = kwargs.get('no_insert', False)\n self.specify_report = kwargs.get('specify_report', [])\n self.oldversion = kwargs.get('oldversion', False)\n self.bothversion = kwargs.get('bothversion', False)\n self.__init_context()\n self.__init_storage_engine()\n self.__init_compute_engine()\n self.__init_computations()\n self.__init_report_units()\n self.result_buffer = []\n \n def __init_context(self):\n context = dict()\n \n if self.specify_date:\n today_time = time.mktime(time.strptime(self.specify_date,'%Y-%m-%d'))\n else:\n today_time = time.time()-86400\n \n localtime_today = time.localtime(today_time)\n context['today'] = time.strftime('%Y-%m-%d', localtime_today)\n \n self.context = context\n \n def __init_storage_engine(self):\n storage_engine_info = defaultdict(list)\n storage_engine_settings = self.db.get_storage_engine_settings()\n today_str = str(self.context.get('today'))\n condition = {\"query\":{\"match\": {\n \"computation_ds\": today_str\n }\n }\n }\n\n if self.specify_report:\n condition = {\"query\": {\"bool\": {\"must\": [{ \"terms\": { \"refer\": self.specify_report } },{ \"match\": { \"computation_ds\": today_str } }]}}}\n \n for storage_engine_setting in storage_engine_settings:\n stype = storage_engine_setting.stype\n setype = storage_engine_setting.setype\n \n if setype == 'ELASTICSEARCH':\n storage = ES(storage_engine_setting)\n if self.to_update or self.delete:\n storage.delete(conditions=condition)\n if self.delete:\n sys.exit()\n else:\n try:\n get_result = storage.get(conditions=condition)\n except NotFoundError:\n get_result = None\n if get_result:\n print('data in {0} has exist, if you want to overwrite it, you must provide the update argu'.format(self.context['today']))\n sys.exit()\n \n storage_engine_info[stype].append(storage)\n self.storage_engine_info = storage_engine_info\n \n def __init_compute_engine(self):\n computation_engine_info = dict()\n computation_engine_settings = self.db.get_computation_engine_settings()\n \n for computation_engine_setting in computation_engine_settings:\n ctype = computation_engine_setting.ctype\n \n if ctype == 'HIVE':\n compute = Hive(computation_engine_setting)\n elif ctype == 'PRESTO':\n compute = Presto(computation_engine_setting)\n \n computation_engine_info[computation_engine_setting.id] = compute\n self.computation_engine_info = computation_engine_info\n \n def __init_computations(self):\n computation_info = defaultdict(list)\n computation_settings = self.db.get_computation_settings()\n \n for computation_setting in computation_settings:\n layer = computation_setting.layer\n computation_info[layer].append(computation_setting)\n self.computation_info = computation_info\n\n def __init_report_units(self):\n report_unit_list = list()\n report_unit_settings = self.db.get_report_unit_settings()\n \n for report_unit_setting in report_unit_settings:\n report_unit_list.append(report_unit_setting)\n self.report_unit_list = report_unit_list\n \n def _worker(self, computation):\n engine_id = computation.engine_id\n sql_template = computation.template # the computation template, default sql\n output = computation.output\n \n if sql_template != 'select': # if sql is 'select', skip it\n if (not output) and (not self.no_insert):\n sql = sql_template.format(**self.context) # render the computation template\n print('/n--------------------------\\n' + sql + '\\n-----------------------------\\n')\n # logging.info('worker: ' + sql)\n engine_object = self.computation_engine_info.get(engine_id) # get engine object\n results = engine_object.execute(sql = sql) # execute will start a new subprocess to carry out the workload, so it's thread-safe\n \n if output:\n refer = computation.refer\n if (not self.specify_report) or (refer in self.specify_report):\n dimension = computation.dimension\n dimension = json.loads(dimension)\n dimension.sort()\n if not dimension:\n dimension = ['matrix_token']\n \n dimension_num = len(dimension)\n grouping_sets_list = []\n grouping_sets_list += dimension\n if dimension_num > 1:\n if dimension_num > 3:\n dimension_num = 3\n for i in range(2, dimension_num+1):\n grouping_sets_list += list(itertools.combinations(dimension,i))\n group_by_str = ','.join(dimension)\n grouping_sets_str = str(grouping_sets_list).replace('[','(').replace(']',')').replace('\\'','')\n \n self.context['group_by'] = group_by_str\n self.context['grouping_sets'] = grouping_sets_str\n \n as_others = \"grouping__id AS unit_name,'{today}' AS computation_ds,\"\n as_value = 'AS value,'\n as_ds = 'AS ds, count(1),'\n \n as_dimension_list = []\n for each_dimension in dimension:\n if each_dimension == 'matrix_token':\n as_dimension_list.append('matrix_token AS product_id')\n elif each_dimension == 'ds':\n pass\n else:\n as_dimension_list.append('{0} AS {0}'.format(each_dimension))\n \n dimension_str = ','.join(as_dimension_list)\n as_others = as_others + dimension_str\n \n self.context['as_others'] = as_others\n self.context['as_value'] = as_value\n self.context['as_ds'] = as_ds\n \n output_conf = json.loads(output)\n if 'ds' in dimension:\n tmplist = []\n for i in dimension:\n if i != 'ds':\n tmplist.append(i)\n column_names = ['ds', 'value', 'unit_name', 'computation_ds'] + tmplist\n else:\n column_names = ['ds', 'value', 'unit_name', 'computation_ds'] + dimension\n column_names = ['product_id' if x == 'matrix_token' else x for x in column_names]\n name_type_mapping = output_conf\n \n sql = sql_template.format(**self.context).format(**self.context) # render the computation template\n print('\\n=========='+refer+'===========\\n' + sql + '\\n=========================\\n')\n # logging.info('worker: ' + sql)\n engine_object = self.computation_engine_info.get(engine_id) # get engine object\n results = engine_object.execute(sql = sql)\n \n if results:\n for result in results:\n result = result.strip() # clear the heading and tailing blank spaces\n if result:\n result_items = result.split('\\t') # split tsv output\n result_items.pop(1)\n name_data_mapping = dict(zip(column_names, result_items))\n tmpmap = name_data_mapping.copy()\n for resultkey in tmpmap.keys():\n resultvalue = tmpmap[resultkey]\n if resultvalue == 'NULL':\n name_data_mapping.pop(resultkey)\n \n for resultkey in name_data_mapping.keys():\n resultvalue = name_data_mapping[resultkey]\n field_type = name_type_mapping.get(resultkey, 'str')\n if field_type == 'str':\n name_data_mapping[resultkey] = str(resultvalue)\n elif field_type == 'int':\n name_data_mapping[resultkey] = float(resultvalue)\n elif field_type == 'date':\n name_data_mapping[resultkey] = str(resultvalue)\n else:\n pass\n \n name_data_mapping['refer'] = refer\n intstr = name_data_mapping.get('unit_name')\n binstr = bin(int(intstr)).replace('0b','')\n \n if len(binstr) < len(dimension):\n binstr = '0'*(len(dimension)-len(binstr)) + binstr\n binstr = ''.join(reversed(binstr))\n if 'ds' not in dimension:\n unitname_list = ['ds']\n else:\n unitname_list = []\n binstr_index = 0\n for hasornot in binstr:\n if hasornot == '1':\n unitname_list.append(dimension[binstr_index])\n binstr_index += 1\n unitname_list = ['product_id' if x == 'matrix_token' else x for x in unitname_list]\n unitname_list.sort()\n unit_name = '_'.join(unitname_list)\n name_data_mapping['unit_name'] = unit_name\n \n self.result_buffer.append(name_data_mapping)\n else: # if no result,not put it\n pass\n else:\n print('★★★★★ '+ refer +' ERROR:' + sql)\n \n def _worker_by_sqlgenerator(self, analysis):\n sql_template = analysis.analysis_sql().replace('\\n',' ')\n self.context['computation_ds'] = self.context['today']\n sql = sql_template.format(**self.context)\n \n dimensions = analysis.analysis_dimensions\n output_consts = analysis.analysis_output_consts\n output_dimensions = analysis.analysis_output_dimensions\n output_metrics = analysis.analysis_output_metrics\n column_names_init = output_dimensions + output_metrics\n \n to_run = False\n for output_metric in output_metrics:\n if not self.specify_report:\n to_run = True\n elif output_metric in self.specify_report and output_metric != 'dummy':\n to_run = True\n \n if to_run:\n '''此处要获取engine_object要修改'''\n tmp = list(self.computation_engine_info.keys())[0]\n engine_object = self.computation_engine_info.get(tmp)\n print('\\n--------------------------\\n' + sql + '\\n-----------------------------\\n')\n results = engine_object.execute(sql = sql)\n if results:\n for result in results:\n column_names = []\n column_names = [x for x in column_names_init]\n result = result.strip() # clear the heading and tailing blank spaces\n if result:\n result_items = [str(x) for x in result.split('\\t')] # split tsv output\n name_data_mapping = dict(zip(column_names, result_items))\n if output_consts: # if has consts configration, add it into result\n for key in output_consts.keys():\n name_data_mapping[key] = output_consts[key].format(**self.context)\n name_data_mapping.pop('dummy')\n column_names.remove('dummy')\n \n # build unit_name\n intstr = name_data_mapping.pop('gid')\n column_names.remove('gid')\n binstr = bin(int(intstr)).replace('0b','')\n \n if len(binstr) < len(dimensions):\n binstr = '0'*(len(dimensions)-len(binstr)) + binstr\n binstr = ''.join(reversed(binstr))\n if 'ds' not in dimensions:\n unitname_list = ['ds']\n else:\n unitname_list = []\n binstr_index = 0\n for hasornot in binstr:\n if hasornot == '1':\n unitname_list.append(dimensions[binstr_index])\n binstr_index += 1\n unitname_list = [x for x in unitname_list]\n unitname_list.sort()\n unit_name = '_'.join(unitname_list)\n \n # build refer\n common_column_names = []\n common_column_names = column_names + [x for x in output_consts.keys()]\n [common_column_names.remove(x) for x in output_metrics if x != 'dummy']\n for output_metric in output_metrics:\n if output_metric == 'dummy':\n continue\n refer = output_metric\n if (not self.specify_report) or (refer in self.specify_report):\n result_dict = {}\n result_dict['computation_ds'] = self.context['today']\n result_dict['refer'] = refer\n result_dict['unit_name'] = unit_name\n result_dict['value'] = float(name_data_mapping.get(output_metric, '0.0'))\n \n hook = analysis.analysis_metrics.get(refer, {}).get('analysis_metric_hook', None)\n if hook:\n result_dict['value'] = float(hook(result_dict['value']))\n \n for common_column_name in common_column_names:\n result_dict[common_column_name] = name_data_mapping.get(common_column_name, 'unknown')\n \n tobe_delete = [] \n for key in result_dict.keys():\n if result_dict[key] == 'NULL':\n tobe_delete.append(key)\n for key in tobe_delete:\n result_dict.pop(key)\n \n self.result_buffer.append(result_dict)\n else:\n print('★★★★★ ERROR: ' + sql) \n\n \n def start(self):\n logging.info('Engine Start!')\n \n if not self.no_insert:\n # first of all, start all the datawarehouse-related computations\n layer_range = range(4)\n for layer in layer_range:\n layer_computation_list = self.computation_info.get(layer, [])\n \n with multiprocessing.dummy.Pool(4) as computation_pool:\n computation_pool.map(self._worker, layer_computation_list)\n # first of all, start all the datawarehouse-related computations END\n if self.oldversion or self.bothversion: \n # all report units computations\n with multiprocessing.dummy.Pool(8) as computation_pool:\n computation_pool.map(self._worker, self.report_unit_list)\n # all report units computations END\n \n # all sql generator computations\n if (not self.oldversion) or self.bothversion:\n with multiprocessing.dummy.Pool(8) as computation_pool:\n computation_pool.map(self._worker_by_sqlgenerator, ALL_ANALYSIS)\n # all sql generator computations end\n \n logging.info('Engine Done')\n\n def replay(self, storge_name, **kwargs):\n logging.info('Storge Replay!')\n logfile_num = 9999\n specify_date = kwargs.get('date', None)\n while logfile_num >= 0:\n lognum_str = ('.' + str(logfile_num)) if logfile_num else ''\n file_path = '/data/log/elasticsearch/es_log.log' + lognum_str\n logfile_num = logfile_num - 1\n if not os.path.exists(file_path):\n continue\n file_path_new = file_path+'.backup'+str(int(time.time()))\n os.rename(file_path, file_path_new)\n with open(file_path_new, 'r') as logfile:\n for logline in logfile:\n log_list = logline.split('\\t')\n if log_list[0] != storge_name or str(log_list[5]) == 'False':\n continue\n if specify_date:\n if log_list[1].split(' ')[0] != specify_date:\n continue\n for storage in self.storage_engine_info['RESULT']: # store with all storage_engine\n # reinit the es_logger to write log to the new file\n storage.es_logger = storage.__init_logger__(storge_name, file_path)\n if log_list[3] == 'PUT':\n storage.put(doc = json.loads(log_list[4]))\n elif log_list[3] == 'DELETE':\n storage.delete(conditions = json.loads(log_list[4]))\n \n def flush_buffer(self):\n logging.info('Flush Buffer...')\n for storage in self.storage_engine_info['RESULT']: # store with all storage_engine\n storage.puts(docs = self.result_buffer)\n \nif __name__ == '__main__':\n \n start_engine_time = time.time()\n help_text = '''\n Hi, I'm a engine to run your pixel settings.I have some argus:\n \n --help To watch the help text.\n e.g. python3 engine.py --help\n --date To specify a date to run engine.\n e.g. python3 engine.py --date=2017-01-01\n --noinsert If given this argu,I won't run the sql of 'insert overwrite'.(Only used in old version)\n e.g. python3 engine.py --noinsert\n --report To specify some report to run engine.\n e.g. python3 engine.py --report=dau,dtu,drru\n --oldversion To run this engine only by oldversion way.\n e.g. python3 engine.py --oldversion\n --bothversion To run this engine by both the new and the old version way.\n e.g. python3 engine.py --bothversion\n -y To auto anwser yes for all question.\n e.g. python3 engine.py --update -y --date=2017-01-01\n \\033[1;31;40m--update\\033[0m Delete the data of the specify_date before run engine.\n e.g. python3 engine.py --update --date=2017-01-01\n \\033[1;31;40m--replay\\033[0m To specify a storage name,I will replay it to your storage from your storage log file.\n e.g. python3 engine.py --replay=ES_01\n \\033[1;31;40m--delete\\033[0m To delete data of the specify_date.\n e.g. python3 engine.py --delete --date=2017-01-01\n \n ps: The red font word is the argus which can change your date.\n '''\n \n opt,args = getopt.getopt(sys.argv[1:], \"yd:r:\", ['update','date=','replay=','help','delete','noinsert','report=', 'oldversion', 'bothversion'])\n \n update = False\n specify_date = None\n replay = None\n delete = False\n choose_yes = False\n no_insert = False\n oldversion = False\n bothversion = False\n specify_report = []\n \n for op,value in opt: # get argus\n if op in ('-h', '--help'):\n print(help_text) \n sys.exit()\n if op in ('--update'):\n if not value:\n update = True\n else:\n print('update argu must have no value')\n sys.exit()\n if op in ('d', '--date'):\n specify_date = str(value).lower()\n if op in ('-r', '--replay'):\n replay = str(value)\n if op in ('--delete'):\n if not value:\n delete = True\n else:\n print('delete argu must have no value')\n sys.exit()\n if op in ('-y'):\n if not value:\n choose_yes = True\n else:\n print('-y argu must have no value')\n sys.exit()\n if op in ('--noinsert'):\n if not value:\n no_insert = True\n else:\n print('noinsert argu must have no value')\n sys.exit()\n if op in ('--report'):\n specify_report = str(value).split(',')\n if op in ('--oldversion'):\n if not value:\n oldversion = True\n else:\n print('oldversion argu must have no value')\n sys.exit()\n if op in ('--bothversion'):\n if not value:\n bothversion = True\n if oldversion:\n print('use bothversion argu must have no oldversion argu')\n sys.exit()\n else:\n print('bothversion argu must have no value')\n sys.exit()\n \n if replay: # To specify a storage name,I will replay it to your storage from your storage log file.\n if any(update, specify_date, delete):\n print('if you choose replay, you mustn\\'t provide other argu')\n sys.exit()\n else:\n if choose_yes:\n choose = 'yes'\n else:\n choose = input('\\033[1;31;40mThis command will overwrite your data. Are you sure to continue?\\033[0m').lower()\n if not (choose == 'yes' or choose == 'y'):\n sys.exit()\n else:\n engine = ETLEngine()\n engine.replay(replay)\n sys.exit()\n \n if update: # Delete the data of the specify_date before run engine.\n if delete:\n print('update and delete argu can\\'t appear together')\n sys.exit()\n if choose_yes:\n choose = 'yes'\n else:\n choose = input('\\033[1;31;40mThis command will overwrite your data. Are you sure to continue?\\033[0m').lower()\n if not (choose == 'yes' or choose == 'y'):\n sys.exit()\n elif not specify_date:\n print('update must has the date argu')\n sys.exit()\n \n if delete: # To delete data of the specify_date.\n if choose_yes:\n choose = 'yes'\n else:\n choose = input('\\033[1;31;40mThis command will overwrite your data. Are you sure to continue?\\033[0m').lower()\n if not (choose == 'yes' or choose == 'y'):\n sys.exit()\n if not specify_date:\n print('delete must has the date argu')\n sys.exit()\n \n engine = ETLEngine(update=update, \n specify_date=specify_date, \n delete=delete, \n no_insert=no_insert, \n specify_report=specify_report, \n oldversion=oldversion, \n bothversion=bothversion)\n engine.start()\n engine.flush_buffer()\n \n end_engine_time = time.time()\n cost_time = str(int(end_engine_time - start_engine_time))\n print('spend: about {0} seconds.'.format(cost_time))\n\n","repo_name":"wellsmile/Bigdata-BI-ETL","sub_path":"utils/etl/engine.py","file_name":"engine.py","file_ext":"py","file_size_in_byte":25954,"program_lang":"python","lang":"en","doc_type":"code","stars":4,"dataset":"github-code","pt":"17"} +{"seq_id":"8638243745","text":"from __future__ import print_function\nfrom pprint import *\nimport tabulate\nimport random\nimport time\nimport re\nimport codecs\n## Spacy imports\nimport json\nimport pathlib\nimport spacy\nfrom spacy.pipeline import EntityRecognizer\nfrom spacy.gold import GoldParse\nfrom spacy.tokens import Doc\n# from spacy.tagger import Tagger\n## NLTK imports\nfrom nltk.tokenize.moses import MosesDetokenizer\n\ndef get_data(file):\n\tfin = open(file,\"r\")\n\ttokens_l = []; tags_l =[]\n\ttl = []; tgl = []\n\tfor line in fin:\n\t\tif(line.strip()==\"\"):\n\t\t\ttokens_l.append(tl);tags_l.append(tgl)\n\t\t\ttl = [];tgl = []\n\t\telse:\n\t\t\tl = [x.strip() for x in line.split()]\n\t\t\ttl.append(l[0]); tgl.append(l[1])\n\treturn tokens_l, tags_l\n\ndef train_ner(nlp, train_data, entity_types):\n\tdetokenizer = MosesDetokenizer()\n\t## Add new words to vocab.\n\tfor tokens, _ in train_data:\n\t\t# doc = nlp.make_doc(raw_text)\n\t\tfor word in tokens:\n\t\t\t_ = nlp.vocab[word]\n\n\t# ## Train NER.\n\t# ner = EntityRecognizer(nlp.vocab, entity_types=entity_types)\n\t# for itn in range(5):\n\t# \trandom.shuffle(train_data)\n\t# \tfor tokens, entity_offsets in train_data:\n\t# \t\tdoc = nlp.make_doc(detokenizer.detokenize(tokens, return_str=True))\n\t# \t\tgold = GoldParse(doc,entities=entity_offsets)\n\t# \t\tner.update([doc], [gold])\n\t# return ner\n\tif 'ner' not in nlp.pipe_names:\n\t\tner = nlp.create_pipe('ner')\n\t\tnlp.add_pipe(ner, last=True)\n\t# otherwise, get it so we can add labels\n\telse:\n\t\tner = nlp.get_pipe('ner')\n\n\t# add labels\n\tfor _, annotations in train_data:\n\t\tfor ent in annotations:\n\t\t\tner.add_label(ent)\n\tother_pipes = [pipe for pipe in nlp.pipe_names if pipe != 'ner']\n\n\toptimizer = nlp.begin_training()\n\tfor itn in range(100):\n\t\trandom.shuffle(train_data)\n\t\tfor raw_text, entity_offsets in train_data:\n\t\t\tdoc = Doc(nlp.vocab,words = raw_text)\n\t\t\tgold = GoldParse(doc, entities=entity_offsets)\n\t\t\tnlp.update([doc], [gold], drop=0.5, sgd=optimizer)\n\ndef predict_list_spacy(nlp,data,testing,model_dir=None):\n\tnlp = spacy.load('en_default', parser=False, entity=False, add_vectors=False)\n\tif nlp.tagger is None:\n\t\tprint(\"---------> Didn't find a model, performance will be not upto mark.\")\n\t\tnlp.tagger = Tagger(nlp.vocab, features=Tagger.feature_templates)\n\n\tprint(\"testing on indices\",testing)\n\ttrain_d = [data[i] for i in indices if i not in testing]\n\ttest_d = [data[i] for i in testing]\n\tprint(\"Training and testing on corpus of size\",len(train_d),len(test_d)); t1 = time.time()\n\tner = train_ner(nlp, train_d, global_labels)\n\tprint(\"training completed in \",time.time()-t1)\n\n\toffer_strings = [x[0] for x in test_d]\n\tpreds = []\n\tfor s in offer_strings:\n\t\tp = []\n\t\tdoc = nlp.make_doc(s)\n\t\tnlp.tagger(doc)\n\t\tner(doc)\n\t\tfor word in doc:\n\t\t\t# print(word.text,word.ent_type_)\n\t\t\tp.append((word.text,word.ent_type_))\n\t\tpreds.append(p)\n\n\tif model_dir is not None:\n\t\tsave_model(ner, model_dir)\n\treturn(preds)\n\ntokens,tags = get_data(\"train3.txt\")\nprint(len(tokens),len(tags))\npprint(tokens[:4])\npprint(set([x for ll in tags for x in ll]))\nnlp = spacy.load(\"en\")\nner_tagger = train_ner(nlp,list(zip(tokens,tags)),['B-PER', 'I-ORG', 'O', 'I-LOC', 'I-PER', 'B-ORG', 'B-LOC'])","repo_name":"Akshay9414/TwitterAnalytics","sub_path":"NLP on Tweets/Spacy/NER_using_spacy.py","file_name":"NER_using_spacy.py","file_ext":"py","file_size_in_byte":3091,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"17"} +{"seq_id":"6178731105","text":"from __future__ import annotations\n\nfrom enum import IntEnum\nfrom uuid import UUID, uuid4\n\nimport pytest\n\nfrom restio.fields import (\n BoolField,\n EnumField,\n FloatField,\n FrozenSetField,\n FrozenSetModelField,\n IntField,\n ModelField,\n StrField,\n TupleField,\n TupleModelField,\n UUIDField,\n)\nfrom restio.fields.base import ContainerField, Field, FrozenType\nfrom restio.model import BaseModel\n\n\nclass IntEnumType(IntEnum):\n A = 1\n B = 2\n C = 3\n\n\nclass FieldsModel(BaseModel):\n id: IntField = IntField(default=0, pk=True)\n a: IntField = IntField(default=0)\n b: StrField = StrField(default=\"\")\n\n\ndefault_model = FieldsModel()\ndefault_uuid = UUID(\"6564d955-5fb9-4731-9452-2e0a49a46243\")\ndefault_uuid2 = UUID(\"f4135fa3-ec79-45aa-a6e4-f5470eca9e01\")\n\n\nclass TestFields:\n def test_base_field_provide_both_defaults(self):\n with pytest.raises(ValueError, match=\"provided for both\"):\n Field(\n type_=str,\n pk=False,\n allow_none=False,\n depends_on=False,\n frozen=FrozenType.NEVER,\n default=\"\",\n default_factory=str,\n )\n\n def test_base_field_missing_defaults(self):\n class BaseFieldModel(BaseModel):\n field = Field(\n type_=str,\n pk=False,\n allow_none=False,\n depends_on=False,\n frozen=FrozenType.NEVER,\n )\n\n with pytest.raises(ValueError, match=\"default value not\"):\n BaseFieldModel()\n\n def test_enum_field_wrong_type(self):\n with pytest.raises(TypeError):\n EnumField(int) # type: ignore\n\n @pytest.mark.parametrize(\"type_check\", [True, False])\n @pytest.mark.parametrize(\n \"field_type, value\",\n [\n (IntField, \"a\"),\n (StrField, 5),\n (BoolField, \"a\"),\n (FloatField, 1),\n (UUIDField, \"6564d955-5fb9-4731-9452-2e0a49a46243\"),\n (lambda **kwargs: EnumField(IntEnumType, **kwargs), 1),\n (lambda **kwargs: TupleField(int, **kwargs), [\"a\"]),\n (lambda **kwargs: FrozenSetField(str, **kwargs), {\"b\"}),\n (lambda **kwargs: ModelField(FieldsModel, **kwargs), \"s\"),\n (lambda **kwargs: TupleModelField(FieldsModel, **kwargs), [\"a\"]),\n (lambda **kwargs: FrozenSetModelField(FieldsModel, **kwargs), {\"b\"}),\n ],\n )\n def test_set_field_invalid_value(self, type_check, field_type, value):\n class Model(BaseModel):\n field = field_type(type_check=type_check)\n\n if type_check:\n with pytest.raises(TypeError, match=\"should be of type\"):\n Model(field=value)\n else:\n m = Model(field=value)\n assert m.field == value\n\n @pytest.mark.parametrize(\n \"field_type, default\",\n [\n (IntField, 1),\n (StrField, \"a\"),\n (BoolField, True),\n (FloatField, 1.0),\n (UUIDField, default_uuid),\n (lambda default: EnumField(IntEnumType, default=default), IntEnumType.A),\n (lambda default: TupleField(int, default_factory=default), lambda: (1, 2)),\n (\n lambda default: FrozenSetField(str, default_factory=default),\n lambda: frozenset([\"a\", \"b\"]),\n ),\n (lambda default: ModelField(FieldsModel, default=default), default_model),\n (\n lambda default: TupleModelField(FieldsModel, default_factory=default),\n lambda: (default_model,),\n ),\n (\n lambda default: FrozenSetModelField(\n FieldsModel, default_factory=default\n ),\n lambda: frozenset({default_model}),\n ),\n ],\n )\n def test_model_fields_custom_default(self, field_type, default):\n field = field_type(default=default)\n\n assert field.default == default() if callable(default) else default\n\n @pytest.mark.parametrize(\"type_check\", [True, False])\n @pytest.mark.parametrize(\n \"field_type\",\n [\n IntField,\n StrField,\n BoolField,\n FloatField,\n UUIDField,\n lambda **kwargs: EnumField(IntEnumType, **kwargs),\n lambda **kwargs: TupleField(int, **kwargs),\n lambda **kwargs: FrozenSetField(str, **kwargs),\n lambda **kwargs: TupleModelField(FieldsModel, **kwargs),\n lambda **kwargs: FrozenSetModelField(FieldsModel, **kwargs),\n ],\n )\n def test_set_field_none(self, type_check, field_type):\n class Model(BaseModel):\n field = field_type(type_check=type_check)\n\n if type_check:\n with pytest.raises(TypeError, match=\"should be of type\"):\n Model(field=None)\n else:\n m = Model(field=None)\n assert m.field is None\n\n @pytest.mark.parametrize(\n \"field_type\",\n [\n IntField,\n StrField,\n BoolField,\n FloatField,\n UUIDField,\n lambda **kwargs: EnumField(IntEnumType, **kwargs),\n lambda **kwargs: ModelField(FieldsModel, **kwargs),\n ],\n )\n def test_default_none_when_allow_none(self, field_type):\n class Model(BaseModel):\n field = field_type(allow_none=True)\n\n obj = Model()\n\n assert obj.field is None\n\n @pytest.mark.parametrize(\n \"field_type, expected_value\",\n [\n (IntField, 1),\n (StrField, \"a\"),\n (BoolField, True),\n (FloatField, 1.0),\n (UUIDField, default_uuid),\n (lambda **kwargs: EnumField(IntEnumType, **kwargs), IntEnumType.A),\n (lambda **kwargs: ModelField(FieldsModel, **kwargs), default_model),\n ],\n )\n def test_default_not_none_when_allow_none(self, field_type, expected_value):\n class Model(BaseModel):\n field = field_type(default=expected_value, allow_none=True)\n\n obj = Model()\n\n assert obj.field == expected_value\n\n def test_model_field_string_type(self):\n class Model(BaseModel):\n field = ModelField(type_check=True, model_type=\"Model\")\n\n obj = Model()\n obj_set = Model()\n\n obj.field = obj_set\n\n assert obj.field == obj_set\n assert Model._meta.fields[\"field\"].type_ == Model\n\n def test_model_field_string_type_wrong_value_type(self):\n class Model(BaseModel):\n field = ModelField(type_check=True, model_type=\"Model\")\n\n obj = Model()\n\n obj_set = FieldsModel()\n\n with pytest.raises(TypeError):\n obj.field = obj_set\n\n def test_model_field_string_type_not_relational(self):\n\n with pytest.raises(TypeError, match=\"is invalid for non-relational\"):\n\n class Model(BaseModel):\n field = Field(\n type_=\"Model\",\n pk=False,\n allow_none=False,\n depends_on=False,\n frozen=FrozenType.NEVER,\n )\n\n @pytest.mark.parametrize(\n \"field_type, factory\",\n [(TupleModelField, tuple), (FrozenSetModelField, frozenset)],\n )\n def test_iterable_model_field_string_type(self, field_type, factory):\n class Model(BaseModel):\n field = field_type(\n type_check=True, model_type=\"Model\", default_factory=factory\n )\n\n obj = Model()\n obj_set = factory([Model(field=factory())])\n\n obj.field = obj_set\n\n assert obj.field == obj_set\n assert Model._meta.fields[\"field\"].sub_type == Model # type: ignore\n\n @pytest.mark.parametrize(\n \"field_type, factory\",\n [(TupleModelField, tuple), (FrozenSetModelField, frozenset)],\n )\n def test_iterable_model_field_string_type_wrong_model_type(\n self, field_type, factory\n ):\n class Model(BaseModel):\n field = field_type(\n type_check=True, model_type=\"Model\", default_factory=factory\n )\n\n obj = Model()\n obj_set = factory([FieldsModel(field=factory())])\n\n with pytest.raises(TypeError):\n obj.field = obj_set\n\n def test_model_field_string_type_container_not_relational(self):\n\n with pytest.raises(TypeError, match=\"is invalid for non-relational\"):\n\n class Model(BaseModel):\n field = ContainerField(\n type_=tuple,\n sub_type=\"Model\",\n pk=False,\n allow_none=False,\n depends_on=False,\n frozen=FrozenType.NEVER,\n )\n\n _setter_params = [\n (lambda **kwargs: IntField(default=0, **kwargs), 1, 2),\n (lambda **kwargs: StrField(default=\"\", **kwargs), \"a\", \"b\"),\n (lambda **kwargs: BoolField(default=False, **kwargs), False, True),\n (lambda **kwargs: FloatField(default=0.0, **kwargs), 1.0, 2.0),\n (\n lambda **kwargs: UUIDField(default_factory=uuid4, **kwargs),\n default_uuid,\n default_uuid2,\n ),\n (\n lambda **kwargs: EnumField(IntEnumType, default=IntEnumType.A, **kwargs),\n IntEnumType.B,\n IntEnumType.C,\n ),\n (lambda **kwargs: TupleField(int, default_factory=tuple, **kwargs), (1,), (2,)),\n (\n lambda **kwargs: FrozenSetField(str, default_factory=frozenset, **kwargs),\n frozenset({\"a\"}),\n frozenset({\"b\"}),\n ),\n (\n lambda **kwargs: ModelField(FieldsModel, default=None, **kwargs),\n None,\n default_model,\n ),\n (\n lambda **kwargs: TupleModelField(\n FieldsModel, default_factory=tuple, **kwargs\n ),\n tuple(),\n (default_model,),\n ),\n (\n lambda **kwargs: FrozenSetModelField(\n FieldsModel, default_factory=frozenset, **kwargs\n ),\n frozenset(),\n frozenset({default_model}),\n ),\n ]\n\n @pytest.mark.parametrize(\"field_type, input_value, setter_value\", _setter_params)\n @pytest.mark.parametrize(\n \"setter_type\", [\"constructor\", \"decorator\", \"method_decorator\"]\n )\n def test_setter_field_assignment(\n self, setter_type, field_type, input_value, setter_value\n ):\n initialized = False\n model_class = None\n\n def setter(model, value):\n assert isinstance(model, BaseModel)\n\n if initialized:\n assert value == input_value\n return setter_value\n else:\n return value\n\n if setter_type == \"constructor\":\n\n class ModelConstructor(BaseModel):\n field = field_type(setter=setter)\n\n model_class = ModelConstructor\n\n elif setter_type == \"decorator\":\n\n class ModelDecorator(BaseModel):\n field = field_type()\n\n @field.setter\n def field_setter(self, value):\n return setter(self, value)\n\n model_class = ModelDecorator\n\n elif setter_type == \"method_decorator\":\n\n class ModelMethodDecorator(BaseModel):\n field = field_type()\n field_setter = field.setter(setter)\n\n model_class = ModelMethodDecorator\n\n if not model_class:\n pytest.fail(\"Setter type has not been properly defined\")\n\n obj = model_class()\n initialized = True\n assert obj.field != setter_value\n obj.field = input_value\n assert obj.field == setter_value\n\n def test_setter_exception(self):\n class Model(BaseModel):\n field = IntField(default=20)\n\n @field.setter\n def field_setter(self, value: int):\n if value < 18:\n raise ValueError()\n return value\n\n obj = Model()\n\n assert obj.field == 20\n\n with pytest.raises(ValueError):\n obj.field = 5\n\n assert obj.field == 20\n\n def test_property_setter(self):\n class Model(BaseModel):\n _field = IntField(default=15)\n\n @property\n def field(self):\n return self._field\n\n @field.setter\n def field(self, value: int):\n if value < 18:\n raise ValueError()\n self._field = value\n\n obj = Model()\n\n assert obj.field == 15\n assert obj._field == 15\n\n obj.field = 20\n\n assert obj.field == 20\n assert obj._field == 20\n","repo_name":"eduardostarling/restio","sub_path":"tests/unit/test_fields.py","file_name":"test_fields.py","file_ext":"py","file_size_in_byte":12792,"program_lang":"python","lang":"en","doc_type":"code","stars":5,"dataset":"github-code","pt":"17"} +{"seq_id":"35351821535","text":"num_loops = 1\nnumbe = 1\nstar = \"*\"\nspace = \" \"\n\n\ndef part_of_tree():\n num = 1\n number = 1\n numbers = 16\n while num < 10:\n print (space*numbers + star*number)\n num = num + 1\n number = number + 2\n numbers = numbers - 1\n\nwhile num_loops < 4:\n part_of_tree()\n num_loops = num_loops + 1\n\nwhile numbe < 6:\n print (\" \"*15 + \"***\")\n numbe = numbe + 1\n\n \n","repo_name":"JASPERLICA/pythonjayden","sub_path":"mutlipication table.py","file_name":"mutlipication table.py","file_ext":"py","file_size_in_byte":401,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"17"} +{"seq_id":"3496760662","text":"from discord.ext import commands\nimport config\n\nclient = commands.Bot(command_prefix=config.PREF)\n\n@client.command()\nasync def commands(ctx):\n await ctx.send('Моя модель ещё не доработана, данная команда пока не доступна...')\n\n@client.command()\nasync def admin_help(ctx):\n await ctx.send('Моя модель ещё не доработана, данная команда пока не доступна...')\n\n\nclient.run(config.TOKEN)","repo_name":"BackLagg/DS_BOT","sub_path":"commands.py","file_name":"commands.py","file_ext":"py","file_size_in_byte":490,"program_lang":"python","lang":"ru","doc_type":"code","stars":0,"dataset":"github-code","pt":"17"} +{"seq_id":"71106202585","text":"import matplotlib.pyplot as plt\nimport matplotlib.patches as patches \nimport nibabel as nib \nimport numpy as np \nimport os\nfrom scipy import ndimage\nimport sys \nfrom tqdm import tqdm \n\nimport pandas as pd \n\ndef check_noise(plot=False):\n ''' Iterates over all defaced files and compute the background noise of a specific region. \n\n Args: \n plot: boolean determining whether to plot the noise box. \n '''\n prefix = '../../../../../..'\n root_path = prefix + '/data/projects/ahead/raw_gdata/'\n save_path = prefix + '/data/projects/ahead/defaced/'\n \n # caclulate for different coils\n n = 50\n s = 140\n df = pd.DataFrame(columns=['subj', 'echo', 'coil', 'diff_real', 'diff_imag','perc_real','perc_imag'])\n\n for d in tqdm(directories):\n \n for echo in range(1,5):\n data = {'subj': np.full(32,int(d.split('_')[1])), 'echo':np.full(32,echo), 'coil': range(1,33)}\n \n try: \n original = nib.load(f'{root_path}{d}/{d}_inv2_{echo}_gdataCorrected.nii.gz').get_fdata(dtype=np.complex64)\n defaced = nib.load(f'{save_path}{d}/{d}_inv2_{echo}_gdataCorrected_defaced.nii.gz').get_fdata(dtype=np.complex64)\n no_noise = nib.load(f'{save_path}{d}/{d}_inv2_{echo}_gdataCorrected_no_noise.nii.gz').get_fdata(dtype=np.complex64)\n except:\n print(d)\n continue\n\n x, y, z = original.shape[:3] \n\n difference_real = []\n difference_imag = []\n percent_real = []\n percent_imag = []\n all_std_real_orig = []\n all_std_imag_orig = []\n all_std_real_def = []\n all_std_imag_def = []\n \n\n for coil in range(original.shape[3]):\n # print('Coil:', coil + 1)\n\n # compute std for both imageinary and real channels from original and defaced \n std_real_orig = np.std(original[0:n,0:n,z-n:, coil].real)\n std_imag_orig = np.std(original[0:n,0:n,z-n:, coil].imag)\n\n std_real_def = np.std(defaced[0:n,0:n,z-n:, coil].real)\n std_imag_def = np.std(defaced[0:n,0:n,z-n:, coil].imag)\n\n all_std_real_orig.append(std_real_orig)\n all_std_imag_orig.append(std_imag_orig)\n all_std_real_def.append(std_real_def)\n all_std_imag_def.append(std_imag_def)\n\n difference_real.append(std_real_def - std_real_orig)\n difference_imag.append(std_imag_def - std_imag_orig)\n\n p_real = ((std_real_def - std_real_orig) / ((std_real_def + std_real_orig) / 2)) * 100\n p_imag = ((std_imag_def - std_imag_orig) / ((std_imag_def + std_imag_orig) / 2)) * 100\n percent_real.append(p_real)\n percent_imag.append(p_imag)\n\n\n data['diff_real'] = difference_real\n data['diff_imag'] = difference_imag\n data['perc_real'] = percent_real\n data['perc_imag'] = percent_imag\n\n data['std_real_orig'] = all_std_real_orig\n data['std_imag_orig'] = all_std_imag_orig\n data['std_real_def'] = all_std_real_def\n data['std_imag_def'] = all_std_imag_def\n\n\n df = df.append(pd.DataFrame(data),ignore_index=True)\n\n df.to_csv('defacing_background_noise_adjusted_box.csv')\n\n\ndef plot_defacing_comparison(original, no_noise, defaced, s, coil=7):\n ''' Plots the original, defaced, and defaced with no noise images. '''\n\n plt.subplot(131)\n plt.imshow(ndimage.rotate(original[s,:,:,coil].real, 90), vmin=-100, vmax=100, cmap='gray')\n plt.title('Original image')\n plt.subplot(132)\n plt.imshow(ndimage.rotate(no_noise[s,:,:,coil].real, 90), vmin=-100, vmax=100, cmap='gray')\n plt.title('Defaced, without noise')\n plt.subplot(133)\n plt.imshow(ndimage.rotate(defaced[s,:,:,coil].real, 90), vmin=-100, vmax=100, cmap='gray')\n plt.title('Defaced, with noise')\n\n plt.colorbar(shrink=0.5)\n plt.show()\n\n\ndef plot_noise_box(original, n, coil=7):\n ''' Plots a box from which the noise in compared. '''\n\n x, y, z = original.shape[:3]\n\n fig, ax = plt.subplots()\n ax.imshow(original[s,:,:,coil].real, cmap='gray')\n rect = patches.Rectangle((y-n,z-n), n, n, linewidth=1, edgecolor='lime', facecolor='none')\n ax.add_patch(rect)\n ax.axis('off')\n plt.show()\n\n\nif __name__ == '__main__':\n check_noise(plot=False)","repo_name":"emmahokken/thesis_amsterdamumc","sub_path":"defacing/code/check_noise.py","file_name":"check_noise.py","file_ext":"py","file_size_in_byte":4474,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"17"} +{"seq_id":"12531327414","text":"from collections import defaultdict\n\n\nclass Graph:\n def __init__(self):\n self.graph = defaultdict(list)\n\n def addEdge(self, u, v):\n self.graph[u].append(v)\n\n def BFS(self, s):\n visited = [False] * len(self.graph)\n queue = [s]\n visited[s] = True\n while queue:\n temp = queue.pop(0)\n print(temp, end=' ')\n for child in self.graph[temp]:\n if not visited[child]:\n queue.append(child)\n visited[child] = True\n\n def DFS(self, s):\n visited = set()\n self.DFSUtil(s, visited)\n\n def DFSUtil(self,s,visited):\n print(s, end=\" \")\n visited.add(s)\n for child in self.graph[s]:\n if child not in visited:\n self.DFSUtil(child, visited)\n\n\ng = Graph()\ng.addEdge(0, 1)\ng.addEdge(0, 2)\ng.addEdge(1, 2)\ng.addEdge(2, 0)\ng.addEdge(2, 3)\ng.addEdge(3, 3)\n\nprint(\"Following is Breadth First Traversal\", \"(starting from vertex 2)\")\ng.BFS(2)\n","repo_name":"DhyeyRajveer/AI-Lab","sub_path":"main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":1014,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"17"} +{"seq_id":"26970187647","text":"import csv\n\nfrom django.http import HttpResponse\nfrom django.utils import timezone\n\n\ndef determine_remote_ip(request):\n \"\"\"\n Returns the client IP address for the HTTP request.\n\n This function may return either an IPv4 or an IPv6 address. It may also\n return `None` if an IP cannot be reliably determined (e.g. in a unit test).\n\n Args:\n * `request` - `HttpRequest`\n\n Returns:\n `str|None`\n \"\"\"\n x_client_ip = request.headers.get('X-Client-Ip')\n return x_client_ip if x_client_ip else request.META.get('REMOTE_ADDR')\n\n\ndef csv_download_response(column_headings, data, filename, include_date=True):\n \"\"\"\n Put data into a CSV download response\n\n Args:\n - ``column_headings`` - A tuple of column headings\n - ``data`` - An iterable of data. Each value should be tuple of values aligning with\n the columns given.\n - ``filename`` - The filename without the `.csv` file extension\n - ``include_date`` - If true, the filename will be appended with a datetime string\n\n Returns:\n - A tuple containing an ``HttpResponse`` object to be returned by the view, and the\n CSV writer if any more rows needed to be added from outside this function. The\n CSV writer contains the response object so any changes made to the CSV will automatically\n be added to the returned response object.\n \"\"\"\n response = _format_csv_response(filename, include_date)\n writer = csv.writer(response)\n writer.writerow(column_headings)\n for row in data:\n writer.writerow(row)\n return (response, writer)\n\n\ndef csv_download_response_dict(data, filename, include_date=True):\n \"\"\"\n Same as `csv_download_response` but accepts a list of dicts as data. Does\n not require column headings.\n\n Note, columns are ordered alphabetically.\n\n Raises:\n * `ValueError` if data is empty\n \"\"\"\n if not data:\n raise ValueError('Data is empty')\n\n # get headings\n headings = sorted(set().union(*(d.keys() for d in data)))\n\n response = _format_csv_response(filename, include_date)\n writer = csv.DictWriter(response, headings)\n writer.writeheader()\n for row in data:\n writer.writerow(row)\n return (response, writer)\n\n\ndef _format_csv_response(filename, include_date):\n if include_date:\n filename = '%s-%s.csv' % (filename, timezone.now().strftime('%Y-%m-%d-%H-%M-%S'))\n else:\n filename = '%s.csv'\n\n # Build CSV\n response = HttpResponse(content_type='text/csv')\n response['Content-Disposition'] = 'attachment; filename=%s' % filename\n return response\n","repo_name":"mrmonkington/gn-django","sub_path":"gn_django/utils/http.py","file_name":"http.py","file_ext":"py","file_size_in_byte":2696,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"17"} +{"seq_id":"10226471030","text":"\"\"\"\nMiscs utilities.\n\"\"\"\n\nimport numpy as np\n\n\ndef create_ellipse(\n a: float,\n b: float,\n steps: int = 200,\n phase: float = 0.0\n) -> np.ndarray:\n \"\"\"\n Creates an ellipse.\n\n Parameters:\n a: float : major semiaxis\n b: float : minor semiaxis\n steps: int = 200 : number of points\n phase: float = 0.0 : starting angle\n\n Returns:\n x: np.ndarray : xy coordinates of an ellipse\n \"\"\"\n\n phi = np.linspace(0, 2 * np.pi, num=steps, endpoint=False)\n phi += phase\n x = np.zeros((steps, 2), dtype=np.float64)\n x[:, 0] = a * np.cos(phi)\n x[:, 1] = b * np.sin(phi)\n\n return x\n","repo_name":"bhornung11/bhornung11.github.io","sub_path":"assets/formula1/src/util/misc.py","file_name":"misc.py","file_ext":"py","file_size_in_byte":655,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"17"} +{"seq_id":"33195861854","text":"\"\"\"\nGiven a list of numbers and a number k, return whether any two numbers from the list add up to k.\nFor example, given[10, 15, 3, 7] and k of 17, return true since 10 + 7 is 17.\n\"\"\"\n\n\ndef has_sum_pair(numbers, k):\n # Check all pairs of numbers for a sum equal to k\n for i in range(len(numbers)):\n for j in range(i + 1, len(numbers)):\n if numbers[i] + numbers[j] == k:\n return (numbers[i], numbers[j])\n\n # No pair of numbers adds up to k\n return False\n\n\nnumbers = []\nwhile True:\n val = int(input(\"Enter an array element (-1 to stop): \"))\n if val == -1:\n break\n numbers.append(val)\nk = int(input('Enter a value for k:'))\nresult = has_sum_pair(numbers, k)\n\n\nprint(f\"The input list is {numbers}, and k is {k}. The result is {result}.\")","repo_name":"nihmrnd/hacker-rank","sub_path":"Algorithms/HasSumPair.py","file_name":"HasSumPair.py","file_ext":"py","file_size_in_byte":794,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"17"} +{"seq_id":"31959863346","text":"import pygame\n\nclass Button():\n\tdef __init__(self, game, msg):\n\t\tself.screen = game.screen\n\t\tself.screen_rect = game.screen_rect\n\n\t\tself.font = pygame.font.SysFont(None, 48)\n\t\tself.button_color = (85, 85, 85)\n\t\tself.text_color = (255, 255, 255)\n\t\tself.prep_msg(msg)\n\n\t\tself.width = 10 + self.msg_image_rect.width\n\t\tself.height = 20 + self.msg_image_rect.height\n\n\t\tself.rect = pygame.Rect(0, 0, self.width, self.height)\n\t\tself.rect.center = self.screen_rect.center\n\t\tself.msg_image_rect.center = self.rect.center \n\n\tdef prep_msg(self, msg):\n\t\tself.msg_image = self.font.render(msg, True, \n\t\t\tself.text_color, self.button_color)\n\t\tself.msg_image_rect = self.msg_image.get_rect()\n\n\tdef draw_button(self):\n\t\tself.screen.fill(self.button_color, self.rect)\n\t\tself.screen.blit(self.msg_image, self.msg_image_rect)\n\nclass Difficulty_Button(Button):\n\tdef __init__(self, game, msg):\n\t\tsuper().__init__(game, msg)\n\t\tself.padding = 10\n\t\tself.rect.top += self.height + self.padding\n\n\t\tif msg == \"EASY\":\n\t\t\tself.rect.right = game.difficulty_default.rect.left - self.padding\n\t\telif msg == \"HARD\":\n\t\t\tself.rect.left = game.difficulty_default.rect.right + self.padding\n\t\telse:\n\t\t\tself.rect.left = self.screen_rect.centerx - int(self.width / 2)\n\n\t\tself.msg_image_rect.center = self.rect.center\n\n\n","repo_name":"trettifjerde/doodles","sub_path":"crow_invasion/button.py","file_name":"button.py","file_ext":"py","file_size_in_byte":1278,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"17"} +{"seq_id":"37934753977","text":"import os\nimport random\n\nmy_dir = 'C:/Users/e.menshaev/Desktop/Skillbox/python-ds/15_IDE/'\nfile_name = 'main.py'\ncount = random.randint(0, 7)\nprint(count)\ni = 0\n\nfor dirs in os.listdir(my_dir):\n print()\n print(dirs)\n for file in os.listdir(os.path.join(my_dir, dirs)):\n print(' ', file)\n if file == file_name:\n print(' ', os.path.join(my_dir, dirs, file), end=' - ')\n print('Размер файла -', os.path.getsize(os.path.join(my_dir, dirs, file)), 'байт!')\n my_read = open(os.path.join(my_dir, dirs, file), 'r', encoding= 'UTF-8')\n i += 1\n if i == count:\n my = my_read.read()\n print(my)\n print()\n else:\n continue\n\n","repo_name":"Obolensk/SkillBox","sub_path":"python-ds/23_Intermediate/23_2_2.py","file_name":"23_2_2.py","file_ext":"py","file_size_in_byte":769,"program_lang":"python","lang":"en","doc_type":"code","stars":2,"dataset":"github-code","pt":"17"} +{"seq_id":"14908251758","text":"#Q7 WAP to take the file name at command line argument and count the occurrence of each symbol i.e count of 'a', count of #spaces, count of commas,etc.\n\nimport sys\n\nif len(sys.argv) == 2:\n source_file = sys.argv[1]\nelse:\n source_file = input(\"Enter a source file :\")\n\nunique_char = []\nwith open(source_file,'r') as s_file:\n s = s_file.read()\n for c in s:\n if c not in unique_char:\n unique_char.append(c)\n print(unique_char)\n \n\ncount = []\nwith open(source_file,'r') as s_file:\n s = s_file.read()\n for c in unique_char:\n count.append((c, s.count(c)))\n\nfor e in count:\n print(e)\n\n# s = string.ascii_letters + \" \" + string.digits\n# #print(s)\n\n# def char_freq(s):\n# s1=[]\n# # finds out unique characters\n# for c in s:\n# if c not in s1:\n# s1.append(c)\n# # print(s1)\n# count=[]\n# for i in s1:\n# count.append((i, s.count(i)))\n# return count\n\n\n#--\n\n# import sys\n# file_name=sys.argv[1:]\n# try:\n# with open(file_name[0],'r') as f:\n# content=f.read()\n# res={}\n# for i in content:\n# res[i]=1+res.get(i,0)\n# print(res)\n# except Exception as err:\n# print(err)\n","repo_name":"leangaurav/dsc_weekday_2020_08_13","sub_path":"Assignments/Guru/AssignmentPython9-Files/q7_count_symbols.py","file_name":"q7_count_symbols.py","file_ext":"py","file_size_in_byte":1198,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"17"} +{"seq_id":"39719130687","text":"frequency = 0\nfrequencies = set()\nfoundRepeatedFrequency = False\nwhile not foundRepeatedFrequency:\n f = open(\"c:\\\\git\\\\advent-of-code-2018\\\\python\\\\day1b\\\\puzzle.txt\", \"r\")\n for change in f:\n frequency += int(change)\n if (frequency in frequencies):\n print(\"answer \" + str(frequency))\n foundRepeatedFrequency = True\n break\n frequencies.add(frequency)\n","repo_name":"ernestderry/advent-of-code-2018","sub_path":"python/day1b/main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":410,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"17"} +{"seq_id":"5956494144","text":"my_list1 = [0,1,2,3,4,5,6,6,7,8,9]\n\n#list[start:end:end]\n\n\n#sample_url ='https://coreymas.com'\n#print sample_url\n\n\nnum =[0,1,2,3,4,5,6,6,7,8,9]\nmy_list= []\n\n\n# I want 'n' for each 'n' in num\n#or n in num:\n# my_list.append(n)\n#rint (my_list)\n\n# I want 'n+n' for each 'n' in num\n#my_list =[]\n#for n in num:\n# my_list.append(n+n)\n#print(my_list)\n\n\n#my_list = [n+n for n in num]\n#print(my_list)\n\n\n# Using a map + lambda\n#my_list= map (lambda n: n+n,num)\n#\n#print(my_list)\n\n# I want 'n' for each 'n' nums if 'n' is even\n#my_list =[]\n#for n in num:\n# if n%2==0:\n# my_list.append(n)\n#print(my_list)\n\n# using a filter +lambda\n\n#my_list =filter[lambda n: n%2==0 ,num]\n#print my_list\n\n# I want a (letter, num) pair for each letter in 'abcd' and each number in '0123'\n\n#for letter in 'abcd':\n# for num in '0123':\n# my_list.append((letter,num))\n#print (my_list)\n\n#my_list=[(letter,num) for letter in 'abcd' for num in (4)]\n#print (my_list)\n\nnames = ['Bruce','Clark','peter','Logan','wade']\nheroes = ['Batman','superman','spidermen','Wolverine','Deadpool']\n#print zip(names,heroes)\n\n# I want a dict{'name': 'hero} for each name, hero in zip (name, heros)\n#my_dict= {}\n#for name, hero in zip(names,heroes):\n# my_dict[name] =hero\n#print (my_dict)\n\n#my_dict ={name: hero for name, hero in zip (names,heroes) if name != 'Peter'}\n#print (my_dict)\n\n# set comprehensions\n#nums =[1,1,2,1,3,4,3,4,5,5,6,7,8,7,9,9]\n#my_set =set()\n#for n in nums:\n# my_set.add(n)\n#print (my_set)\n\n","repo_name":"utkal08/Learning_python","sub_path":"tut11.py","file_name":"tut11.py","file_ext":"py","file_size_in_byte":1488,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"17"} +{"seq_id":"17556532729","text":"import torch\nimport sys\nfrom config import get_ADE,get_FDE,get_1DE,get_2DE\nimport config\nfrom network.vector_net import VectorNet, VectorNetWithPredicting\nfrom torch.utils.data import DataLoader, Dataset\nfrom torch.utils.data import DataLoader\nimport numpy as np\nimport os\nfrom pathlib import Path\nimport matplotlib.pyplot as plt\n\ndef get_ADE(pred, target):\n #target = target.to(config['device'])\n assert pred.shape == target.shape\n temp=torch.sum((pred - target) ** 2)\n tmp = torch.sqrt(torch.sum((pred - target) ** 2, dim=2)) # [batch_size, len]\n ade = torch.mean(tmp, dim=1, keepdim=True) # [batch_size, 1]\n return ade \n\ndataset20 = np.load(\"data_test_1000.npy\",\n allow_pickle=True)\n\ndataset = dataset20\ndata_len = len(dataset)\nn = int(0*len(dataset))\nprint(data_len)\ndataset = dataset[n:data_len-1]\nbatch = 1\ntrain_loader = DataLoader(dataset, batch_size=batch, shuffle=True,drop_last=True)\n\n\ndevice = torch.device(\"cuda\")\nprint(\"load\")\nvector_net = torch.load(\"/home/ljq/motion_prediction/pre_train\")\nvector_net = vector_net.to(device)\noptimizer = torch.optim.Adam(vector_net.parameters(), lr=0.001)\nloss_func = torch.nn.MSELoss()\nvector_net.eval()\ncnt=0\nall_loss=0\nall_loss1=0\nall_loss2=0\nall_loss3=0\nall_loss4=0\nprint(\"start test\")\nfor i, data in enumerate(train_loader):\n #print(i)\n labels = data[\"gt_preds\"].to(torch.float32)\n #print(labels.shape)\n idd = torch.tensor([0]*batch)\n outputs = vector_net(data[\"item_num\"].to(config.device), idd.to(\n config.device), data[\"polyline_list1\"], data['near_centerline'].to(\n config.device), data['goal'].to(\n config.device),0)\n #print(outputs['traj_with_gt'])\n #print(outputs['traj_with_gt'].shape,labels.shape\n feature = data[\"polyline_list1\"]\n outputs1 = outputs['traj_with_gt'].squeeze().detach().cpu().numpy()\n outputs2 = outputs['trajs'].squeeze().detach().cpu().numpy()\n #target_points=outputs['target_select'].squeeze().detach().cpu().numpy()\n #print(\"test: \",outputs2.shape,outputs1.shape)\n\n labels1 = labels.squeeze().detach().cpu().numpy()\n loss = loss_func(outputs['traj_with_gt'], labels.to(config.device))\n # print(loss.shape)\n ade = torch.mean(get_ADE(outputs['traj_with_gt'], labels.to(\n config.device))).cpu().detach().numpy()\n fde = torch.mean(get_FDE(outputs['traj_with_gt'], labels.to(\n config.device))).cpu().detach().numpy()\n\n onede = torch.mean(get_1DE(outputs['traj_with_gt'], labels.to(\n config.device))).cpu().detach().numpy()\n twode = torch.mean(get_2DE(outputs['traj_with_gt'], labels.to(\n config.device))).cpu().detach().numpy()\n\n\n all_loss = all_loss+float(ade)\n all_loss1 = all_loss1+float(loss.item()/batch)\n all_loss2 = all_loss2+float(fde)\n all_loss3 = all_loss3+float(onede)\n all_loss4 = all_loss4+float(twode)\n\n all_traj=outputs['trajs'].squeeze().detach().cpu().numpy()\n \n near_cente=data['near_centerline']\n \n plt.cla()\n plt.axis('equal') \n plt.scatter(near_cente[0,:, 0], near_cente[0, :, 1], color=\"black\", linewidth=1)\n #print(\"dd: \",target_points.shape)\n #plt.scatter(target_points[:, 0], target_points[:, 1], color=\"red\", linewidth=2)\n \n # for k in range(5):\n # each_traj = all_traj[k, :]\n # plt.scatter(each_traj[:, 0], each_traj[:, 1], s=5, c='c')\n plt.plot(labels1[:, 0], labels1[:, 1], color=\"black\", linewidth=5)\n plt.plot(outputs1[:, 0], outputs1[:, 1], color=\"green\", linewidth=5)\n colorset = [\"red\",\"yellow\",\"pink\",\"magenta\",\"bisque\"]\n for i in range(5):\n #print(outputs2[i])\n plt.plot(outputs2[i,:, 0], outputs2[i,:, 1], color=colorset[i], linewidth=1)\n for i in range(30):\n plt.scatter(feature[i][0, :, 0], feature[i][0, :, 1], s=5)\n for j in range(90):\n plt.scatter(feature[30+j][0, :, 0], feature[30+j][0, :, 1], s=5, c='r')\n plt.show()\n\n cnt=cnt+1\n \nprint(\"ade: \",cnt, all_loss/(cnt), \"fde: \",all_loss2/(cnt),all_loss3/(cnt),all_loss4/(cnt))\n","repo_name":"longjianquan/motion_prediction_tnt","sub_path":"argo_test_muti.py","file_name":"argo_test_muti.py","file_ext":"py","file_size_in_byte":4016,"program_lang":"python","lang":"en","doc_type":"code","stars":2,"dataset":"github-code","pt":"17"} +{"seq_id":"14613651124","text":"from sqlalchemy import create_engine\nfrom sqlalchemy.orm import sessionmaker\nfrom sqlalchemy.ext.declarative import declarative_base\n\nfrom src.config import config\n\n\nengine = create_engine(config.DATABASE_URL)\n\nSessionLocal = sessionmaker(autocommit=False,autoflush=False,bind=engine)\n\nBase = declarative_base()\n\ndef get_db():\n db = SessionLocal()\n try:\n yield db\n finally:\n db.close()\n\ndef create_tables():\n Base.metadata.create_all(bind=engine)","repo_name":"amansharma2910/slack-bot-poc","sub_path":"src/db.py","file_name":"db.py","file_ext":"py","file_size_in_byte":472,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"17"} +{"seq_id":"21328983346","text":"from .TurbineGovernorDynamics import TurbineGovernorDynamics\n\n\nclass GovGAST1(TurbineGovernorDynamics):\n\t'''\n\tModified single shaft gas turbine.\n\n\t:mwbase: Base for power values (MWbase) (> 0). Unit = MW. Default: 0.0\n\t:r: Permanent droop (R). Typical Value = 0.04. Default: 0.0\n\t:t1: Governor mechanism time constant (T1). T1 represents the natural valve positioning time constant of the governor for small disturbances, as seen when rate limiting is not in effect. Typical Value = 0.5. Default: 0\n\t:t2: Turbine power time constant (T2). T2 represents delay due to internal energy storage of the gas turbine engine. T2 can be used to give a rough approximation to the delay associated with acceleration of the compressor spool of a multi-shaft engine, or with the compressibility of gas in the plenum of the free power turbine of an aero-derivative unit, for example. Typical Value = 0.5. Default: 0\n\t:t3: Turbine exhaust temperature time constant (T3). T3 represents delay in the exhaust temperature and load limiting system. Typical Value = 3. Default: 0\n\t:lmax: Ambient temperature load limit (Lmax). Lmax is the turbine power output corresponding to the limiting exhaust gas temperature. Typical Value = 1. Default: 0.0\n\t:kt: Temperature limiter gain (Kt). Typical Value = 3. Default: 0.0\n\t:vmax: Maximum turbine power, PU of MWbase (Vmax). Typical Value = 1. Default: 0.0\n\t:vmin: Minimum turbine power, PU of MWbase (Vmin). Typical Value = 0. Default: 0.0\n\t:fidle: Fuel flow at zero power output (Fidle). Typical Value = 0.18. Default: 0.0\n\t:rmax: Maximum fuel valve opening rate (Rmax). Unit = PU/sec. Typical Value = 1. Default: 0.0\n\t:loadinc: Valve position change allowed at fast rate (Loadinc). Typical Value = 0.05. Default: 0.0\n\t:tltr: Valve position averaging time constant (Tltr). Typical Value = 10. Default: 0\n\t:ltrate: Maximum long term fuel valve opening rate (Ltrate). Typical Value = 0.02. Default: 0.0\n\t:a: Turbine power time constant numerator scale factor (a). Typical Value = 0.8. Default: 0.0\n\t:b: Turbine power time constant denominator scale factor (b). Typical Value = 1. Default: 0.0\n\t:db1: Intentional dead-band width (db1). Unit = Hz. Typical Value = 0. Default: 0.0\n\t:eps: Intentional db hysteresis (eps). Unit = Hz. Typical Value = 0. Default: 0.0\n\t:db2: Unintentional dead-band (db2). Unit = MW. Typical Value = 0. Default: 0.0\n\t:gv1: Nonlinear gain point 1, PU gv (Gv1). Typical Value = 0. Default: 0.0\n\t:pgv1: Nonlinear gain point 1, PU power (Pgv1). Typical Value = 0. Default: 0.0\n\t:gv2: Nonlinear gain point 2,PU gv (Gv2). Typical Value = 0. Default: 0.0\n\t:pgv2: Nonlinear gain point 2, PU power (Pgv2). Typical Value = 0. Default: 0.0\n\t:gv3: Nonlinear gain point 3, PU gv (Gv3). Typical Value = 0. Default: 0.0\n\t:pgv3: Nonlinear gain point 3, PU power (Pgv3). Typical Value = 0. Default: 0.0\n\t:gv4: Nonlinear gain point 4, PU gv (Gv4). Typical Value = 0. Default: 0.0\n\t:pgv4: Nonlinear gain point 4, PU power (Pgv4). Typical Value = 0. Default: 0.0\n\t:gv5: Nonlinear gain point 5, PU gv (Gv5). Typical Value = 0. Default: 0.0\n\t:pgv5: Nonlinear gain point 5, PU power (Pgv5). Typical Value = 0. Default: 0.0\n\t:gv6: Nonlinear gain point 6, PU gv (Gv6). Typical Value = 0. Default: 0.0\n\t:pgv6: Nonlinear gain point 6, PU power (Pgv6). Typical Value = 0. Default: 0.0\n\t:ka: Governor gain (Ka). Typical Value = 0. Default: 0.0\n\t:t4: Governor lead time constant (T4). Typical Value = 0. Default: 0\n\t:t5: Governor lag time constant (T5). Typical Value = 0. Default: 0\n\t\t'''\n\n\tcgmesProfile = TurbineGovernorDynamics.cgmesProfile\n\n\tpossibleProfileList = {'class': [cgmesProfile.DY.value, ],\n\t\t\t\t\t\t'mwbase': [cgmesProfile.DY.value, ],\n\t\t\t\t\t\t'r': [cgmesProfile.DY.value, ],\n\t\t\t\t\t\t't1': [cgmesProfile.DY.value, ],\n\t\t\t\t\t\t't2': [cgmesProfile.DY.value, ],\n\t\t\t\t\t\t't3': [cgmesProfile.DY.value, ],\n\t\t\t\t\t\t'lmax': [cgmesProfile.DY.value, ],\n\t\t\t\t\t\t'kt': [cgmesProfile.DY.value, ],\n\t\t\t\t\t\t'vmax': [cgmesProfile.DY.value, ],\n\t\t\t\t\t\t'vmin': [cgmesProfile.DY.value, ],\n\t\t\t\t\t\t'fidle': [cgmesProfile.DY.value, ],\n\t\t\t\t\t\t'rmax': [cgmesProfile.DY.value, ],\n\t\t\t\t\t\t'loadinc': [cgmesProfile.DY.value, ],\n\t\t\t\t\t\t'tltr': [cgmesProfile.DY.value, ],\n\t\t\t\t\t\t'ltrate': [cgmesProfile.DY.value, ],\n\t\t\t\t\t\t'a': [cgmesProfile.DY.value, ],\n\t\t\t\t\t\t'b': [cgmesProfile.DY.value, ],\n\t\t\t\t\t\t'db1': [cgmesProfile.DY.value, ],\n\t\t\t\t\t\t'eps': [cgmesProfile.DY.value, ],\n\t\t\t\t\t\t'db2': [cgmesProfile.DY.value, ],\n\t\t\t\t\t\t'gv1': [cgmesProfile.DY.value, ],\n\t\t\t\t\t\t'pgv1': [cgmesProfile.DY.value, ],\n\t\t\t\t\t\t'gv2': [cgmesProfile.DY.value, ],\n\t\t\t\t\t\t'pgv2': [cgmesProfile.DY.value, ],\n\t\t\t\t\t\t'gv3': [cgmesProfile.DY.value, ],\n\t\t\t\t\t\t'pgv3': [cgmesProfile.DY.value, ],\n\t\t\t\t\t\t'gv4': [cgmesProfile.DY.value, ],\n\t\t\t\t\t\t'pgv4': [cgmesProfile.DY.value, ],\n\t\t\t\t\t\t'gv5': [cgmesProfile.DY.value, ],\n\t\t\t\t\t\t'pgv5': [cgmesProfile.DY.value, ],\n\t\t\t\t\t\t'gv6': [cgmesProfile.DY.value, ],\n\t\t\t\t\t\t'pgv6': [cgmesProfile.DY.value, ],\n\t\t\t\t\t\t'ka': [cgmesProfile.DY.value, ],\n\t\t\t\t\t\t't4': [cgmesProfile.DY.value, ],\n\t\t\t\t\t\t't5': [cgmesProfile.DY.value, ],\n\t\t\t\t\t\t }\n\n\tserializationProfile = {}\n\n\t__doc__ += '\\n Documentation of parent class TurbineGovernorDynamics: \\n' + TurbineGovernorDynamics.__doc__ \n\n\tdef __init__(self, mwbase = 0.0, r = 0.0, t1 = 0, t2 = 0, t3 = 0, lmax = 0.0, kt = 0.0, vmax = 0.0, vmin = 0.0, fidle = 0.0, rmax = 0.0, loadinc = 0.0, tltr = 0, ltrate = 0.0, a = 0.0, b = 0.0, db1 = 0.0, eps = 0.0, db2 = 0.0, gv1 = 0.0, pgv1 = 0.0, gv2 = 0.0, pgv2 = 0.0, gv3 = 0.0, pgv3 = 0.0, gv4 = 0.0, pgv4 = 0.0, gv5 = 0.0, pgv5 = 0.0, gv6 = 0.0, pgv6 = 0.0, ka = 0.0, t4 = 0, t5 = 0, *args, **kw_args):\n\t\tsuper().__init__(*args, **kw_args)\n\t\n\t\tself.mwbase = mwbase\n\t\tself.r = r\n\t\tself.t1 = t1\n\t\tself.t2 = t2\n\t\tself.t3 = t3\n\t\tself.lmax = lmax\n\t\tself.kt = kt\n\t\tself.vmax = vmax\n\t\tself.vmin = vmin\n\t\tself.fidle = fidle\n\t\tself.rmax = rmax\n\t\tself.loadinc = loadinc\n\t\tself.tltr = tltr\n\t\tself.ltrate = ltrate\n\t\tself.a = a\n\t\tself.b = b\n\t\tself.db1 = db1\n\t\tself.eps = eps\n\t\tself.db2 = db2\n\t\tself.gv1 = gv1\n\t\tself.pgv1 = pgv1\n\t\tself.gv2 = gv2\n\t\tself.pgv2 = pgv2\n\t\tself.gv3 = gv3\n\t\tself.pgv3 = pgv3\n\t\tself.gv4 = gv4\n\t\tself.pgv4 = pgv4\n\t\tself.gv5 = gv5\n\t\tself.pgv5 = pgv5\n\t\tself.gv6 = gv6\n\t\tself.pgv6 = pgv6\n\t\tself.ka = ka\n\t\tself.t4 = t4\n\t\tself.t5 = t5\n\t\t\n\tdef __str__(self):\n\t\tstr = 'class=GovGAST1\\n'\n\t\tattributes = self.__dict__\n\t\tfor key in attributes.keys():\n\t\t\tstr = str + key + '={}\\n'.format(attributes[key])\n\t\treturn str\n","repo_name":"sogno-platform/cimpy","sub_path":"cimpy/cgmes_v2_4_15/GovGAST1.py","file_name":"GovGAST1.py","file_ext":"py","file_size_in_byte":6408,"program_lang":"python","lang":"en","doc_type":"code","stars":40,"dataset":"github-code","pt":"17"} +{"seq_id":"36860515925","text":"\"\"\"\nAlice and Bob continue their games with piles of stones. There are a number of piles arranged in a row, and each pile has a positive integer number of stones piles[i]. The objective of the game is to end with the most stones. \nAlice and Bob take turns, with Alice starting first. Initially, M = 1.\nOn each player's turn, that player can take all the stones in the first X remaining piles, where 1 <= X <= 2M. Then, we set M = max(M, X).\nThe game continues until all the stones have been taken.\nAssuming Alice and Bob play optimally, return the maximum number of stones Alice can get.\nExample 1:\nInput: piles = [2,7,9,4,4]\nOutput: 10\nExplanation: If Alice takes one pile at the beginning, Bob takes two piles, then Alice takes 2 piles again. Alice can get 2 + 4 + 4 = 10 piles in total. If Alice takes two piles at the beginning, then Bob can take all three piles left. In this case, Alice get 2 + 7 = 9 piles in total. So we return 10 since it's larger. \n\"\"\"\n\nfrom typing import List\nclass Solution:\n def stoneGameII(self, piles: List[int]) -> int:\n n = len(piles)\n dp = [[[-1, -1] for _ in range(n + 1)] for _ in range(n)]\n total = sum(piles)\n def max_score(start, m, turn):\n if start >= n: return 0\n if dp[start][m][turn] != -1: return dp[start][m][turn]\n curr_points = 0\n max_points = 0 if turn else total # if it's not alice's turn, bob will try to minimize left points for alice\n # go through all possible solutions\n for x in range(1, 2 * m + 1):\n end = start + x - 1 # pick piles[start: end+1]\n if end >= n: break\n curr_points += piles[end] # accumulate points\n if turn: max_points = max(max_points, curr_points + max_score(end + 1, max(x, m), 0))\n else: max_points = min(max_points, max_score(end + 1, max(x, m), 1))\n dp[start][m][turn] = max_points\n return max_points\n \n return max_score(0, 1, 1)\n\n\n\n\n\n\ns = Solution()\nprint(s.stoneGameII([2,7,9,4,4]))","repo_name":"SightVanish/MyLeetcode","sub_path":"task1140.py","file_name":"task1140.py","file_ext":"py","file_size_in_byte":2076,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"17"} +{"seq_id":"41272998427","text":"# -*- encoding: utf-8 -*-\n\nimport logging\nimport os\nimport pytest\nfrom mockito import when\nfrom b3 import TEAM_UNKNOWN\nfrom b3.config import XmlConfigParser, CfgConfigParser\nfrom b3.plugins.admin import AdminPlugin\nfrom b3.plugins.makeroom import MakeroomPlugin\n\n\nDEFAULT_PLUGIN_CONFIG_FILE = os.path.join(os.path.dirname(__file__), '../../../b3/conf/plugin_makeroom.ini')\n\n\nclass logging_disabled(object):\n \"\"\"\n context manager that temporarily disable logging.\n\n USAGE:\n with logging_disabled():\n # do stuff\n \"\"\"\n DISABLED = False\n\n def __init__(self):\n self.nested = logging_disabled.DISABLED\n\n def __enter__(self):\n if not self.nested:\n logging.getLogger('output').propagate = False\n logging_disabled.DISABLED = True\n\n def __exit__(self, exc_type, exc_val, exc_tb):\n if not self.nested:\n logging.getLogger('output').propagate = True\n logging_disabled.DISABLED = False\n\n\n@pytest.fixture\ndef console():\n with logging_disabled():\n from b3.fake import FakeConsole\n fake_console = FakeConsole('@b3/conf/b3.distribution.xml')\n\n # load the admin plugin\n with logging_disabled():\n admin_plugin = AdminPlugin(fake_console, '@b3/conf/plugin_admin.ini')\n admin_plugin._commands = {} # work around known bug in the Admin plugin which makes the _command property shared between all instances\n admin_plugin.onStartup()\n\n # make sure the admin plugin obtained by other plugins is our admin plugin\n when(fake_console).getPlugin('admin').thenReturn(admin_plugin)\n\n return fake_console\n\n\ndef plugin_maker(console_obj, conf):\n p = MakeroomPlugin(console_obj, conf)\n p.onLoadConfig()\n p.onStartup()\n return p\n\n\ndef plugin_maker_xml(console_obj, conf_content):\n conf = XmlConfigParser()\n conf.loadFromString(conf_content)\n return plugin_maker(console_obj, conf)\n\n\ndef plugin_maker_ini(console_obj, conf_content):\n conf = CfgConfigParser()\n conf.loadFromString(conf_content)\n return plugin_maker(console_obj, conf)\n\n\n@pytest.fixture\ndef superadmin(console):\n with logging_disabled():\n from b3.fake import FakeClient\n superadmin = FakeClient(console, name=\"Superadmin\", guid=\"Superadmin_guid\", groupBits=128, team=TEAM_UNKNOWN)\n superadmin.clearMessageHistory()\n return superadmin\n\n\n@pytest.fixture\ndef moderator(console):\n with logging_disabled():\n from b3.fake import FakeClient\n moderator = FakeClient(console, name=\"Moderator\", guid=\"moderator_guid\", groupBits=8, team=TEAM_UNKNOWN)\n moderator.clearMessageHistory()\n return moderator\n\n\n@pytest.fixture\ndef joe(console):\n with logging_disabled():\n from b3.fake import FakeClient\n joe = FakeClient(console, name=\"Joe\", guid=\"joe_guid\", groupBits=1, team=TEAM_UNKNOWN)\n joe.clearMessageHistory()\n return joe\n\n\n@pytest.fixture\ndef jack(console):\n with logging_disabled():\n from b3.fake import FakeClient\n jack = FakeClient(console, name=\"Jack\", guid=\"jack_guid\", groupBits=1, team=TEAM_UNKNOWN)\n jack.clearMessageHistory()\n return jack","repo_name":"dulkith/cod4","sub_path":"b3_custom_edition/tests/plugins/makeroom/__init__.py","file_name":"__init__.py","file_ext":"py","file_size_in_byte":3133,"program_lang":"python","lang":"en","doc_type":"code","stars":18,"dataset":"github-code","pt":"17"} +{"seq_id":"3275150386","text":"from .utils import getmembers\n\n\ndef derive(prototype, bind=dict()):\n Prototyper = prototyper(prototype, bind=bind)\n derived = Prototyper()\n return derived\n\n\ndef prototyper(prototype, bind=dict()):\n class Prototyper(prototype.__class__, object):\n def __init__(self, *args, **kw):\n prototype.__class__.__init__(self, *args, **kw)\n self.__metachao_prototype__ = prototype\n self.__metachao_bind__ = dict(getattr(prototype,\n '__metachao_bind__',\n ()))\n self.__metachao_bind__.update(bind)\n\n def __getattribute__(self, name):\n \"\"\"realize prototyping chain\n\n 1. instance dictionary\n 2. for callables/properties check instance's class\n (the ad-hoc Prototyper)\n 3. get attribute from prototype\n \"\"\"\n # shortcut for things we don't want to go into the prototype chain\n if name in (\n '__class__',\n '__dict__',\n '__metachao_bind__',\n '__metachao_prototype__',\n ):\n return object.__getattribute__(self, name)\n\n # no binding, if served from instance dictionary\n selfdict = self.__dict__\n if name in selfdict:\n return selfdict[name]\n\n # check class' members for properties\n attr = dict((k, v) for k, v in getmembers(self.__class__)\n if k == name and isinstance(v, property)\n ).get(name, ())\n\n # enter prototype chain\n if attr is ():\n prototype = self.__metachao_prototype__\n attr = getattr(prototype, name)\n\n # get to real function in case of methods\n attr = getattr(attr, 'im_func', attr)\n\n # bind descriptors to instance or whatever they are supposed to\n # bind to\n if hasattr(attr, '__get__'):\n bindto = self.__metachao_bind__.get(name)\n if bindto is None:\n bindto = self\n attr = attr.__get__(bindto, bindto.__class__)\n\n return attr\n\n return Prototyper\n\n\n# XXX: I don't think this will be needed anymore\ndef prototype_property(prototype, prop):\n \"\"\"prototype property\n\n - try fget on self, fallback to prototype\n - fset and fdel on self\n \"\"\"\n def fget(self):\n try:\n return prop.fget(self)\n except AttributeError:\n return prop.fget(prototype)\n return property(fget, prop.fset, prop.fdel, prop.__doc__)\n","repo_name":"chaoflow/metachao","sub_path":"src/metachao/prototype.py","file_name":"prototype.py","file_ext":"py","file_size_in_byte":2689,"program_lang":"python","lang":"en","doc_type":"code","stars":3,"dataset":"github-code","pt":"17"} +{"seq_id":"42120364564","text":"from setuptools import setup\n\npackage_name = 'lifecycle_py'\n\nsetup(\n name=package_name,\n version='0.0.0',\n packages=[package_name],\n data_files=[\n ('share/ament_index/resource_index/packages',\n ['resource/' + package_name]),\n ('share/' + package_name, ['package.xml']),\n ],\n install_requires=['setuptools'],\n zip_safe=True,\n maintainer='arthemis',\n maintainer_email='alejandroamar66@gmail.com',\n description='TODO: Package description',\n license='TODO: License declaration',\n tests_require=['pytest'],\n entry_points={\n 'console_scripts': [\n \"number_publisher=lifecycle_py.number_publisher:main\",\n \"number_publisher_lifecylce=lifecycle_py.number_publisher_lifecycle:main\",\n \"lifecycle_manager_node = lifecycle_py.lifecycle_manager_node:main\",\n \"move_robot_server=lifecycle_py.robot_server:main\",\n \"move_robot_startup=lifecycle_py.move_robot_startup:main\"\n ],\n },\n)\n","repo_name":"aleamar264/ros2_basics_advances_concepts","sub_path":"ros2_ws/src/lifecycle_py/setup.py","file_name":"setup.py","file_ext":"py","file_size_in_byte":1000,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"17"} +{"seq_id":"71722911385","text":"#!/usr/bin/env python3\nimport fileinput\nimport re\n\n# Read in the file input\ninp = [line.strip() for line in fileinput.input()]\n# Variables for storing the results\npart_1 = None\npart_2 = None\n\n# Code\nPREAMBLE_LENGTH = 25\nnumbers = []\npre_calcs = []\nfor i in range(0, len(inp)):\n number = int(inp[i])\n numbers.append(number)\n pre_calcs.append([])\n for j in range(min(PREAMBLE_LENGTH, len(numbers))):\n pre_calcs[i].append(number + numbers[-j])\n if i > PREAMBLE_LENGTH:\n valid = False\n for predessesor in pre_calcs[-PREAMBLE_LENGTH:]:\n if number in predessesor:\n valid = True\n if not valid:\n part_1 = number\n\nblock_len = 2\nfound = False\nwhile block_len < len(inp) and not found:\n current_block = []\n current_sum = 0\n for IP in inp:\n current_block.append(int(IP))\n if len(current_block) > block_len:\n current_block.pop(0)\n current_sum = sum(current_block)\n if current_sum == part_1:\n found = True\n current_block.sort()\n part_2 = (current_block[0] + current_block[-1])\n block_len += 1\n\n# Print the results\nprint(f\"Part 1: {part_1}\")\nprint(f\"Part 2: {part_2}\")\n","repo_name":"b3nj5m1n/adventofcode","sub_path":"2020/day09/solve.py","file_name":"solve.py","file_ext":"py","file_size_in_byte":1218,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"17"} +{"seq_id":"33538406458","text":"\"\"\"\r\n Copyright (c) 2016- by Dietmar W Weiss\r\n\r\n This is free software; you can redistribute it and/or modify it\r\n under the terms of the GNU Lesser General Public License as\r\n published by the Free Software Foundation; either version 3.0 of\r\n the License, or (at your option) any later version.\r\n\r\n This software is distributed in the hope that it will be useful,\r\n but WITHOUT ANY WARRANTY; without even the implied warranty of\r\n MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU\r\n Lesser General Public License for more details.\r\n\r\n You should have received a copy of the GNU Lesser General Public\r\n License along with this software; if not, write to the Free\r\n Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA\r\n 02110-1301 USA, or see the FSF site: http://www.fsf.org.\r\n\r\n Version:\r\n 2020-03-05 DWW\r\n\"\"\"\r\n\r\nimport sys\r\nfrom typing import Any, Dict, Optional, Union\r\n\r\ntry:\r\n from grayboxes.boxmodel import BoxModel\r\n from grayboxes.datatype import Float2D, Function\r\n from grayboxes.metrics import init_metrics\r\nexcept:\r\n from boxmodel import BoxModel\r\n from datatype import Float2D, Function\r\n from metrics import init_metrics\r\n\r\ntry:\r\n from grayboxes.neuraltf import Neural as NeuralTf\r\nexcept ImportError:\r\n try:\r\n from neuraltf import Neural as NeuralTf\r\n except ImportError:\r\n print('!!! Module neuraltf not imported')\r\n\r\ntry:\r\n from grayboxes.neuralnl import Neural as NeuralNl\r\nexcept ImportError:\r\n try:\r\n from neuralnl import Neural as NeuralNl\r\n except ImportError:\r\n print('!!! Module neuralnl not imported')\r\n\r\ntry:\r\n from grayboxes.neuralto import Neural as NeuralTo\r\nexcept ImportError:\r\n try:\r\n from neuralto import Neural as NeuralTo\r\n except ImportError:\r\n print('!!! Module neuralto not imported')\r\n\r\ntry:\r\n from grayboxes.splines import Splines\r\nexcept ImportError:\r\n print('!!! Module splines not imported')\r\n\r\n\r\nclass Black(BoxModel):\r\n \"\"\"\r\n Black box model y = beta(x, w) with w = arg min ||beta(X, w) - Y||_2\r\n where Y(X) is the training data and x is arbitrary input\r\n\r\n - Neural network is employed if 'splines' not in kwargs, \r\n Splines are employed otherwise\r\n\r\n - Weights of best model training trials are saved as \r\n 'self._empirical._weights'\r\n\r\n Example:\r\n X = np.linspace(0., 1., 200).reshape(-1, 1) # train input \r\n x = np.linspace(-1., 2., 100).reshape(-1, 1) # test input \r\n x = X * 1.9\r\n Y = X**2.\r\n\r\n # black box, neural network, compact variant:\r\n y = Black()(XY=(X, Y), neurons=[8, 6], x=x)\r\n\r\n # black box, neural network, expanded variant:\r\n phi = Black() # create instance of Black\r\n metrics = phi(X=X, Y=Y, neurons=[8, 6]) # training\r\n Y_prd = phi(x=X) # prediction with training input\r\n y_prd = phi(x=x) # prediction with test input\r\n \"\"\"\r\n\r\n def __init__(self, f: Function = None, identifier: str = 'Black') -> None:\r\n \"\"\"\r\n Args:\r\n f:\r\n Dummy parameter for compatibility with the other \r\n children of class BoxModel where 'f' is the theoretical \r\n submodel for a single data point\r\n\r\n identifier:\r\n Unique object identifier\r\n \"\"\"\r\n super().__init__(f=None, identifier=identifier)\r\n self._empirical: Optional[Union[NeuralTf, NeuralNl, \r\n NeuralTo, Splines]] = None\r\n \r\n @property\r\n def silent(self) -> bool:\r\n return self._silent\r\n\r\n @silent.setter\r\n def silent(self, value: bool) -> None:\r\n self._silent = value\r\n if self._empirical is not None:\r\n self._empirical._silent = value\r\n\r\n def train(self, X: Float2D, Y: Float2D, **kwargs: Any) -> Dict[str, Any]:\r\n \"\"\"\r\n Trains model, stores X and Y as self.X and self.Y, and stores\r\n performance of best training trial as self.metrics\r\n\r\n Args:\r\n X:\r\n training input, shape: (n_point, n_inp)\r\n shape (n_point,) is tolerated\r\n\r\n Y:\r\n training target, shape: (n_point, n_out)\r\n shape (n_point,) is tolerated\r\n\r\n Kwargs:\r\n backend (str):\r\n identifier of backend:\r\n 'neurolab'\r\n 'tensorflow'\r\n 'torch'\r\n default: 'tensorflow'\r\n \r\n neurons (int, 1D array of int, or None):\r\n number of neurons in hidden layer(s) of neural network\r\n\r\n splines (int, 1D array of float, or None):\r\n not specified yet\r\n \r\n trainer (str, list of str, or None):\r\n optimizer of network, see BruteForce.train()\r\n \r\n ... additional training options, see BruteForce.train()\r\n\r\n Returns:\r\n metrics of best training trial\r\n see BoxModel.train()\r\n \"\"\" \r\n self.metrics = init_metrics()\r\n self.ready = False\r\n \r\n if X is not None and Y is not None:\r\n self.set_XY(X, Y)\r\n \r\n neurons = kwargs.get('neurons', None)\r\n splines = kwargs.get('splines', None) if neurons is None else None\r\n if 'splines' not in sys.modules:\r\n splines = None\r\n \r\n if splines is None: \r\n backend = kwargs.get('backend', 'keras').lower()\r\n if backend in ('tensorflow', 'tf', 'keras',):\r\n backend = 'tensorflow'\r\n assert 'grayboxes.neuraltf' in sys.modules or \\\r\n 'neuraltf' in sys.modules\r\n elif backend in ('nl', 'neurolab',):\r\n backend = 'neurolab'\r\n assert 'grayboxes.neuralnl' in sys.modules or \\\r\n 'neuralnl' in sys.modules\r\n elif backend in ('torch', 'pytorch',):\r\n backend = 'torch'\r\n assert 'grayboxes.neuralto' in sys.modules or \\\r\n 'neuralto' in sys.modules\r\n else:\r\n backend = 'tensorflow'\r\n self.write('+++ backend: ' + str(backend))\r\n else:\r\n backend = None\r\n\r\n if splines is not None:\r\n empirical = Splines()\r\n else: \r\n if backend == 'tensorflow':\r\n empirical = NeuralTf(self.f) \r\n elif backend == 'torch':\r\n empirical = NeuralTo(self.f) \r\n elif backend == 'neurolab':\r\n empirical = NeuralNl(self.f) \r\n else:\r\n assert 0, str(backend)\r\n\r\n self.write('+++ train')\r\n \r\n if self._empirical is not None:\r\n del self._empirical\r\n self._empirical = empirical\r\n self._empirical.silent = self.silent\r\n \r\n self.metrics = self._empirical.train(self.X, self.Y, \r\n **self.kwargs_del(kwargs,'f'))\r\n self.ready = self._empirical.ready\r\n self.metrics['ready'] = self.ready\r\n\r\n return self.metrics\r\n\r\n def predict(self, x: Float2D, **kwargs: Any) -> Float2D:\r\n \"\"\"\r\n Executes box model, stores input as self.x and output as self.y\r\n\r\n Args:\r\n x:\r\n prediction input, shape: (n_point, n_inp)\r\n shape: (n_inp,) is tolerated\r\n\r\n Kwargs:\r\n Keyword arguments of emprical model\r\n\r\n Returns:\r\n prediction output, shape: (n_point, n_out)\r\n or\r\n None if self._empirical is None or not self.ready\r\n \"\"\"\r\n if not self.ready or self._empirical is None:\r\n self.y = None\r\n return self.y\r\n\r\n self.x = x # setter ensuring 2D array\r\n assert self._n_inp == self.x.shape[1], str((self._n_inp, self.x.shape))\r\n\r\n self.y = self._empirical.predict(self.x, **kwargs)\r\n \r\n return self.y\r\n","repo_name":"dwweiss/grayboxes","sub_path":"grayboxes/black.py","file_name":"black.py","file_ext":"py","file_size_in_byte":8402,"program_lang":"python","lang":"en","doc_type":"code","stars":4,"dataset":"github-code","pt":"17"} +{"seq_id":"75171383385","text":"import sys\nfrom collections import deque\n\nMAXNUM = 10001\n\n\nif __name__ == \"__main__\":\n N = int(input())\n\n depth = [0] * MAXNUM\n cost = [0] * MAXNUM\n v = [0] * MAXNUM\n adj = [[] for _ in range(MAXNUM)]\n\n for i in range(1, N+1):\n tp = list(map(int, sys.stdin.readline().split()))\n v[i] = tp[0]\n for val in tp[2:]:\n adj[val].append(i)\n depth[i] += 1\n\n q = deque()\n for i in range(1, N + 1):\n if depth[i] == 0:\n q.append(i)\n cost[i] = v[i]\n\n while q:\n x = q.popleft()\n for j in range(0, len(adj[x])):\n y = adj[x][j]\n cost[y] = max(cost[y], v[y] + cost[x])\n depth[y] -= 1\n if depth[y] == 0:\n q.append(y)\n\n answer = 0\n for i in range(1, N + 1):\n answer = max(answer, cost[i])\n\n print(answer)\n\n","repo_name":"kimnamu/ps_study","sub_path":"07_Topological_sorting/Level4/2056.py","file_name":"2056.py","file_ext":"py","file_size_in_byte":875,"program_lang":"python","lang":"ko","doc_type":"code","stars":48,"dataset":"github-code","pt":"17"} +{"seq_id":"5403583475","text":"import time\n\nfrom products_crawler.crawlers.category_keyword_crawler import CategoryKeywordCrawler\nfrom products_crawler.utils import prepare_cate_keyword_url\nfrom project.celery import app\n\napp.conf.beat_schedule = {\n 'update_aliexpress_category': {\n 'task': 'products_crawler.tasks.update_categories',\n 'schedule': 2*60*60,\n },\n}\n\n\n@app.task\ndef update_categories():\n from products_crawler.models import Category\n from django.db.models import Count\n cates = Category.objects.all().filter(keyword=None).annotate(product_count=Count('product')).order_by('-product_count')\n \n for idx,cate in enumerate(cates):\n crawl_category.delay(cate.id)\n \n@app.task\ndef crawl_keyword_category(cate_id,sleep_time=0):\n print('::KEYWORD')\n crawl_category(cate_id,sleep_time , url_function=prepare_cate_keyword_url, crawler=CategoryKeywordCrawler)\n \n \n@app.task\ndef crawl_category(cate_id,sleep_time=0,url_function=None,crawler=None):\n \n time.sleep(sleep_time)\n \n from products_crawler.models import Product,Category\n from products_crawler.utils import prepare_cate_url\n from products_crawler.crawlers.category_crawler import CategoryCrawler\n \n print('cate_id')\n print(cate_id)\n cate = Category.objects.get(id=cate_id)\n\n if not crawler:\n crawler = CategoryCrawler\n \n if not url_function:\n url_function = prepare_cate_url\n\n page_num = 10\n for p in range(page_num):\n \n url = url_function(cate,p)\n \n print(url)\n\n res = crawler(url).crawl_now()\n \n \n products = res['data']\n if len(products) == 0:\n print('\\n================')\n print('End with error ')\n break\n \n print('Got %d item(s)'%len(products))\n \n for product in products:\n \n if not product.get('category'):\n product.update({\n 'category': cate\n })\n \n _product,_ = Product.objects.update_or_create(\n product_id = product['product_id'],\n defaults = product\n )\n crawl_product_buyer.delay(prod_id=_product.id)\n \n \n@app.task\ndef crawl_product_buyer(prod_id=None):\n \n from products_crawler.models import Product,Buyer,AliexpressCookie\n from products_crawler.crawlers.transaction_crawler import TransactionCrawler\n from products_crawler.utils import search_lucky_buyer\n\n # cookie = AliexpressCookie.objects.filter(state=AliexpressCookie.STATE_OK).first()\n product = Product.objects.get(id=prod_id)\n \n for i in range(1,11):\n res = TransactionCrawler(\n trans_id = product.product_id,\n page = i,\n # cookies = cookie.cookies,\n ).crawl_now()\n \n buyers = res['data']\n\n lucky_buyer = search_lucky_buyer(buyers)\n \n \n\n for buyer in buyers:\n buyer.update({\n 'product' : product,\n 'buyer_lucky' : buyer['buyer_name'] == lucky_buyer,\n })\n _buyer,_ = Buyer.objects.update_or_create(\n product = buyer['product'],\n buyer_name = buyer['buyer_name'],\n buyer_time = buyer['buyer_time'],\n defaults = buyer\n )\n \n ","repo_name":"nix010/aliexpress_crawler","sub_path":"products_crawler/tasks.py","file_name":"tasks.py","file_ext":"py","file_size_in_byte":3411,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"17"} +{"seq_id":"43687614880","text":"import os\n\nimport dash\nimport pytest\n\nimport hidebound.server.app as application\nimport hidebound.server.components as components\nimport hidebound.server.server_tools as hst\n# ------------------------------------------------------------------------------\n\n\ndef test_liveness(app_setup, app_client):\n result = app_client.get('/healthz/live').status_code\n assert result == 200\n\n\ndef test_readiness(app_setup, app_client):\n result = app_client.get('/healthz/ready').status_code\n assert result == 200\n\n\n@pytest.mark.skipif('SKIP_SLOW_TESTS' in os.environ, reason='slow test')\ndef test_get_app(app_setup):\n result = application.get_app(testing=True)\n assert isinstance(result, dash.Dash)\n\n\ndef test_serve_stylesheet(app_setup, app_client):\n params = dict(\n COLOR_SCHEME=components.COLOR_SCHEME,\n FONT_FAMILY=components.FONT_FAMILY,\n )\n expected = hst.render_template('style.css.j2', params)\n result = next(app_client.get('/static/style.css').response)\n assert result == expected\n","repo_name":"theNewFlesh/hidebound","sub_path":"python/hidebound/server/app_test.py","file_name":"app_test.py","file_ext":"py","file_size_in_byte":1021,"program_lang":"python","lang":"en","doc_type":"code","stars":4,"dataset":"github-code","pt":"17"} +{"seq_id":"23665127212","text":"import turtle\r\nclass svgTurtle(turtle.Turtle):\r\n def __init__(self, params):\r\n self.instructions = params\r\n super().__init__()\r\n super().pd()\r\n \r\n #debug \r\n def drawCoords(self, turtleWriter):\r\n print(\"writing from\",turtleWriter)\r\n turtleWriter.setposition(0,0)\r\n coordText=str(super().xcor())\r\n coordText+=\" \"\r\n coordText+=str(super().ycor())\r\n turtleWriter.write(coordText, font=('Arial',15,'bold'), align='left')\r\n \r\n def svg_M(self, x, y): # 'M' key: moveTo\r\n print(\"M call:\",x,\",\",y)\r\n super().pd()\r\n super().pu()\r\n super().setposition(x,y)\r\n\r\n def svg_l(self, dx, dy): #'l' key: draw line to\r\n super().pd()\r\n super().setposition(dx,dy)\r\n super().pu()\r\n \r\n def render(self, debug): #start drawing from commandlist\r\n for instruction in self.instructions:\r\n self.drawCoords(debug)\r\n switch={\r\n 'M':self.svg_M(instruction[1][0], instruction[1][1]),\r\n 'l':self.svg_l(instruction[1][0], instruction[1][1])\r\n }\r\n switch.get(instruction[0],\"Invalid\")\r\n print(instruction[0],\"completed\")\r\n\r\n\r\n","repo_name":"PLUS-dextra/svg-turtle","sub_path":"svgTurtle.py","file_name":"svgTurtle.py","file_ext":"py","file_size_in_byte":1260,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"17"} +{"seq_id":"37384689507","text":"from machine import Pin\n\nfrom src.const import DEFAULT_SPAN\nfrom src.enums.state_enum import DeviceState\nfrom src.interfaces.device import Device\n\n\nclass IRQDevice(Device):\n \"\"\"\n Class created for representing irq device.\n \"\"\"\n def __init__(self, pin: int, callback, trigger: int, pull: int, span_ms: int = DEFAULT_SPAN):\n super().__init__(pin)\n self._trigger_span = span_ms\n self._initialized_pin = Pin(pin, Pin.IN, pull)\n self._callback = callback\n self._initialized_pin.irq(trigger=trigger, handler=self._do_callback)\n self._state = DeviceState.ON\n\n @property\n def trigger_span(self):\n \"\"\"\n Represents minimal time span between calling callback.\n :return: Minimal time span between presses in ms.\n \"\"\"\n return self._trigger_span\n\n @trigger_span.setter\n def trigger_span(self, span_ms: int):\n \"\"\"\n Represents minimal time span between calling callback.\n :param span_ms: Span in ms.\n \"\"\"\n if span_ms < 0:\n return\n\n self._trigger_span = span_ms\n\n @property\n def callback(self):\n \"\"\"\n Callback is function triggered by irq. Function must have at least one parameter - pin it is callback pin.\n \"\"\"\n return self._callback\n\n @callback.setter\n def callback(self, callback):\n self._callback = callback\n\n def _do_callback(self, pin):\n \"\"\"\n Function created for performing other actions before calling function callback.\n \"\"\"\n if self._state is DeviceState.BUSY:\n return\n\n self._state = DeviceState.BUSY\n\n self._callback(pin=pin)\n\n self._state = DeviceState.ON\n\n def __str__(self):\n return super(IRQDevice, self).__str__() + \\\n f\"Class: IRQDevice\\n\"\n","repo_name":"psp515/MicroPico","sub_path":"src/interfaces/device_irq.py","file_name":"device_irq.py","file_ext":"py","file_size_in_byte":1831,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"17"} +{"seq_id":"28557672313","text":"# Given a .json file, creates a graph of the proportion of Test Files/Lines vs Source at each Commit\n# expects json files in ./results/language/filename\n# For each language, it plots every json file from said language onto a graph.\n\nimport json\nimport matplotlib\nimport matplotlib.pyplot as plt\nimport numpy as np\nimport os\n\nfileTypes = [\"java\", \"py\", \"js\"] # List of all language types to check\ngraphName = \"Proportion\" # const\n# Used for subfolder name\n\ndef makeGraph( fileType, i):\n\n\n allFiles = os.listdir(\"./results/\" + i)\n\n fig, ax = plt.subplots()\n axes = plt.gca()\n\n for f in allFiles:\n fileName = f\n f = \"./results/\" + i + \"/\" + f\n print(f)\n fp = open(f, \"r\")\n data = json.load(fp)\n\n #if(data[\"source_commits\"] > 10000):\n # continue \n \n\n fp.close()\n\n\n xData = []\n yData = []\n yData2 = []\n y = 0\n y2 = 0\n y3 = 0\n y4 = 0\n for a in range(len(data[\"number_of_test_files_per_commit\"])):\n\n\n\n\n xData.append(a+1)\n y = y + data[\"number_of_test_files_per_commit\"][a]\n y2 = y2 + data[\"number_of_files_per_commit\"][a]\n if (y+y2) == 0: # y2 might be zero during division\n yData.append(0)\n else:\n yData.append(float(y)/float(y+y2)*100)\n y3 = y3 + data[\"test_lines_per_commit\"][a]\n y4 = y4 + data[\"total_lines_per_commit\"][a]\n if (y3+y4) == 0:\n yData2.append(0)\n else:\n yData2.append(float(y3)/float(y3+y4)*100) \n\n x = xData\n #y = yData # test files per commit\n y2 = yData2 # test lines per commit \n #ax.plot(x, y)\n ax.plot(x, y2)\n\n\n\n ax.legend()\n\n fileName = fileName.split(\".json\")[0]\n\n \n \n ax.set(xlabel=\"Commit #\", ylabel=\"Percentage(%)\", title=\"Percentage of Test Code Lines vs Total Lines\")\n ax.grid()\n plt.ylim(0, 100)\n # Ignore commits past a point\n if(i == \"java\"):\n axes.set_xlim([0,15000])\n\n if(i == \"py\"):\n axes.set_xlim([0,15000])\n\n if(i == \"js\"):\n axes.set_xlim([0,10000])\n\n\n try:\n os.mkdir(\"./results/\" + graphName + \"/\" + fileType)\n except:\n pass\n plt.savefig('{}.png'.format(\"./results/\" + graphName + \"/\" + fileType + \"Lines\" ))\n plt.close()\n\n\n\n\ntry:\n os.mkdir(\"./results/\" + graphName)\nexcept:\n pass\n\nfor i in fileTypes:\n\n makeGraph(i,i) \n\n \n\n\n\n","repo_name":"cmput402-w19/code-quality","sub_path":"ProportionOneGraphLines.py","file_name":"ProportionOneGraphLines.py","file_ext":"py","file_size_in_byte":2486,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"17"} +{"seq_id":"28739535142","text":"import numpy as np\nimport pandas as pd\n\nfrom src.common.utils import read_standard_dataset, calc_euclidian_dist_all, read_standard_route\nfrom src.common.vrptw_path_holder import VRPTWPathHolder\nfrom src.vrptw.vrptw_launch_entry import VRPTWLaunchEntry\n\n\nclass Statistics:\n def __init__(self, vrptw_launch_entry: VRPTWLaunchEntry, vrptw_path_holder: VRPTWPathHolder):\n self._vrptw_launch_entry = vrptw_launch_entry\n self._vrptw_path_holder = vrptw_path_holder\n\n self._cluster_launch_entry_arr = self._vrptw_launch_entry.cluster_launch_entry_arr\n self._tsptw_launch_entry_arr = self._vrptw_launch_entry.tsptw_launch_entry_arr\n\n def collect_all_stats(self):\n common_id_arr = []\n dim_arr = []\n k3_arr = []\n dataset_type_arr = []\n dataset_name_arr = []\n\n time_cluster_arr = []\n time_tsptw_arr = []\n time_common_arr = []\n\n evaluation_arr = np.empty(shape=(self._tsptw_launch_entry_arr.size, 4))\n wait_time_arr = []\n late_time_arr = []\n avg_wait_time_arr = []\n avg_late_time_arr = []\n max_wait_time_arr = []\n max_late_time_arr = []\n wait_time_part_arr = []\n late_time_part_arr = []\n\n total_time_arr = []\n\n std_wait_time_arr = []\n\n function_arr = []\n\n evaluation_old_arr = np.empty(shape=(self._tsptw_launch_entry_arr.size, 4))\n wait_time_old_arr = []\n late_time_old_arr = []\n\n # tsptw_launch_entry и cluster_launch_entry соответствуют друг другу\n for i, tsptw_launch_entry in enumerate(self._tsptw_launch_entry_arr):\n # TODO: только ради vehicle_number, может поместить куда-то количество тс?\n data = pd.read_fwf(self._vrptw_path_holder.BASE_DIR + '/input/task/'\n + tsptw_launch_entry.dataset.data_file)\n vehicle_number = int(data['VEHICLE_NUMBER'][0])\n\n self._fill_time_stats(tsptw_launch_entry, time_cluster_arr, time_tsptw_arr, time_common_arr)\n self._fill_evaluation_data(tsptw_launch_entry, vehicle_number, i,\n evaluation_arr, wait_time_arr, late_time_arr)\n self._fill_additional_time_stats(tsptw_launch_entry, vehicle_number, max_wait_time_arr, max_late_time_arr,\n wait_time_part_arr, late_time_part_arr, total_time_arr, std_wait_time_arr,\n avg_wait_time_arr, avg_late_time_arr)\n self._fill_function_stats(tsptw_launch_entry, function_arr)\n\n common_id_arr.append(tsptw_launch_entry.common_id)\n dim_arr.append(tsptw_launch_entry.dataset.dim)\n k3_arr.append(tsptw_launch_entry.cluster_k3)\n dataset_type_arr.append(tsptw_launch_entry.dataset.dataset_type)\n dataset_name_arr.append(tsptw_launch_entry.dataset.name)\n\n self._fill_evaluation_data_old(tsptw_launch_entry, vehicle_number, i,\n evaluation_old_arr, wait_time_old_arr, late_time_old_arr)\n\n return pd.DataFrame({\n 'common_id': common_id_arr,\n 'name': dataset_name_arr,\n 'dim': dim_arr,\n 'k3': k3_arr,\n 'dataset_type': dataset_type_arr,\n 'time_cluster': time_cluster_arr,\n 'time_tsptw': time_tsptw_arr,\n 'time_common': time_common_arr,\n 'distance': evaluation_arr[:, 0],\n 'wait_time': evaluation_arr[:, 1],\n 'late_time': evaluation_arr[:, 2],\n 'total_evaluation': evaluation_arr[:, 3],\n 'avg_wait_time': avg_wait_time_arr,\n 'avg_late_time': avg_late_time_arr,\n 'wait_time_per_vehicle': wait_time_arr,\n 'late_time_per_customer': late_time_arr,\n 'max_wait_time': max_wait_time_arr,\n 'max_late_time': max_late_time_arr,\n 'wait_time_part': wait_time_part_arr,\n 'late_time_part': late_time_part_arr,\n 'total_time': total_time_arr,\n 'std_wait_time': std_wait_time_arr,\n 'function': function_arr,\n\n 'distance_old': evaluation_old_arr[:, 0],\n 'wait_time_old': evaluation_old_arr[:, 1],\n 'late_time_old': evaluation_old_arr[:, 2],\n 'wait_time_old_per_vehicle': wait_time_old_arr,\n 'late_time_old_per_customer': late_time_old_arr,\n })\n\n def _fill_time_stats(self, launch_entry, time_cluster_arr, time_tsptw_arr, time_common_arr):\n time_cluster = pd.read_fwf(\n self._vrptw_path_holder.CLUSTER_OUTPUT + launch_entry.common_id + '/time_cluster.csv',\n header=None\n )\n time_tsptw = pd.read_fwf(\n self._vrptw_path_holder.TSPTW_OUTPUT + launch_entry.common_id + '/time_tsptw.csv',\n header=None\n )\n time_cluster_arr.append(time_cluster.values[0][0])\n time_tsptw_arr.append(time_tsptw.values[0][0])\n time_common_arr.append(time_cluster.values[0][0] + time_tsptw.values[0][0])\n\n def _fill_evaluation_data(self, launch_entry, vehicle_number, i, evaluation_arr, wait_time_arr, late_time_arr):\n evaluation_data = pd.read_fwf(\n self._vrptw_path_holder.EVALUATION_OUTPUT + launch_entry.common_id + '/evaluation.csv',\n header=None\n )\n evaluation_arr[i] = evaluation_data.transpose().values[0]\n\n wait_time_arr.append(evaluation_arr[i][1] / vehicle_number)\n late_time_arr.append(evaluation_arr[i][2] / launch_entry.dataset.dim)\n\n def _fill_evaluation_data_old(self, launch_entry, vehicle_number, i, evaluation_old_arr, wait_time_old_arr,\n late_time_old_arr):\n path = self._vrptw_path_holder.BASE_DIR + '/output/evaluation/' \\\n + launch_entry.dataset.name.replace('mod', 'output') + '_' + str(int(launch_entry.cluster_k3))\n\n evaluation_data = pd.read_fwf(path + '/evaluation.csv', header=None)\n evaluation_old_arr[i] = evaluation_data.transpose().values[0]\n\n wait_time_old_arr.append(evaluation_old_arr[i][1] / vehicle_number)\n late_time_old_arr.append(evaluation_old_arr[i][2] / launch_entry.dataset.dim)\n\n def _fill_additional_time_stats(self, launch_entry, vehicle_number,\n max_wait_time_arr, max_late_time_arr, wait_time_part_arr,\n late_time_part_arr, total_time_arr, std_wait_time_arr,\n avg_wait_time_arr, avg_late_time_arr):\n max_wait_time = 0.0\n max_late_time = 0.0\n\n wait_counter = 0\n late_counter = 0\n\n total_travel_time = 0.0\n\n wait_arr_route = []\n late_arr_route = []\n for j in range(vehicle_number):\n cur_report = pd.read_csv(self._vrptw_path_holder.TSPTW_OUTPUT\n + launch_entry.common_id\n + '/report{}.csv'.format(j), delimiter=' ')\n\n time_df = cur_report[['Wait_Time', 'Late_Time', 'Leave_Time']].values\n for row in time_df[:-2]:\n if float(row[0]) > max_wait_time:\n max_wait_time = float(row[0])\n if float(row[1]) > max_late_time:\n max_late_time = float(row[1])\n\n if float(row[0]) > 0.0:\n wait_counter += 1\n if float(row[1]) > 0.0:\n late_counter += 1\n total_travel_time += float(time_df[-1][2])\n wait_arr_route.append(float(time_df[-1][0]))\n late_arr_route.append(float(time_df[-1][1]))\n\n max_wait_time_arr.append(max_wait_time)\n max_late_time_arr.append(max_late_time)\n wait_time_part_arr.append(wait_counter / launch_entry.dataset.dim)\n late_time_part_arr.append(late_counter / launch_entry.dataset.dim)\n\n total_time_arr.append(total_travel_time / vehicle_number)\n\n avg_wait_time_arr.append(np.mean(wait_arr_route))\n avg_late_time_arr.append(np.mean(late_arr_route))\n\n std_wait_time_arr.append(np.std(wait_arr_route))\n\n ### collect stats from bks\n def collect_bks_stats(self):\n bks_routes_df = self._parse_bks_routes()\n\n wait_time_sum_arr = []\n late_time_sum_arr = []\n total_time_sum_arr = []\n distance_sum_arr = []\n\n add_wait_arr = []\n add_late_arr = []\n add_total_arr = []\n\n avg_wait_time_arr = []\n avg_late_time_arr = []\n\n std_wait_time_arr = []\n\n dataset_name_arr = []\n\n grouped = bks_routes_df.groupby('dataset')\n\n for name, group in grouped:\n ### evaluation_stats\n wait_time_sum = group['wait_time'].sum()\n late_time_sum = group['late_time'].sum()\n total_time_sum = group['total_time'].sum()\n distance_sum = group['distance'].sum()\n\n wait_time_sum_arr.append(wait_time_sum)\n late_time_sum_arr.append(late_time_sum)\n total_time_sum_arr.append(total_time_sum)\n distance_sum_arr.append(distance_sum)\n\n ### additional time_stats\n vehicle_number = group.shape[0]\n dim = group['dim'].iloc[0]\n\n add_wait_arr.append(wait_time_sum / vehicle_number)\n add_late_arr.append(late_time_sum / dim)\n add_total_arr.append(total_time_sum / vehicle_number)\n\n avg_wait_time_arr.append(np.mean(group['wait_time'].values))\n avg_late_time_arr.append(np.mean(group['late_time'].values))\n ### std\n std_wait_time_arr.append(np.std(group['wait_time'].values))\n\n dataset_name_arr.append(name)\n\n return pd.DataFrame({\n 'name': dataset_name_arr,\n 'wait_time': wait_time_sum_arr,\n 'late_time': late_time_sum_arr,\n 'total_time': total_time_sum_arr,\n 'distance': distance_sum_arr,\n 'avg_wait_time': avg_wait_time_arr,\n 'avg_late_time': avg_late_time_arr,\n 'std_wait_time': std_wait_time_arr,\n 'wait_time_per_vehicle': add_wait_arr,\n 'late_time_per_customer': add_late_arr\n })\n\n ### parse bks and save stats\n def _parse_bks_routes(self):\n dataset_arr = self._vrptw_launch_entry.dataset_arr\n\n wait_time_all = np.array([])\n late_time_all = np.array([])\n total_time_all = np.array([])\n dist_all = np.array([])\n\n dataset_name_all = np.array([])\n dim_all = np.array([])\n\n for d in dataset_arr:\n dataset = pd.read_fwf(self._vrptw_path_holder.BASE_DIR + '/input/task/'\n + d.data_file)\n\n points_dataset, tws_all, service_time_all = read_standard_dataset(dataset)\n euclidian_dist = calc_euclidian_dist_all(points_dataset)\n\n routes_dataset = read_standard_route(self._vrptw_path_holder.BASE_DIR + '/input/bks/' + d.data_file)\n routes_len = len(routes_dataset)\n wait_time_arr = np.zeros(routes_len)\n late_time_arr = np.zeros(routes_len)\n total_time_arr = np.zeros(routes_len)\n dist_arr = np.zeros(routes_len)\n\n dataset_name_arr = np.full(routes_len, d.name)\n dim_arr = np.full(routes_len, d.dim)\n\n for i, route in enumerate(routes_dataset):\n cur_time = 0.0\n cur_wait_time = 0.0\n cur_late_time = 0.0\n prev = 0\n cur_distance = 0.0\n for j in route:\n cur_distance += euclidian_dist[prev][j]\n\n cur_time += euclidian_dist[prev][j]\n wait_time = tws_all[j][0] - cur_time\n late_time = cur_time - tws_all[j][1]\n if wait_time > 0.0:\n cur_wait_time += wait_time\n cur_time = tws_all[j][0]\n if late_time > 0.0:\n cur_late_time += late_time\n\n cur_time += service_time_all[j]\n prev = j\n cur_time += euclidian_dist[prev][0]\n cur_distance += euclidian_dist[prev][0]\n\n wait_time_arr[i] = cur_wait_time\n late_time_arr[i] = cur_late_time\n total_time_arr[i] = cur_time\n\n dist_arr[i] = cur_distance\n dataset_name_arr[i] = d.name\n dim_arr[i] = d.dim\n wait_time_all = np.append(wait_time_all, wait_time_arr)\n late_time_all = np.append(late_time_all, late_time_arr)\n total_time_all = np.append(total_time_all, total_time_arr)\n dist_all = np.append(dist_all, dist_arr)\n\n dataset_name_all = np.append(dataset_name_all, dataset_name_arr)\n dim_all = np.append(dim_all, dim_arr)\n\n return pd.DataFrame({\n 'dataset': dataset_name_all,\n 'dim': dim_all,\n 'wait_time': wait_time_all,\n 'late_time': late_time_all,\n 'total_time': total_time_all,\n 'distance': dist_all\n })\n\n def _fill_function_stats(self, launch_entry, function_arr):\n function_data = pd.read_csv(\n self._vrptw_path_holder.CLUSTER_FUNC_OUTPUT + launch_entry.common_id + '/function.csv',\n header=None, index_col=0\n )\n\n function_arr.append(function_data.values[:, 0].tolist())\n","repo_name":"Stranger488/vrptw-ga-k-medoid","sub_path":"src/common/statistics.py","file_name":"statistics.py","file_ext":"py","file_size_in_byte":13570,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"17"} +{"seq_id":"43586890615","text":"import PySimpleGUI as sg\nsg.theme('SandyBeach')\nlayout = [\n [sg.Text('Version 0.3'),\n ],\n [sg.Text('Developed by Jabka125'),\n ],\n [sg.Button('Start'),\n ],\n [sg.Output(size=(60, 15))],\n [sg.Cancel()]\n]\nwindow = sg.Window('Minada16', layout)\nwhile True: # The Event Loop\n event, values = window.read()\n # print(event, values) #debug\n if event == sg.WIN_CLOSED or event == 'Cancel': # if user closes window or clicks cancel\n break","repo_name":"Jabka125/Minada16","sub_path":"design.py","file_name":"design.py","file_ext":"py","file_size_in_byte":498,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"17"} +{"seq_id":"26786605813","text":"from setuptools import setup\nimport sys, os\n\nhere = os.path.abspath(os.path.dirname(__file__))\nREADME = open(os.path.join(here, 'README.md')).read()\n\nsetup(name='zrpc',\n version='0.1',\n description=\"0mq RPC client and server\",\n long_description=README,\n classifiers=[\n 'Intended Audience :: Developers',\n 'Development Status :: 4 - Beta',\n 'Programming Language :: Python',\n 'License :: OSI Approved :: BSD License',\n ],\n keywords='zmq rpc',\n author='Joshua Forman',\n author_email='josh@yoshrote.com',\n url='',\n license='BSD',\n py_modules=['zrpc'],\n include_package_data=True,\n zip_safe=False,\n install_requires=['zmq'],\n entry_points=\"\"\"\n # -*- Entry points: -*-\n \"\"\",\n )\n","repo_name":"yoshrote/zrpc","sub_path":"setup.py","file_name":"setup.py","file_ext":"py","file_size_in_byte":807,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"17"} +{"seq_id":"21285808762","text":"import math\nA, B, C = map(int, input().split())\n\nleft = min((C-B)/A, (C+B)/A)\nright = max((C-B)/A, (C+B)/A)\n\n\ndef cal(x):\n return C - A*x - B*math.sin(x)\n\ndiff = 1\n\nwhile abs(diff) > 0.0000001:\n mid = (left + right)/2\n diff = cal(mid)\n if diff > 0:\n left = mid\n else:\n right = mid\n print(mid)\n\nprint(mid)\n","repo_name":"boham97/BOJ","sub_path":"14786.py","file_name":"14786.py","file_ext":"py","file_size_in_byte":337,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"17"} +{"seq_id":"16684351253","text":"#!/usr/bin/env python3\n\nfrom obspy import UTCDateTime\nfrom obspy import Stream\nfrom obspy.clients.fdsn import Client\n\ndef get_and_remove_response(station, channel, location, output, t1, duration=60):\n client = Client(\"http://service-nrt.geonet.org.nz\")\n st = client.get_waveforms(\n network=\"NZ\", station=station, location=location,\n channel=channel, starttime=t1, endtime=t1 + duration)\n tr = Stream()\n for n in range(len(st)):\n st.merge()[n]\n inv = client.get_stations(\n network=st[n].stats.network, station=st[n].stats.station, \n location=st[n].stats.location, channel=st[n].stats.channel, \n level=\"response\", startbefore=t1, endafter=t1 + duration)\n # pre_filt = (0.005, 0.006, 30.0, 35.0)\n st[n].remove_response(output=output, pre_filt=False, plot=False,\n water_level=60, inventory=inv)\n tr += st[n]\n \n return tr\n\n# pre_filt = [0.01,1,25,30]\ntr = get_and_remove_response(station=\"WHSZ\", channel=\"HH*\", location=\"10\", output=\"VEL\", t1=UTCDateTime(2021, 11, 17, 00, 41, 30))\n# tr += get_and_remove_response(station=\"RIZ\", channel=\"H**\", location=\"10\", output=\"ACC\", t1=UTCDateTime(2021, 3, 4, 17, 41, 30))\n\ntr.plot(equal_scale=False)\n","repo_name":"CBurton90/cburton","sub_path":"seis_tools/general_plots/quick_6ch_mseed.py","file_name":"quick_6ch_mseed.py","file_ext":"py","file_size_in_byte":1258,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"17"} +{"seq_id":"3516282165","text":"import numpy as np\nimport os\nfrom datetime import datetime\nimport copy\nimport time\nimport pickle as pkl\nimport isaacgym\nimport torch\nfrom model_free_agility.envs import *\n\n\ndef class_to_dict(obj) -> dict:\n if not hasattr(obj, \"__dict__\"):\n return obj\n result = {}\n for key in dir(obj):\n if key.startswith(\"_\") or key == \"terrain\":\n continue\n element = []\n val = getattr(obj, key)\n if isinstance(val, list):\n for item in val:\n element.append(class_to_dict(item))\n else:\n element = class_to_dict(val)\n result[key] = element\n return result\n\n\ndef export_policy_as_jit(actor_critic, path):\n os.makedirs(path, exist_ok=True)\n path = os.path.join(path, 'policy_1.pt')\n model = copy.deepcopy(actor_critic.actor).to('cpu')\n traced_script_module = torch.jit.script(model)\n traced_script_module.save(path)\n\n\ndef export_rma_policy_as_jit(actor_critic, path):\n os.makedirs(path, exist_ok=True)\n adaptation_module_path = os.path.join(path, 'adaptation_module.pt')\n body_path = os.path.join(path, 'body.pt')\n adaptation_module = copy.deepcopy(actor_critic.adaptation_module).to('cpu')\n body_model = copy.deepcopy(actor_critic.actor_body).to('cpu')\n traced_script_adaptation_module = torch.jit.script(adaptation_module)\n traced_script_body_module = torch.jit.script(body_model)\n traced_script_adaptation_module.save(adaptation_module_path)\n traced_script_body_module.save(body_path)\n\n\ndef export_rma_disentangled_policy_as_jit(actor_critic, path):\n os.makedirs(path, exist_ok=True)\n\n for i, adaptation_module in enumerate(actor_critic.adaptation_modules):\n adaptation_module_path = os.path.join(path, f'adaptation_module_{i}.pt')\n adaptation_module = copy.deepcopy(adaptation_module).to('cpu')\n traced_script_adaptation_module = torch.jit.script(adaptation_module)\n traced_script_adaptation_module.save(adaptation_module_path)\n\n body_path = os.path.join(path, 'body.pt')\n body_model = copy.deepcopy(actor_critic.actor_body).to('cpu')\n traced_script_body_module = torch.jit.script(body_model)\n traced_script_body_module.save(body_path)\n\n\ndef export_cse_policy_as_jit(actor_critic, path):\n os.makedirs(path, exist_ok=True)\n\n adaptation_module_path = os.path.join(path, f'adaptation_module.pt')\n adaptation_module = copy.deepcopy(actor_critic.adaptation_module).to('cpu')\n traced_script_adaptation_module = torch.jit.script(adaptation_module)\n traced_script_adaptation_module.save(adaptation_module_path)\n\n body_path = os.path.join(path, 'body.pt')\n body_model = copy.deepcopy(actor_critic.actor_body).to('cpu')\n traced_script_body_module = torch.jit.script(body_model)\n traced_script_body_module.save(body_path)\n\n\ndef construct_observation_encoder(env_cfg):\n # we also need to encode heightmap info, etc\n env_vars = vars(env_cfg.env)\n assert \"num_observations\" in env_vars.keys()\n return env_vars\n\n\ndef bundle_for_deployment(experiment_name, label, jumper=False):\n # load policy\n from legged_gym.envs.base.legged_robot_config import LeggedRobotCfg\n from legged_gym.envs.mini_cheetah.mini_cheetah_config import config_mini_cheetah\n from legged_gym.envs.go1.go1_config import config_go1\n # from legged_gym.scripts.helpers import class_to_dict\n\n config_go1(LeggedRobotCfg)\n\n from ml_logger import logger\n logger.configure(prefix=experiment_name)\n\n input(logger.glob(\"*\"))\n params = logger.load_pkl(\"parameters.pkl\")\n print(params)\n alg_name = params[0][\"kwargs\"][\"Args.alg_name\"]\n if alg_name == \"rma\":\n from legged_rl.rma_disentangled import ActorCriticRMA\n from legged_gym.envs.wrappers.rma_wrapper import RMAWrapper\n from legged_rl.rma_disentangled.actor_critic_rma import AC_Args\n elif alg_name == \"cse\":\n from legged_rl.concurrent_se import ActorCriticRMA\n from legged_gym.envs.wrappers.rma_wrapper import RMAWrapper\n from legged_rl.concurrent_se.actor_critic_rma import AC_Args\n else:\n print(f\"Unknown alg: {alg_name} !\")\n return 0\n AC_Args._update(params[0]['kwargs'])\n LeggedRobotCfg.env._update(params[0]['kwargs'])\n LeggedRobotCfg.commands._update(params[0]['kwargs'])\n LeggedRobotCfg.control._update(params[0]['kwargs'])\n LeggedRobotCfg.init_state._update(params[0]['kwargs'])\n # input(AC_Args.adaptation_module_hidden_dims)\n LeggedRobotCfg.env.num_observations = 63\n\n actor_critic = ActorCriticRMA(\n num_obs=LeggedRobotCfg.env.num_observations,\n num_privileged_obs=LeggedRobotCfg.env.num_privileged_obs,\n num_obs_history=LeggedRobotCfg.env.num_observations * \\\n LeggedRobotCfg.env.num_observation_history,\n num_actions=LeggedRobotCfg.env.num_actions)\n\n weights = logger.load_torch(\"checkpoints/ac_weights_last.pt\")\n # weights = logger.load_torch(\"checkpoints/ac_weights_001600.pt\")\n actor_critic.load_state_dict(state_dict=weights)\n # actor_critic.to(env.device)\n\n policy = actor_critic.act_inference\n\n # if \"rma\" in experiment_name or \"control_frequency\" in experiment_name:\n obs = {\"obs\": torch.zeros((1, LeggedRobotCfg.env.num_observations)), \"obs_history\": torch.zeros(\n (1, LeggedRobotCfg.env.num_observations * LeggedRobotCfg.env.num_observation_history)), \"privileged_obs\": None}\n # else:\n # obs = torch.zeros((1, LeggedRobotCfg.env.num_observations))\n tstart = time.time()\n num_steps = 1000\n for i in range(num_steps):\n actions = policy(obs)\n print(f\"frequency: {num_steps / (time.time() - tstart)} Hz\")\n\n # we want: the jit file; the env configuration in dict form\n # env_cfg = load_dict[\"env_cfg\"]\n # env_cfg_encoding = construct_observation_encoder(env_cfg)\n # print(env_cfg_encoding)\n env_cfg_encoding = class_to_dict(LeggedRobotCfg)\n\n datetime = time.strftime(\"%Y_%m_%d-%H_%M\")\n path = f\"../models/{label}_{datetime}/\"\n # if \"rma\" in experiment_name or \"control_frequency\" in experiment_name:\n # export_rma_policy_as_jit(actor_critic, path=path)\n if alg_name == \"rma\":\n export_rma_disentangled_policy_as_jit(actor_critic, path=path)\n elif alg_name == \"cse\":\n export_cse_policy_as_jit(actor_critic, path=path)\n else:\n print(\"Could not export policy, unknown architecture!!\")\n\n with open(path + \"data.pkl\", 'wb') as file:\n pkl.dump({\"env_cfg\": env_cfg_encoding,\n }, file)\n\n print(\"Done\")\n\n\nif __name__ == '__main__':\n import os\n\n os.environ['ML_LOGGER_ROOT'] = \"http://escher.csail.mit.edu:8080\"\n from ml_logger import logger\n\n experiment_name = \"/geyang/rapid-locomotion/2022-06-02/train/164442-test\"\n label = \"20220524_blind_robust_platformer_300\"\n\n bundle_for_deployment(experiment_name, label, jumper=True)\n print('I am done')\n","repo_name":"geyang/unitree-go1-setup-guide","sub_path":"jetson_deploy/scripts/prepare_policy_ge.py","file_name":"prepare_policy_ge.py","file_ext":"py","file_size_in_byte":6909,"program_lang":"python","lang":"en","doc_type":"code","stars":3,"dataset":"github-code","pt":"17"} +{"seq_id":"20410851295","text":"from ..buffer import Buffer\nfrom ..constants import WHITESPACES, EOL, DELIMITERS, CR, LF, STRING_ESCAPED, DEFAULT_ENCODING\nfrom ..types import *\nfrom ..exceptions import ParserException\n\n\nclass BasicTypesParser(object):\n \"\"\" can parse basic PDF types \"\"\"\n\n exception_class = ParserException\n indirect_references_allowed = True\n empty_names_allowed = True\n\n def __init__(self, fileobj_or_buffer, offset=0):\n if isinstance(fileobj_or_buffer, Buffer):\n self.buffer = fileobj_or_buffer\n else:\n self.buffer = Buffer(fileobj_or_buffer, offset)\n\n @property\n def current(self):\n return self.buffer.current\n\n @property\n def is_eof(self):\n return self.buffer.is_eof\n\n def next(self):\n return self.buffer.next()\n\n def prev(self):\n return self.buffer.prev()\n\n def read(self, n):\n return self.buffer.read(n)\n\n def read_backward(self, n):\n return self.buffer.read_backward(n)\n\n def get_state(self):\n return self.buffer.get_state()\n\n def set_state(self, state):\n return self.buffer.set_state(state)\n\n def reset(self, n):\n return self.buffer.reset(n)\n\n def on_parser_error(self, message):\n # ToDo: display parsing context here\n raise self.exception_class(message)\n\n def spaces(self):\n if self.is_whitespace:\n self.on_parser_error(\"Whitespace character expected\")\n self.maybe_spaces()\n\n def maybe_spaces(self):\n while self.is_whitespace:\n self.next()\n\n def maybe_spaces_or_comments(self):\n self.maybe_spaces()\n comments = []\n res = ''\n while self.current == b'%':\n comments.append(self.comment())\n self.maybe_spaces()\n if comments:\n # return multiline comment\n res = Comment(\"\\n\".join(comments))\n return res\n\n def eol(self):\n \"\"\" EOL is either CR or LF or the both \"\"\"\n if self.current not in EOL:\n self.on_parser_error(\"EOL expected\")\n self.maybe_eol()\n\n def maybe_eol(self):\n \"\"\" EOL is either CR or LF or the both except for the streams \"\"\"\n if self.current == CR:\n self.next()\n if self.current == LF:\n self.next()\n elif self.current == LF:\n self.next()\n\n @property\n def is_eol(self):\n return self.current is not None and self.current in EOL\n\n @property\n def is_whitespace(self):\n return self.current is not None and self.current in WHITESPACES\n\n @property\n def is_delimiter(self):\n return self.current is not None and self.current in DELIMITERS\n\n @property\n def is_regular(self):\n return self.current is not None and not (self.is_whitespace or self.is_delimiter)\n\n @property\n def is_digit(self):\n return self.current is not None and self.current in b'0123456789'\n\n @property\n def is_hex_digit(self):\n return self.current is not None and self.current in b'0123456789ABCDEFabcdef'\n\n def null(self):\n \"\"\"\n null token\n\n >>> s = b'null'\n >>> BasicTypesParser(s, 0).null() is null\n True\n\n >>> s = b'none'\n >>> BasicTypesParser(s, 0).null()\n Traceback (most recent call last):\n ...\n pdfreader.exceptions.ParserException: null token expected\n \"\"\"\n val = self.read(4)\n if val != b'null':\n self.on_parser_error(\"null token expected\")\n return null\n\n def true(self):\n \"\"\"\n true token\n\n >>> s = b'true'\n >>> BasicTypesParser(s, 0).true()\n True\n\n >>> s = b'True'\n >>> BasicTypesParser(s, 0).true()\n Traceback (most recent call last):\n ...\n pdfreader.exceptions.ParserException: true token expected\n \"\"\"\n val = self.read(4)\n if val != b'true':\n self.on_parser_error(\"true token expected\")\n return True\n\n def false(self):\n \"\"\"\n false token\n\n\n >>> s = b'false'\n >>> BasicTypesParser(s, 0).false()\n False\n\n >>> s = b'False'\n >>> BasicTypesParser(s, 0).false()\n Traceback (most recent call last):\n ...\n pdfreader.exceptions.ParserException: false token expected\n \"\"\"\n val = self.read(5)\n if val != b'false':\n self.on_parser_error(\"false token expected\")\n return False\n\n def comment(self):\n \"\"\"\n\n >>> s = b'%any occurance of %-sign outside of string or stream until EOL (not including) is a comment\\\\n'\n >>> BasicTypesParser(s, 0).comment()\n '%any occurance of %-sign outside of string or stream until EOL (not including) is a comment'\n\n Empty comment\n >>> s = b'%\\\\n'\n >>> BasicTypesParser(s, 0).comment()\n '%'\n \"\"\"\n if self.current != b\"%\":\n self.on_parser_error(\"% expected\")\n line = b\"\"\n while not self.is_eol:\n line += self.next()\n self.eol()\n return Comment(line.decode(DEFAULT_ENCODING))\n\n def numeric(self):\n \"\"\"\n\n >>> s = b'0'\n >>> BasicTypesParser(s, 0).numeric()\n 0\n\n >>> s = b'123'\n >>> BasicTypesParser(s, 0).numeric()\n 123\n\n >>> s = b'+123'\n >>> BasicTypesParser(s, 0).numeric()\n 123\n\n >>> s = b'-123'\n >>> BasicTypesParser(s, 0).numeric()\n -123\n\n >>> s = b'-3.5'\n >>> BasicTypesParser(s, 0).numeric()\n Decimal('-3.5')\n\n >>> s = b'+3.0'\n >>> BasicTypesParser(s, 0).numeric()\n Decimal('3.0')\n\n >>> s = b'.01'\n >>> BasicTypesParser(s, 0).numeric()\n Decimal('0.01')\n\n >>> s = b'+.01'\n >>> BasicTypesParser(s, 0).numeric()\n Decimal('0.01')\n\n >>> s = b'-.01'\n >>> BasicTypesParser(s, 0).numeric()\n Decimal('-0.01')\n\n \"\"\"\n is_negative = False\n is_integer = True\n if self.current == b\"+\":\n self.next()\n elif self.current == b\"-\":\n is_negative = True\n self.next()\n ipart, fpart = b'', b''\n\n # read integer part\n while self.is_digit:\n ipart += self.current\n self.next()\n\n # read point if exists\n if self.current == b'.':\n is_integer = False\n self.next()\n while self.is_digit:\n fpart += self.next()\n\n if not ipart and not fpart:\n self.on_parser_error(\"Invalid numeric token\")\n\n if not ipart:\n ipart = b'0'\n if not fpart:\n fpart = b'0'\n\n if is_integer:\n val = int(ipart.decode(DEFAULT_ENCODING))\n else:\n val = Decimal(\"{}.{}\".format(ipart.decode(DEFAULT_ENCODING), fpart.decode(DEFAULT_ENCODING)))\n\n if is_negative:\n val = -val\n\n return val\n\n def non_negative_int(self):\n n = self.numeric()\n if not isinstance(n, Integer) or n < 0:\n self.on_parser_error(\"Non negative int expected\")\n return n\n\n def name(self):\n \"\"\"\n >>> s = b'/Name'\n >>> BasicTypesParser(s, 0).name()\n 'Name'\n\n >>> s = b'/Name#20with#20spaces'\n >>> BasicTypesParser(s, 0).name()\n 'Name with spaces'\n\n >>> s = b'/Name#with!^speci_#0_als#'\n >>> BasicTypesParser(s, 0).name()\n 'Name#with!^speci_#0_als#'\n\n >>> s = b'/'\n >>> BasicTypesParser(s, 0).name()\n ''\n\n >>> s = b'/'\n >>> p = BasicTypesParser(s, 0)\n >>> p.empty_names_allowed = False\n >>> p.name()\n Traceback (most recent call last):\n ...\n pdfreader.exceptions.ParserException: Empty /Name found\n\n >>> s = b'Name'\n >>> BasicTypesParser(s, 0).name()\n Traceback (most recent call last):\n ...\n pdfreader.exceptions.ParserException: Name token expected\n \"\"\"\n if self.current != b'/':\n self.on_parser_error(\"Name token expected\")\n token = b''\n self.next()\n while self.is_regular:\n if self.current == b'#':\n self.next()\n code = b''\n for i in range(2):\n if not self.is_hex_digit:\n break\n code += self.next()\n if len(code) == 2:\n # must be exactly 2 characters\n token += chr(int(code.decode(DEFAULT_ENCODING), 16)).encode(DEFAULT_ENCODING)\n else:\n # leave as is\n token += b'#' + code\n else:\n token += self.next()\n if not self.empty_names_allowed and not token:\n self.on_parser_error(\"Empty /Name found\")\n\n return Name(token.decode(DEFAULT_ENCODING))\n\n def dictionary_or_stream_or_hexstring(self):\n if self.current != b\"<\":\n self.on_parser_error(\"Dict or hexstring expected\")\n self.next()\n val = None\n if self.current == b\"<\":\n self.prev()\n val = self.dictionary()\n # stream may come after the dict\n self.maybe_spaces_or_comments()\n if self.current == b's':\n val = self._stream(val)\n elif self.is_hex_digit or self.is_whitespace or self.current == b'>':\n # < 09FF> and <> are possible\n self.prev()\n val = self.hexstring()\n else:\n self.on_parser_error(\"Dict, stream or hexstring expected\")\n return val\n\n def dictionary(self):\n \"\"\"\n\n >>> s = b'<<>>'\n >>> BasicTypesParser(s, 0).dictionary()\n {}\n\n >>> s = b'''<< /Type /Example\n ... /Subtype /DictExample\n ... /Version 0.01\n ... /IntegerItem 12\n ... /StringItem (a string)\n ... /ArrayItem [1 2]\n ... /ObjRef 12 0 R\n ... /SubDictionary <<\n ... /Item1 true\n ... /Item2 false\n ... /Item3 null\n ... /Item4 (OK)\n ... >>\n ... >>'''\n >>> expected = {'Type': 'Example', 'Subtype': 'DictExample', 'Version': Decimal('0.01'), 'IntegerItem': 12,\n ... 'StringItem': b'a string', 'ArrayItem': [1, 2], 'ObjRef': IndirectReference(12, 0),\n ... 'SubDictionary': {'Item1': True, 'Item2': False, 'Item3': None, 'Item4': b'OK'}}\n >>> BasicTypesParser(s, 0).dictionary() == expected\n True\n\n \"\"\"\n pfx = self.read(2)\n if pfx != b'<<':\n self.on_parser_error(\"Dictionary expected\")\n res = {}\n self.maybe_spaces_or_comments()\n while self.current != b'>':\n key = self.name()\n self.maybe_spaces_or_comments()\n res[key] = self.object()\n self.maybe_spaces_or_comments()\n self.next()\n if self.next() != b'>':\n self.on_parser_error(\"End of dictionary >> expected \")\n return res\n\n def stream(self):\n \"\"\"\n Parses stream (dict + binary data)\n\n >>> s = b'''<<\n ... /Length 10\n ... >>\n ... stream\\\\r\\\\n***data***\\\\nendstream'''\n >>> BasicTypesParser(s, 0).stream()\n \n\n \"\"\"\n d = self.dictionary()\n # binary data comes after dict\n self.maybe_spaces_or_comments()\n return self._stream(d)\n\n def _stream(self, d):\n \"\"\"\n Parses binary data which is part of Stream object itself\n\n >>> d = dict(Length=10)\n\n >>> s = b'stream\\\\r\\\\n***data***\\\\nendstream'\n >>> BasicTypesParser(s, 0)._stream(d).stream\n b'***data***'\n\n >>> s = b'stream\\\\n***data***\\\\r\\\\nendstream'\n >>> BasicTypesParser(s, 0)._stream(d).stream\n b'***data***'\n\n >>> s = b'stream\\\\n***data***\\\\rendstream'\n >>> BasicTypesParser(s, 0)._stream(d).stream\n b'***data***'\n\n Work around wrong length. See https://github.com/maxpmaxp/pdfreader/issues/68\n 1. Length greater than real data length\n >>> d = dict(Length=2)\n >>> s = b'''stream\\\\n\\\\nendstream\\\\n\\\\n\\\\n\\\\n\\\\n\\\\n'''\n >>> BasicTypesParser(s, 0)._stream(d).stream\n b''\n\n 2. Length less than real data length\n >>> d = dict(Length=1)\n >>> s = b'''stream\\\\n***data***\\\\nendstream\\\\n\\\\n\\\\n\\\\n\\\\n'''\n >>> BasicTypesParser(s, 0)._stream(d).stream\n b'***data***'\n \"\"\"\n length = d['Length']\n token = self.read(6)\n if token != b'stream':\n self.on_parser_error(\"stream expected\")\n # `stream` keyword must be followed by CR+LF or by LF, but NOT by CR alone\n ch = self.next()\n if ch == CR:\n ch = self.next()\n if ch != LF:\n logging.warning(\"Missing LF after `stream` token - [CR]LF expected. Trying to proceed.\")\n self.prev()\n\n state = self.get_state()\n\n data = self.read(length)\n # According to the spec EOL should be after the data and before endstream\n # But some files do not follow this.\n #\n # See data/leesoil-cases-2.pdf\n #\n # self.eol()\n self.maybe_spaces()\n token = self.read(9)\n if token != b'endstream':\n # Work around wrong length. See https://github.com/maxpmaxp/pdfreader/issues/68\n err_state = self.get_state()\n logging.warning(\"Wrong stream length: {}. Trying to work around the issue.\".format(length))\n self.set_state(state)\n data = self.read(9)\n while not data.endswith(b'endstream'):\n ch = self.next()\n if ch is None:\n self.set_state(err_state)\n self.on_parser_error(\"endstream expected\")\n data += ch\n\n data = data[:-9]\n while data and data[-1:] in EOL:\n data = data[:-1]\n\n return Stream(d, data)\n\n def hexstring(self):\n \"\"\"\n >>> s = b'<01020a0B>'\n >>> BasicTypesParser(s, 0).hexstring()\n '01020A0B'\n\n\n >>> s = b'<0>'\n >>> BasicTypesParser(s, 0).hexstring()\n '00'\n\n >>> s = b'<01 AA FF 1>'\n >>> BasicTypesParser(s, 0).hexstring()\n '01AAFF10'\n\n >>> s = b'<>'\n >>> BasicTypesParser(s, 0).hexstring()\n ''\n\n >>> s = b'<0011XX>'\n >>> BasicTypesParser(s, 0).hexstring()\n Traceback (most recent call last):\n ...\n pdfreader.exceptions.ParserException: Wrong hexadecimal string\n\n \"\"\"\n if self.current != b\"<\":\n self.on_parser_error(\"Hexadecimal string expected\")\n self.next()\n token = b''\n self.maybe_spaces_or_comments()\n while self.is_hex_digit:\n token += self.next()\n self.maybe_spaces_or_comments()\n\n ch = self.next()\n if ch != b'>':\n self.on_parser_error(\"Wrong hexadecimal string\")\n if len(token) % 2:\n # if there is an odd number of digits - the last one should be assumed 0\n token += b'0'\n return HexString(token.decode(DEFAULT_ENCODING).upper())\n\n def array(self):\n \"\"\"\n\n >>> s = b'[]'\n >>> BasicTypesParser(s, 0).array()\n []\n\n >>> s = b'[-1.5 (Regular string) <> 0 10 5 R]'\n >>> BasicTypesParser(s, 0).array()\n [Decimal('-1.5'), 'AABBCC', b'Regular string', {'Name': 'Value'}, 0, ]\n\n \"\"\"\n if self.current != b'[':\n self.on_parser_error(\"Array expected\")\n self.next()\n array = Array()\n self.maybe_spaces_or_comments()\n while self.current != b']':\n array.append(self.object())\n self.maybe_spaces_or_comments()\n self.next() # skip enclosing bracket\n return array\n\n def string(self):\n \"\"\"\n The following are valid literal strings\n\n >>> s = b'(This is a string)'\n >>> BasicTypesParser(s, 0).string()\n b'This is a string'\n\n >>> s = b'''(Strings may contain newlines\n ... and such.)'''\n >>> BasicTypesParser(s, 0).string()\n b'Strings may contain newlines\\\\nand such.'\n\n >>> s = b'''(Strings may contain balanced parenthesis () and special characters (*!&}^% and so on).)'''\n >>> BasicTypesParser(s, 0).string()\n b'Strings may contain balanced parenthesis () and special characters (*!&}^% and so on).'\n\n Empty strings are allowed\n >>> s = b'()'\n >>> BasicTypesParser(s, 0).string()\n b''\n\n Multiline strings come with reverse solidus wollowed by CR, LF or the both.\n >>> s = b'''(This is \\\\\n ... a multiline \\\\\n ... string)'''\n >>> BasicTypesParser(s, 0).string()\n b'This is a multiline string'\n\n >>> s = b'(This string has escaped chars in it \\\\\\\\n\\\\\\\\r\\\\\\\\t\\\\\\\\b\\\\\\\\f\\\\\\\\(\\\\\\\\)\\\\\\\\\\\\\\\\)'\n >>> BasicTypesParser(s, 0).string()\n b'This string has escaped chars in it \\\\n\\\\r\\\\t\\\\x08\\\\x0c()\\\\\\\\'\n\n >>> s = b'(This string contains 2 \\\\\\\\245octal characters\\\\\\\\307)'\n >>> BasicTypesParser(s, 0).string()\n b'This string contains 2 ¥octal charactersÇ'\n\n >>> s = b'(The octal ddd may contain 1,2 or 3 octal digits: \\\\\\\\2,\\\\\\\\20,\\\\\\\\245)'\n >>> BasicTypesParser(s, 0).string()\n b'The octal ddd may contain 1,2 or 3 octal digits: \\\\x02,\\\\x10,¥'\n\n >>> s = b'(\\\\\\\\0053 denotes 2 characters Ctl+E followed by the digit 3)'\n >>> BasicTypesParser(s, 0).string()\n b'\\\\x053 denotes 2 characters Ctl+E followed by the digit 3'\n \"\"\"\n\n if self.current != b'(':\n self.on_parser_error(\"String expected\")\n val = b''\n self.next()\n while True:\n ch = self.next()\n if ch == b'(':\n self.prev()\n val += b\"(\" + self.string() + b\")\"\n elif ch == b'\\\\':\n ch = self.next()\n if ch in b\"01234567\":\n # octal code comes up to 3 characters\n code = ch\n for _ in range(2):\n if self.current not in b\"01234567\":\n break\n code += self.next()\n icode = int(code, 8)\n # 8 bits values are allowed only\n if icode <= 255:\n val += bytes([icode])\n else:\n # leave as is\n val += b\"\\\\\" + code\n elif ch in EOL:\n # multiline string - just skip\n self.prev()\n self.eol()\n else:\n # unescape or leave as is\n val += STRING_ESCAPED.get(ch) or (b\"\\\\\" + ch)\n elif ch == b')':\n break\n else:\n val += ch\n return String(val)\n\n def _get_parser(self):\n method = None\n if self.current == b'<':\n method = self.dictionary_or_stream_or_hexstring\n elif self.current == b'[':\n method = self.array\n elif self.current == b'(':\n method = self.string\n elif self.current == b'n':\n method = self.null\n elif self.current == b'f':\n method = self.false\n elif self.current == b't':\n method = self.true\n elif self.current in b'+-.':\n method = self.numeric\n elif self.current in b'1234567890':\n if self.indirect_references_allowed:\n method = self.numeric_or_indirect_reference\n else:\n method = self.numeric\n elif self.current == b\"/\":\n method = self.name\n return method\n\n def object(self):\n val = None\n self.maybe_spaces_or_comments()\n method = self._get_parser()\n if method:\n val = method()\n else:\n self.on_parser_error(\"Unexpected token\")\n return val\n\n def indirect_reference(self):\n \"\"\"\n >>> s = b'10 5 R'\n >>> BasicTypesParser(s, 0).indirect_reference()\n \n\n \"\"\"\n num = self.non_negative_int()\n self.maybe_spaces_or_comments()\n gen = self.non_negative_int()\n self.maybe_spaces_or_comments()\n ch = self.next()\n if ch != b'R':\n self.on_parser_error('R keyword expected')\n return IndirectReference(num, gen)\n\n def numeric_or_indirect_reference(self):\n state = self.get_state()\n try:\n val = self.indirect_reference()\n except ParserException:\n self.set_state(state)\n val = self.numeric()\n return val\n\n def token(self):\n \"\"\" just a token which does not belong to any of PDF types like: def, findresource, ET, BT\n >>> s = b'def'\n >>> BasicTypesParser(s, 0).token()\n 'def'\n\n >>> s = b'T*'\n >>> BasicTypesParser(s, 0).token()\n 'T*'\n\n >>> s = b'10T*'\n >>> BasicTypesParser(s, 0).token()\n Traceback (most recent call last):\n ...\n pdfreader.exceptions.ParserException: Regular non-digit character expected\n \"\"\"\n if not self.is_regular or self.is_digit:\n self.on_parser_error(\"Regular non-digit character expected\")\n\n token = b''\n while self.is_regular:\n token += self.next()\n return Token(token.decode(DEFAULT_ENCODING))\n\n def expected_name(self, value):\n name = self.name()\n if name != value:\n self.on_parser_error(\"%s expected\".format(value))\n return name\n\n def expected_token(self, value):\n token = self.token()\n if token != value:\n self.on_parser_error(\"%s expected\".format(value))\n return token\n\n def expected_numeric(self, value):\n n = self.numeric()\n if n != value:\n self.on_parser_error(\"%s expected\".format(value))\n return n\n\n\nif __name__ == \"__main__\":\n import doctest\n doctest.testmod()\n","repo_name":"maxpmaxp/pdfreader","sub_path":"pdfreader/parsers/base.py","file_name":"base.py","file_ext":"py","file_size_in_byte":22509,"program_lang":"python","lang":"en","doc_type":"code","stars":103,"dataset":"github-code","pt":"17"} +{"seq_id":"33847299073","text":"# Program that takes a list of numbers and makes a new list of only the first and last elements of the given list.\r\ndef enter_list():\r\n size = int(input(\"Enter the size of list (integers): \"))\r\n num_list = []\r\n for count in range(1,size+1):\r\n num_list.append(int(input(\"Enter number {}: \".format(count))))\r\n print(\"Entered list is: \",num_list)\r\n return num_list\r\n\r\ndef extract_first_and_last_elements(numlist):\r\n new = []\r\n numlist_len = len(numlist)\r\n for count in range(0,numlist_len):\r\n if count == 0 or count == numlist_len-1:\r\n new.append(numlist[count])\r\n print(new)\r\n\r\n\r\n\r\ntemp = enter_list()\r\nextract_first_and_last_elements(temp)\r\n","repo_name":"vigneshkumarv/PracticePython","sub_path":"listends.py","file_name":"listends.py","file_ext":"py","file_size_in_byte":692,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"17"} +{"seq_id":"38679112041","text":"from django.shortcuts import render\nfrom rest_framework.views import APIView, Response, status\nfrom usuario.models import *\nfrom agenda.models import Agenda\nfrom api.serializers import *\nfrom datetime import datetime as date_time\nfrom rest_framework.decorators import api_view\nimport datetime\n\n@api_view(['GET'])\ndef get_especialidades(request):\n if request.method == 'GET':\n espec = Medico.objects.all().values_list('especialidade')\n return Response(espec)\n\nclass UserAPI(APIView):\n def get(self,request):\n PACIENTE = \"1\"\n FUNCIONARIO = \"2\"\n try:\n usuario_tipo = request.query_params['tipo']\n except:\n Response(\"O tipo do usuário é obrigatório na requisição\", status=status.HTTP_400_BAD_REQUEST)\n try: \n usuario_id = request.query_params['usuario_id']\n except:\n usuario_id = None\n\n try:\n especialidade = request.query_params['especialidade']\n except:\n especialidade = None\n \n try:\n if usuario_tipo == PACIENTE:\n if usuario_id:\n pacientes = Paciente.objects.all().get(id=usuario_id)\n pacientes_response = PacienteSerializer(pacientes, many = False).data\n else:\n pacientes = Paciente.objects.all()\n pacientes_response = PacienteSerializer(pacientes, many = True).data\n return Response(pacientes_response)\n elif usuario_tipo == FUNCIONARIO:\n if usuario_id:\n funcionarios = Funcionario.objects.all().get(id=usuario_id)\n funcionario_response = FuncionarioSerializer(funcionarios, many = False).data\n else:\n funcionarios = Funcionario.objects.all()\n funcionario_response = FuncionarioSerializer(funcionarios, many = True).data\n return Response(funcionario_response)\n else:\n if usuario_id:\n medicos = Medico.objects.all().get(id=usuario_id)\n medico_response = MedicoSerializer(medicos, many = False).data\n elif especialidade:\n medicos = Medico.objects.all().filter(especialidade=especialidade)\n medico_response = MedicoSerializer(medicos, many = True).data\n else:\n medicos = Medico.objects.all()\n medico_response = MedicoSerializer(medicos, many = True).data\n return Response(medico_response)\n except Exception as e:\n return Response(\"Erro ao obter usuário, verifique se o tipo e o id do usuário estão de acordo\", status=status.HTTP_400_BAD_REQUEST)\n\n def post(self,request):\n PACIENTE = 1\n FUNCIONARIO = 2\n usuario_tipo = request.data.get('tipo')\n data_contrato = request.data.get('data_contrato') or None\n if data_contrato:\n date = datetime.date(int(data_contrato.split('-')[0]),int(data_contrato.split('-')[1]),int(data_contrato.split('-')[2]))\n\n\n email = request.data.get('email')\n try:\n if Usuario.objects.all().get(email=email):\n return Response(u'Email ja cadastrado', status=status.HTTP_400_BAD_REQUEST)\n except Usuario.DoesNotExist:\n pass\n \n try:\n endereco = Endereco()\n endereco.bairro = request.data.get('bairro')\n endereco.cep = request.data.get('cep')\n endereco.cidade = request.data.get('cidade')\n endereco.estado = request.data.get('estado')\n endereco.save()\n except Exception:\n return Response(u'Não foi possível criar o endereço', status=status.HTTP_400_BAD_REQUEST)\n\n if usuario_tipo == PACIENTE:\n try:\n paciente = Paciente()\n paciente.nome = request.data.get('nome')\n paciente.email = request.data.get('email')\n paciente.telefone = request.data.get('telefone')\n paciente.endereco = endereco\n paciente.peso = request.data.get('peso')\n paciente.altura = request.data.get('altura')\n paciente.tipo_sanguineo = request.data.get('tipo_sanguineo')\n paciente.save()\n except Exception as e :\n return Response(u'Não foi possível criar o Paciente', status=status.HTTP_400_BAD_REQUEST)\n return Response('OK')\n\n elif usuario_tipo == FUNCIONARIO:\n try:\n funcionario = Funcionario()\n funcionario.nome = request.data.get('nome')\n funcionario.email = request.data.get('email')\n funcionario.telefone = request.data.get('telefone')\n funcionario.endereco = endereco\n funcionario.password = request.data.get('password')\n funcionario.salario = request.data.get('salario')\n funcionario.data_contrato = date\n funcionario.save()\n except Exception as e :\n return Response(u'Não foi possível criar o Funcionário', status=status.HTTP_400_BAD_REQUEST)\n return Response('OK')\n else:\n try:\n medico = Medico()\n medico.nome = request.data.get('nome')\n medico.email = request.data.get('email')\n medico.telefone = request.data.get('telefone')\n medico.endereco = endereco\n medico.password = request.data.get('password')\n medico.salario = request.data.get('salario')\n medico.data_contrato = date\n medico.especialidade = request.data.get('especialidade')\n medico.crm = request.data.get('crm')\n medico.save()\n except Exception as e :\n return Response(u'Não foi possível criar o Médico')\n return Response('OK')\n\nclass EnderecoAPI(APIView):\n def get(self,request):\n try:\n usuario = request.query_params['usuario']\n except:\n usuario = None\n \n if usuario:\n usuario_endereco = Usuario.objects.all().get(id=int(usuario)).endereco\n print(usuario_endereco)\n endereco_response = EnderecoSerializer(usuario_endereco, many = False).data\n return Response(endereco_response)\n \n enderecos = Endereco.objects.all()\n enderecos_response = EnderecoSerializer(enderecos, many = True).data\n return Response(enderecos_response)\n\n\nclass LoginAPI(APIView):\n def post(self,request):\n password = request.data.get('password') or None\n email = request.data.get('email') or None\n usuario = ''\n if not password or not email:\n return Response('Sem email ou senha', status=status.HTTP_400_BAD_REQUEST)\n\n try:\n usuario = Funcionario.objects.all().get(email=email,password=password)\n except Usuario.DoesNotExist:\n return Response('Não encontrado', status=status.HTTP_404_NOT_FOUND)\n \n try:\n tipo = Medico.objects.all().get(id=usuario.id)\n tipo = 3\n except Medico.DoesNotExist:\n tipo = 2\n\n usuario_response = UsuarioSerializer(usuario,many=False).data\n return Response({'usuario':usuario_response, 'tipo':tipo})\n\n\nclass AgendaAPI(APIView):\n def post(self,request):\n data = request.data.get('data') or None\n paciente_email = request.data.get('paciente_email') or None\n medico_id = request.data.get('medico_id') or None\n\n if not data or not paciente_email or not medico_id:\n return Response('Faltam dados na requisição', status=status.HTTP_400_BAD_REQUEST)\n \n \n agendamento = Agenda()\n agendamento.data = date_time.strptime(data, '%d/%m/%y %H:%M:%S')\n try:\n agendamento.medico = Medico.objects.all().get(id=medico_id)\n except Medico.DoesNotExist:\n return Response('Medico não existe', status=status.HTTP_404_NOT_FOUND)\n\n try:\n usuario = Usuario.objects.all().get(email=paciente_email).id\n agendamento.paciente = Paciente.objects.all().get(id=usuario)\n except :\n return Response('Paciente não existe', status=status.HTTP_404_NOT_FOUND)\n\n agendamento.save()\n return Response('OK', status=status.HTTP_200_OK)\n\n def get(self,request):\n try:\n medico_id = request.query_params['medico_id'] \n except : \n medico_id = None\n\n if not medico_id:\n agendamentos = Agenda.objects.all().order_by('id')\n agendamentos_serializer = AgendaSerializer(agendamentos,many=True).data\n\n return Response(agendamentos_serializer,status=status.HTTP_200_OK)\n\n agendamentos = Agenda.objects.all().filter(medico_id=int(medico_id))\n if not agendamentos:\n return Response('Não foram encontrados agendamentos para esse médico', status=status.HTTP_404_NOT_FOUND)\n\n agendamentos_serializer = AgendaSerializer(agendamentos,many=True).data\n return Response(agendamentos_serializer,status=status.HTTP_200_OK)\n \n\n\n ","repo_name":"RosaneSilvaF/clinica","sub_path":"api/views.py","file_name":"views.py","file_ext":"py","file_size_in_byte":9341,"program_lang":"python","lang":"pt","doc_type":"code","stars":0,"dataset":"github-code","pt":"17"} +{"seq_id":"16114340250","text":"import functools\nimport gym\nimport logging\nimport numpy as np\nimport time\nfrom typing import Callable, Dict, List, Optional, Tuple, Type, Union\n\nfrom ray.rllib.models.modelv2 import ModelV2\nfrom ray.rllib.models.torch.torch_modelv2 import TorchModelV2\nfrom ray.rllib.models.torch.torch_action_dist import TorchDistributionWrapper\nfrom ray.rllib.policy.policy import Policy, LEARNER_STATS_KEY\nfrom ray.rllib.policy.sample_batch import SampleBatch\nfrom ray.rllib.policy.rnn_sequencing import pad_batch_to_sequences_of_same_size\nfrom ray.rllib.utils import force_list\nfrom ray.rllib.utils.annotations import override, DeveloperAPI\nfrom ray.rllib.utils.framework import try_import_torch\nfrom ray.rllib.utils.schedules import ConstantSchedule, PiecewiseSchedule\nfrom ray.rllib.utils.torch_ops import convert_to_non_torch_type, \\\n convert_to_torch_tensor\nfrom ray.rllib.utils.tracking_dict import UsageTrackingDict\nfrom ray.rllib.utils.typing import ModelGradients, ModelWeights, \\\n TensorType, TrainerConfigDict\n\ntorch, _ = try_import_torch()\n\nlogger = logging.getLogger(__name__)\n\n\n@DeveloperAPI\nclass TorchPolicy(Policy):\n \"\"\"Template for a PyTorch policy and loss to use with RLlib.\n\n Attributes:\n observation_space (gym.Space): observation space of the policy.\n action_space (gym.Space): action space of the policy.\n config (dict): config of the policy.\n model (TorchModel): Torch model instance.\n dist_class (type): Torch action distribution class.\n \"\"\"\n\n @DeveloperAPI\n def __init__(\n self,\n observation_space: gym.spaces.Space,\n action_space: gym.spaces.Space,\n config: TrainerConfigDict,\n *,\n model: ModelV2,\n loss: Callable[[\n Policy, ModelV2, Type[TorchDistributionWrapper], SampleBatch\n ], Union[TensorType, List[TensorType]]],\n action_distribution_class: Type[TorchDistributionWrapper],\n action_sampler_fn: Optional[Callable[[\n TensorType, List[TensorType]\n ], Tuple[TensorType, TensorType]]] = None,\n action_distribution_fn: Optional[Callable[[\n Policy, ModelV2, TensorType, TensorType, TensorType\n ], Tuple[TensorType, Type[TorchDistributionWrapper], List[\n TensorType]]]] = None,\n max_seq_len: int = 20,\n get_batch_divisibility_req: Optional[Callable[[Policy],\n int]] = None,\n ):\n \"\"\"Build a policy from policy and loss torch modules.\n\n Note that model will be placed on GPU device if CUDA_VISIBLE_DEVICES\n is set. Only single GPU is supported for now.\n\n Args:\n observation_space (gym.spaces.Space): observation space of the\n policy.\n action_space (gym.spaces.Space): action space of the policy.\n config (TrainerConfigDict): The Policy config dict.\n model (ModelV2): PyTorch policy module. Given observations as\n input, this module must return a list of outputs where the\n first item is action logits, and the rest can be any value.\n loss (Callable[[Policy, ModelV2, Type[TorchDistributionWrapper],\n SampleBatch], Union[TensorType, List[TensorType]]]): Callable\n that returns a single scalar loss or a list of loss terms.\n action_distribution_class (Type[TorchDistributionWrapper]): Class\n for a torch action distribution.\n action_sampler_fn (Callable[[TensorType, List[TensorType]],\n Tuple[TensorType, TensorType]]): A callable returning a\n sampled action and its log-likelihood given Policy, ModelV2,\n input_dict, explore, timestep, and is_training.\n action_distribution_fn (Optional[Callable[[Policy, ModelV2,\n Dict[str, TensorType], TensorType, TensorType],\n Tuple[TensorType, type, List[TensorType]]]]): A callable\n returning distribution inputs (parameters), a dist-class to\n generate an action distribution object from, and\n internal-state outputs (or an empty list if not applicable).\n Note: No Exploration hooks have to be called from within\n `action_distribution_fn`. It's should only perform a simple\n forward pass through some model.\n If None, pass inputs through `self.model()` to get distribution\n inputs.\n The callable takes as inputs: Policy, ModelV2, input_dict,\n explore, timestep, is_training.\n max_seq_len (int): Max sequence length for LSTM training.\n get_batch_divisibility_req (Optional[Callable[[Policy], int]]]):\n Optional callable that returns the divisibility requirement\n for sample batches given the Policy.\n \"\"\"\n self.framework = \"torch\"\n super().__init__(observation_space, action_space, config)\n if torch.cuda.is_available():\n logger.info(\"TorchPolicy running on GPU.\")\n self.device = torch.device(\"cuda\")\n else:\n logger.info(\"TorchPolicy running on CPU.\")\n self.device = torch.device(\"cpu\")\n self.model = model.to(self.device)\n # Auto-update model's inference view requirements, if recurrent.\n self._update_model_inference_view_requirements_from_init_state()\n # Combine view_requirements for Model and Policy.\n self.view_requirements.update(self.model.inference_view_requirements)\n\n self.exploration = self._create_exploration()\n self.unwrapped_model = model # used to support DistributedDataParallel\n self._loss = loss\n self._optimizers = force_list(self.optimizer())\n\n self.dist_class = action_distribution_class\n self.action_sampler_fn = action_sampler_fn\n self.action_distribution_fn = action_distribution_fn\n\n # If set, means we are using distributed allreduce during learning.\n self.distributed_world_size = None\n\n self.max_seq_len = max_seq_len\n self.batch_divisibility_req = get_batch_divisibility_req(self) if \\\n callable(get_batch_divisibility_req) else \\\n (get_batch_divisibility_req or 1)\n\n @override(Policy)\n @DeveloperAPI\n def compute_actions(\n self,\n obs_batch: Union[List[TensorType], TensorType],\n state_batches: Optional[List[TensorType]] = None,\n prev_action_batch: Union[List[TensorType], TensorType] = None,\n prev_reward_batch: Union[List[TensorType], TensorType] = None,\n info_batch: Optional[Dict[str, list]] = None,\n episodes: Optional[List[\"MultiAgentEpisode\"]] = None,\n explore: Optional[bool] = None,\n timestep: Optional[int] = None,\n **kwargs) -> \\\n Tuple[TensorType, List[TensorType], Dict[str, TensorType]]:\n\n explore = explore if explore is not None else self.config[\"explore\"]\n timestep = timestep if timestep is not None else self.global_timestep\n\n with torch.no_grad():\n seq_lens = torch.ones(len(obs_batch), dtype=torch.int32)\n input_dict = self._lazy_tensor_dict({\n SampleBatch.CUR_OBS: np.asarray(obs_batch),\n \"is_training\": False,\n })\n if prev_action_batch is not None:\n input_dict[SampleBatch.PREV_ACTIONS] = \\\n np.asarray(prev_action_batch)\n if prev_reward_batch is not None:\n input_dict[SampleBatch.PREV_REWARDS] = \\\n np.asarray(prev_reward_batch)\n state_batches = [\n convert_to_torch_tensor(s, self.device)\n for s in (state_batches or [])\n ]\n return self._compute_action_helper(input_dict, state_batches,\n seq_lens, explore, timestep)\n\n @override(Policy)\n def compute_actions_from_input_dict(\n self,\n input_dict: Dict[str, TensorType],\n explore: bool = None,\n timestep: Optional[int] = None,\n **kwargs) -> \\\n Tuple[TensorType, List[TensorType], Dict[str, TensorType]]:\n\n explore = explore if explore is not None else self.config[\"explore\"]\n timestep = timestep if timestep is not None else self.global_timestep\n\n with torch.no_grad():\n # Pass lazy (torch) tensor dict to Model as `input_dict`.\n input_dict = self._lazy_tensor_dict(input_dict)\n # Pack internal state inputs into (separate) list.\n state_batches = [\n input_dict[k] for k in input_dict.keys() if \"state_in\" in k[:8]\n ]\n # Calculate RNN sequence lengths.\n seq_lens = np.array([1] * len(input_dict[\"obs\"])) \\\n if state_batches else None\n\n return self._compute_action_helper(input_dict, state_batches,\n seq_lens, explore, timestep)\n\n def _compute_action_helper(self, input_dict, state_batches, seq_lens,\n explore, timestep):\n \"\"\"Shared forward pass logic (w/ and w/o trajectory view API).\n\n Returns:\n Tuple:\n - actions, state_out, extra_fetches, logp.\n \"\"\"\n if self.action_sampler_fn:\n action_dist = dist_inputs = None\n state_out = state_batches\n actions, logp, state_out = self.action_sampler_fn(\n self,\n self.model,\n input_dict,\n state_out,\n explore=explore,\n timestep=timestep)\n else:\n # Call the exploration before_compute_actions hook.\n self.exploration.before_compute_actions(\n explore=explore, timestep=timestep)\n if self.action_distribution_fn:\n dist_inputs, dist_class, state_out = \\\n self.action_distribution_fn(\n self,\n self.model,\n input_dict[SampleBatch.CUR_OBS],\n explore=explore,\n timestep=timestep,\n is_training=False)\n else:\n dist_class = self.dist_class\n dist_inputs, state_out = self.model(input_dict, state_batches,\n seq_lens)\n\n if not (isinstance(dist_class, functools.partial)\n or issubclass(dist_class, TorchDistributionWrapper)):\n raise ValueError(\n \"`dist_class` ({}) not a TorchDistributionWrapper \"\n \"subclass! Make sure your `action_distribution_fn` or \"\n \"`make_model_and_action_dist` return a correct \"\n \"distribution class.\".format(dist_class.__name__))\n action_dist = dist_class(dist_inputs, self.model)\n\n # Get the exploration action from the forward results.\n actions, logp = \\\n self.exploration.get_exploration_action(\n action_distribution=action_dist,\n timestep=timestep,\n explore=explore)\n\n input_dict[SampleBatch.ACTIONS] = actions\n\n # Add default and custom fetches.\n extra_fetches = self.extra_action_out(input_dict, state_batches,\n self.model, action_dist)\n\n # Action-dist inputs.\n if dist_inputs is not None:\n extra_fetches[SampleBatch.ACTION_DIST_INPUTS] = dist_inputs\n\n # Action-logp and action-prob.\n if logp is not None:\n extra_fetches[SampleBatch.ACTION_PROB] = \\\n torch.exp(logp.float())\n extra_fetches[SampleBatch.ACTION_LOGP] = logp\n\n # Update our global timestep by the batch size.\n self.global_timestep += len(input_dict[SampleBatch.CUR_OBS])\n\n return convert_to_non_torch_type((actions, state_out, extra_fetches))\n\n @override(Policy)\n @DeveloperAPI\n def compute_log_likelihoods(\n self,\n actions: Union[List[TensorType], TensorType],\n obs_batch: Union[List[TensorType], TensorType],\n state_batches: Optional[List[TensorType]] = None,\n prev_action_batch: Optional[Union[List[TensorType],\n TensorType]] = None,\n prev_reward_batch: Optional[Union[List[\n TensorType], TensorType]] = None) -> TensorType:\n\n if self.action_sampler_fn and self.action_distribution_fn is None:\n raise ValueError(\"Cannot compute log-prob/likelihood w/o an \"\n \"`action_distribution_fn` and a provided \"\n \"`action_sampler_fn`!\")\n\n with torch.no_grad():\n input_dict = self._lazy_tensor_dict({\n SampleBatch.CUR_OBS: obs_batch,\n SampleBatch.ACTIONS: actions\n })\n if prev_action_batch is not None:\n input_dict[SampleBatch.PREV_ACTIONS] = prev_action_batch\n if prev_reward_batch is not None:\n input_dict[SampleBatch.PREV_REWARDS] = prev_reward_batch\n seq_lens = torch.ones(len(obs_batch), dtype=torch.int32)\n state_batches = [\n convert_to_torch_tensor(s, self.device)\n for s in (state_batches or [])\n ]\n\n # Exploration hook before each forward pass.\n self.exploration.before_compute_actions(explore=False)\n\n # Action dist class and inputs are generated via custom function.\n if self.action_distribution_fn:\n dist_inputs, dist_class, _ = self.action_distribution_fn(\n policy=self,\n model=self.model,\n obs_batch=input_dict[SampleBatch.CUR_OBS],\n explore=False,\n is_training=False)\n # Default action-dist inputs calculation.\n else:\n dist_class = self.dist_class\n dist_inputs, _ = self.model(input_dict, state_batches,\n seq_lens)\n\n action_dist = dist_class(dist_inputs, self.model)\n log_likelihoods = action_dist.logp(input_dict[SampleBatch.ACTIONS])\n return log_likelihoods\n\n @override(Policy)\n @DeveloperAPI\n def learn_on_batch(\n self, postprocessed_batch: SampleBatch) -> Dict[str, TensorType]:\n # Callback handling.\n self.callbacks.on_learn_on_batch(\n policy=self, train_batch=postprocessed_batch)\n\n # Compute gradients (will calculate all losses and `backward()`\n # them to get the grads).\n grads, fetches = self.compute_gradients(postprocessed_batch)\n\n # Step the optimizers.\n for i, opt in enumerate(self._optimizers):\n opt.step()\n\n if self.model:\n fetches[\"model\"] = self.model.metrics()\n return fetches\n\n @override(Policy)\n @DeveloperAPI\n def compute_gradients(self,\n postprocessed_batch: SampleBatch) -> ModelGradients:\n # Get batch ready for RNNs, if applicable.\n pad_batch_to_sequences_of_same_size(\n postprocessed_batch,\n max_seq_len=self.max_seq_len,\n shuffle=False,\n batch_divisibility_req=self.batch_divisibility_req,\n )\n\n train_batch = self._lazy_tensor_dict(postprocessed_batch)\n\n # Calculate the actual policy loss.\n loss_out = force_list(\n self._loss(self, self.model, self.dist_class, train_batch))\n\n # Call Model's custom-loss with Policy loss outputs and train_batch.\n if self.model:\n loss_out = self.model.custom_loss(loss_out, train_batch)\n\n # Give Exploration component that chance to modify the loss (or add\n # its own terms).\n if hasattr(self, \"exploration\"):\n loss_out = self.exploration.get_exploration_loss(\n loss_out, train_batch)\n\n assert len(loss_out) == len(self._optimizers)\n\n # assert not any(torch.isnan(l) for l in loss_out)\n fetches = self.extra_compute_grad_fetches()\n\n # Loop through all optimizers.\n grad_info = {\"allreduce_latency\": 0.0}\n\n all_grads = []\n for i, opt in enumerate(self._optimizers):\n # Erase gradients in all vars of this optimizer.\n opt.zero_grad()\n # Recompute gradients of loss over all variables.\n loss_out[i].backward(retain_graph=(i < len(self._optimizers) - 1))\n grad_info.update(self.extra_grad_process(opt, loss_out[i]))\n\n grads = []\n # Note that return values are just references;\n # Calling zero_grad would modify the values.\n for param_group in opt.param_groups:\n for p in param_group[\"params\"]:\n if p.grad is not None:\n grads.append(p.grad)\n all_grads.append(p.grad.data.cpu().numpy())\n else:\n all_grads.append(None)\n\n if self.distributed_world_size:\n start = time.time()\n if torch.cuda.is_available():\n # Sadly, allreduce_coalesced does not work with CUDA yet.\n for g in grads:\n torch.distributed.all_reduce(\n g, op=torch.distributed.ReduceOp.SUM)\n else:\n torch.distributed.all_reduce_coalesced(\n grads, op=torch.distributed.ReduceOp.SUM)\n\n for param_group in opt.param_groups:\n for p in param_group[\"params\"]:\n if p.grad is not None:\n p.grad /= self.distributed_world_size\n\n grad_info[\"allreduce_latency\"] += time.time() - start\n\n grad_info[\"allreduce_latency\"] /= len(self._optimizers)\n grad_info.update(self.extra_grad_info(train_batch))\n\n return all_grads, dict(fetches, **{LEARNER_STATS_KEY: grad_info})\n\n @override(Policy)\n @DeveloperAPI\n def apply_gradients(self, gradients: ModelGradients) -> None:\n # TODO(sven): Not supported for multiple optimizers yet.\n assert len(self._optimizers) == 1\n for g, p in zip(gradients, self.model.parameters()):\n if g is not None:\n p.grad = torch.from_numpy(g).to(self.device)\n\n self._optimizers[0].step()\n\n @override(Policy)\n @DeveloperAPI\n def get_weights(self) -> ModelWeights:\n return {\n k: v.cpu().detach().numpy()\n for k, v in self.model.state_dict().items()\n }\n\n @override(Policy)\n @DeveloperAPI\n def set_weights(self, weights: ModelWeights) -> None:\n weights = convert_to_torch_tensor(weights, device=self.device)\n self.model.load_state_dict(weights)\n\n @override(Policy)\n @DeveloperAPI\n def is_recurrent(self) -> bool:\n return len(self.model.get_initial_state()) > 0\n\n @override(Policy)\n @DeveloperAPI\n def num_state_tensors(self) -> int:\n return len(self.model.get_initial_state())\n\n @override(Policy)\n @DeveloperAPI\n def get_initial_state(self) -> List[TensorType]:\n return [\n s.detach().cpu().numpy() for s in self.model.get_initial_state()\n ]\n\n @override(Policy)\n @DeveloperAPI\n def get_state(self) -> Union[Dict[str, TensorType], List[TensorType]]:\n state = super().get_state()\n state[\"_optimizer_variables\"] = []\n for i, o in enumerate(self._optimizers):\n optim_state_dict = convert_to_non_torch_type(o.state_dict())\n state[\"_optimizer_variables\"].append(optim_state_dict)\n return state\n\n @override(Policy)\n @DeveloperAPI\n def set_state(self, state: object) -> None:\n state = state.copy() # shallow copy\n # Set optimizer vars first.\n optimizer_vars = state.pop(\"_optimizer_variables\", None)\n if optimizer_vars:\n assert len(optimizer_vars) == len(self._optimizers)\n for o, s in zip(self._optimizers, optimizer_vars):\n optim_state_dict = convert_to_torch_tensor(\n s, device=self.device)\n o.load_state_dict(optim_state_dict)\n # Then the Policy's (NN) weights.\n super().set_state(state)\n\n @DeveloperAPI\n def extra_grad_process(self, optimizer: \"torch.optim.Optimizer\",\n loss: TensorType):\n \"\"\"Called after each optimizer.zero_grad() + loss.backward() call.\n\n Called for each self._optimizers/loss-value pair.\n Allows for gradient processing before optimizer.step() is called.\n E.g. for gradient clipping.\n\n Args:\n optimizer (torch.optim.Optimizer): A torch optimizer object.\n loss (TensorType): The loss tensor associated with the optimizer.\n\n Returns:\n Dict[str, TensorType]: An dict with information on the gradient\n processing step.\n \"\"\"\n return {}\n\n @DeveloperAPI\n def extra_compute_grad_fetches(self) -> Dict[str, any]:\n \"\"\"Extra values to fetch and return from compute_gradients().\n\n Returns:\n Dict[str, any]: Extra fetch dict to be added to the fetch dict\n of the compute_gradients call.\n \"\"\"\n return {LEARNER_STATS_KEY: {}} # e.g, stats, td error, etc.\n\n @DeveloperAPI\n def extra_action_out(\n self, input_dict: Dict[str, TensorType],\n state_batches: List[TensorType], model: TorchModelV2,\n action_dist: TorchDistributionWrapper) -> Dict[str, TensorType]:\n \"\"\"Returns dict of extra info to include in experience batch.\n\n Args:\n input_dict (Dict[str, TensorType]): Dict of model input tensors.\n state_batches (List[TensorType]): List of state tensors.\n model (TorchModelV2): Reference to the model object.\n action_dist (TorchDistributionWrapper): Torch action dist object\n to get log-probs (e.g. for already sampled actions).\n\n Returns:\n Dict[str, TensorType]: Extra outputs to return in a\n compute_actions() call (3rd return value).\n \"\"\"\n return {}\n\n @DeveloperAPI\n def extra_grad_info(self,\n train_batch: SampleBatch) -> Dict[str, TensorType]:\n \"\"\"Return dict of extra grad info.\n\n Args:\n train_batch (SampleBatch): The training batch for which to produce\n extra grad info for.\n\n Returns:\n Dict[str, TensorType]: The info dict carrying grad info per str\n key.\n \"\"\"\n return {}\n\n @DeveloperAPI\n def optimizer(\n self\n ) -> Union[List[\"torch.optim.Optimizer\"], \"torch.optim.Optimizer\"]:\n \"\"\"Custom the local PyTorch optimizer(s) to use.\n\n Returns:\n Union[List[torch.optim.Optimizer], torch.optim.Optimizer]:\n The local PyTorch optimizer(s) to use for this Policy.\n \"\"\"\n if hasattr(self, \"config\"):\n return torch.optim.Adam(\n self.model.parameters(), lr=self.config[\"lr\"])\n else:\n return torch.optim.Adam(self.model.parameters())\n\n @override(Policy)\n @DeveloperAPI\n def export_model(self, export_dir: str) -> None:\n \"\"\"TODO(sven): implement for torch.\n \"\"\"\n raise NotImplementedError\n\n @override(Policy)\n @DeveloperAPI\n def export_checkpoint(self, export_dir: str) -> None:\n \"\"\"TODO(sven): implement for torch.\n \"\"\"\n raise NotImplementedError\n\n @override(Policy)\n @DeveloperAPI\n def import_model_from_h5(self, import_file: str) -> None:\n \"\"\"Imports weights into torch model.\"\"\"\n return self.model.import_from_h5(import_file)\n\n def _lazy_tensor_dict(self, postprocessed_batch):\n train_batch = UsageTrackingDict(postprocessed_batch)\n train_batch.set_get_interceptor(\n functools.partial(convert_to_torch_tensor, device=self.device))\n return train_batch\n\n def _lazy_numpy_dict(self, postprocessed_batch):\n train_batch = UsageTrackingDict(postprocessed_batch)\n train_batch.set_get_interceptor(\n functools.partial(convert_to_non_torch_type))\n return train_batch\n\n\n# TODO: (sven) Unify hyperparam annealing procedures across RLlib (tf/torch)\n# and for all possible hyperparams, not just lr.\n@DeveloperAPI\nclass LearningRateSchedule:\n \"\"\"Mixin for TFPolicy that adds a learning rate schedule.\"\"\"\n\n @DeveloperAPI\n def __init__(self, lr, lr_schedule):\n self.cur_lr = lr\n if lr_schedule is None:\n self.lr_schedule = ConstantSchedule(lr, framework=None)\n else:\n self.lr_schedule = PiecewiseSchedule(\n lr_schedule, outside_value=lr_schedule[-1][-1], framework=None)\n\n @override(Policy)\n def on_global_var_update(self, global_vars):\n super().on_global_var_update(global_vars)\n self.cur_lr = self.lr_schedule.value(global_vars[\"timestep\"])\n for opt in self._optimizers:\n for p in opt.param_groups:\n p[\"lr\"] = self.cur_lr\n\n\n@DeveloperAPI\nclass EntropyCoeffSchedule:\n \"\"\"Mixin for TorchPolicy that adds entropy coeff decay.\"\"\"\n\n @DeveloperAPI\n def __init__(self, entropy_coeff, entropy_coeff_schedule):\n self.entropy_coeff = entropy_coeff\n\n if entropy_coeff_schedule is None:\n self.entropy_coeff_schedule = ConstantSchedule(\n entropy_coeff, framework=None)\n else:\n # Allows for custom schedule similar to lr_schedule format\n if isinstance(entropy_coeff_schedule, list):\n self.entropy_coeff_schedule = PiecewiseSchedule(\n entropy_coeff_schedule,\n outside_value=entropy_coeff_schedule[-1][-1],\n framework=None)\n else:\n # Implements previous version but enforces outside_value\n self.entropy_coeff_schedule = PiecewiseSchedule(\n [[0, entropy_coeff], [entropy_coeff_schedule, 0.0]],\n outside_value=0.0,\n framework=None)\n\n @override(Policy)\n def on_global_var_update(self, global_vars):\n super(EntropyCoeffSchedule, self).on_global_var_update(global_vars)\n self.entropy_coeff = self.entropy_coeff_schedule.value(\n global_vars[\"timestep\"])\n","repo_name":"ray-project/maze-raylit","sub_path":"rllib/policy/torch_policy.py","file_name":"torch_policy.py","file_ext":"py","file_size_in_byte":26914,"program_lang":"python","lang":"en","doc_type":"code","stars":5,"dataset":"github-code","pt":"17"} +{"seq_id":"2080871265","text":"import numpy as np \nfrom preprocess import preprocess\nfrom texton_color_utils import Textons\nimport cv2\nimport sys\n\nim = cv2.imread(sys.argv[1])\n#im = cv2.blur(im,(5,5))\n#im = cv2.medianBlur(im, 5)\n#ob = preprocess(im)\n#im, _ = ob.kmeans(3)\n\n#im = cv2.medianBlur(im,3)\n\ntex = Textons(im, int(sys.argv[2]), int(sys.argv[3]), 1)\nim = tex.textons()\ncenters = np.unique(im)\n\nfor _ in range(int(sys.argv[2])):\n show = np.zeros_like(im)\n show[im==centers[_]] = 255\n #show = cv2.morphologyEx(show, cv2.MORPH_OPEN, np.ones((5, 5)))\n cv2.imwrite('center: '+str(_) + '.png', cv2.bitwise_not(show))\n\nfor _ in range(int(sys.argv[2])):\n show = np.zeros_like(im)\n show[im==centers[_]] = 255\n show = cv2.morphologyEx(show, cv2.MORPH_OPEN, np.ones((5, 5)))\n cv2.imwrite('center processing: '+str(_) + '.png', cv2.bitwise_not(show))\n\n\ncv2.imshow(\"image\", im)\ncv2.waitKey(0)\ncv2.destroyAllWindows()\n\n\n","repo_name":"BATspock/Textons-colors","sub_path":"test.py","file_name":"test.py","file_ext":"py","file_size_in_byte":907,"program_lang":"python","lang":"en","doc_type":"code","stars":5,"dataset":"github-code","pt":"17"} +{"seq_id":"34687216684","text":"def solution(prices):\n stack = []\n time = [0] * len(prices)\n\n for i, j in enumerate(prices):\n if not stack or stack[-1][1] <= j:\n stack.append([i, j])\n else:\n while stack and stack[-1][1] > j:\n a, b = stack.pop()\n time[a] = i - a\n stack.append([i, j])\n\n while stack:\n a, b = stack.pop()\n time[a] = len(prices) - 1 - a\n\n return time\n","repo_name":"doputer/algorithm","sub_path":"프로그래머스/level2/주식가격.py","file_name":"주식가격.py","file_ext":"py","file_size_in_byte":378,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"17"} +{"seq_id":"43297793626","text":"from dataclasses import dataclass\nfrom zappyAI.enums import *\n\n\n@dataclass\nclass Resources:\n food: int\n linemate: int\n deraumere: int\n sibur: int\n mendiane: int\n phiras: int\n thystame: int\n player: int\n\n def __getitem__(self, item: ObjectType | str) -> int:\n if type(item) == str:\n if item == \"food\":\n return self.food\n elif item == \"linemate\":\n return self.linemate\n elif item == \"deraumere\":\n return self.deraumere\n elif item == \"sibur\":\n return self.sibur\n elif item == \"mendiane\":\n return self.mendiane\n elif item == \"phiras\":\n return self.phiras\n elif item == \"thystame\":\n return self.thystame\n elif item == \"player\":\n return self.player\n else:\n raise ValueError(\"Invalid name\")\n elif type(item) == ObjectType:\n if item == ObjectType.FOOD:\n return self.food\n elif item == ObjectType.LINEMATE:\n return self.linemate\n elif item == ObjectType.DERAUMERE:\n return self.deraumere\n elif item == ObjectType.SIBUR:\n return self.sibur\n elif item == ObjectType.MENDIANE:\n return self.mendiane\n elif item == ObjectType.PHIRAS:\n return self.phiras\n elif item == ObjectType.THYSTAME:\n return self.thystame\n elif item == ObjectType.PLAYER:\n return self.player\n else:\n raise ValueError(\"Invalid ObjectType\")\n else:\n raise ValueError(\"Invalid object type\")\n\n def __setitem__(self, item: ObjectType | str, value: int) -> None:\n if type(item) == str:\n if item == \"food\":\n self.food = value\n elif item == \"linemate\":\n self.linemate = value\n elif item == \"deraumere\":\n self.deraumere = value\n elif item == \"sibur\":\n self.sibur = value\n elif item == \"mendiane\":\n self.mendiane = value\n elif item == \"phiras\":\n self.phiras = value\n elif item == \"thystame\":\n self.thystame = value\n elif item == \"player\":\n self.player = value\n else:\n raise ValueError(\"Invalid name\")\n elif type(item) == ObjectType:\n if item == ObjectType.FOOD:\n self.food = value\n elif item == ObjectType.LINEMATE:\n self.linemate = value\n elif item == ObjectType.DERAUMERE:\n self.deraumere = value\n elif item == ObjectType.SIBUR:\n self.sibur = value\n elif item == ObjectType.MENDIANE:\n self.mendiane = value\n elif item == ObjectType.PHIRAS:\n self.phiras = value\n elif item == ObjectType.THYSTAME:\n self.thystame = value\n elif item == ObjectType.PLAYER:\n self.player = value\n else:\n raise ValueError(\"Invalid ObjectType\")\n else:\n raise ValueError(\"Invalid object type\")\n\n def __contains__(self, item: ObjectType | str) -> bool:\n try:\n self[item] = self[item]\n except ValueError:\n return False\n return True\n\n def __len__(self) -> int:\n res: int = 0\n for key in self:\n res += self[key]\n return res\n\n def __str__(self) -> str:\n return f\"Resources(food={self.food}, linemate={self.linemate}, deraumere={self.deraumere}, sibur={self.sibur}, mendiane={self.mendiane}, phiras={self.phiras}, thystame={self.thystame}, player={self.player})\"\n\n def __repr__(self) -> str:\n return str(self)\n\n def __dict__(self) -> dict:\n return {\n \"food\": self.food,\n \"linemate\": self.linemate,\n \"deraumere\": self.deraumere,\n \"sibur\": self.sibur,\n \"mendiane\": self.mendiane,\n \"phiras\": self.phiras,\n \"thystame\": self.thystame,\n \"player\": self.player\n }\n\n def __iter__(self) -> iter:\n yield ObjectType.FOOD\n yield ObjectType.LINEMATE\n yield ObjectType.DERAUMERE\n yield ObjectType.SIBUR\n yield ObjectType.MENDIANE\n yield ObjectType.PHIRAS\n yield ObjectType.THYSTAME\n yield ObjectType.PLAYER\n\n def __add__(self, other: 'Resources') -> 'Resources':\n return Resources(\n self.food + other.food,\n self.linemate + other.linemate,\n self.deraumere + other.deraumere,\n self.sibur + other.sibur,\n self.mendiane + other.mendiane,\n self.phiras + other.phiras,\n self.thystame + other.thystame,\n self.player + other.player\n )\n\n def __sub__(self, other: 'Resources') -> 'Resources':\n return Resources(\n self.food - other.food,\n self.linemate - other.linemate,\n self.deraumere - other.deraumere,\n self.sibur - other.sibur,\n self.mendiane - other.mendiane,\n self.phiras - other.phiras,\n self.thystame - other.thystame,\n self.player - other.player\n )\n\n def __eq__(self, other: 'Resources') -> bool:\n return (self.food == other.food and\n self.linemate == other.linemate and\n self.deraumere == other.deraumere and\n self.sibur == other.sibur and\n self.mendiane == other.mendiane and\n self.phiras == other.phiras and\n self.thystame == other.thystame and\n self.player == other.player)\n\n def __ne__(self, other: 'Resources') -> bool:\n return not self.__eq__(other)\n\n def is_empty(self) -> bool:\n for i in self:\n if self[i] != 0:\n return False\n return True\n\n\ndef is_object(name: str) -> bool:\n if name in ObjectType.__iter__():\n return True\n return False\n","repo_name":"Ackfire/Zappy","sub_path":"AI/zappyAI/objects.py","file_name":"objects.py","file_ext":"py","file_size_in_byte":6234,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"17"} +{"seq_id":"70247734745","text":"import re\n\nfrom mihto.lexer.exceptions import UnknownTokenException\nfrom mihto.lexer.token_types import TOKEN_PATTERNS\n\n\nclass Lexer:\n\n def __init__(self, code):\n self.code = code\n\n def tokenize(self):\n tokens = []\n while self.code:\n tokens.append(self.single_tokenize())\n self.code = self.code.strip()\n return tokens\n\n def single_tokenize(self):\n for token_type, regex in TOKEN_PATTERNS:\n regex = re.compile(r\"\\A{}\".format(regex))\n value = regex.search(self.code)\n if value:\n value = value.group(0)\n self.code = self.code[len(value):]\n return Token(token_type, value)\n\n raise UnknownTokenException(\"Couldn't match token on {}\".format(self.code))\n\n\nclass Token:\n __slots__ = ('type', 'value')\n\n def __init__(self, type: str, value):\n self.type = type\n self.value = value\n\n def __repr__(self):\n return \"\".format(self.type, self.value)\n","repo_name":"OrbitalAds/Mihto","sub_path":"mihto/lexer/lexer.py","file_name":"lexer.py","file_ext":"py","file_size_in_byte":1041,"program_lang":"python","lang":"en","doc_type":"code","stars":2,"dataset":"github-code","pt":"17"} +{"seq_id":"17542558095","text":"#!/usr/bin/env python\n# -*- coding: utf-8 -*-\n\"\"\"\nsmc : python library for plotting and manipulating smc grids\n\"\"\"\n\nimport os\nfrom setuptools import setup, find_packages\n\nimport smc\nimport SMCPy\n\ninstall_requires = [\n 'netCDF4',\n 'matplotlib',\n 'cartopy',\n ]\n\ndef read(fname):\n return open(os.path.join(os.path.dirname(__file__), fname)).read()\n\nif __name__ == '__main__':\n setup(name = 'pymsl',\n version = smc.__version__,\n description = 'smc',\n author = \"Chris Bunney, Tom Durrant\",\n author_email = \"chris.bunney@metoffice.co\",\n maintainer = \"Tom Durrant\",\n maintainer_email = \"t.durrant@metocean.co.nz\",\n url = 'https://github.com/metocean/pymsl',\n install_requires=install_requires,\n long_description=read('README.md'),\n packages=['smc'],\n )\n setup(name = 'SMCPy',\n version = SMCPy.__version__,\n description = 'SMCPy',\n author = \"Chris Bunney, Tom Durrant\",\n author_email = \"chris.bunney@metoffice.co\",\n maintainer = \"Tom Durrant\",\n maintainer_email = \"t.durrant@metocean.co.nz\",\n url = 'https://github.com/metocean/pymsl',\n install_requires=install_requires,\n long_description=read('README.md'),\n packages=['SMCPy'],\n )\n","repo_name":"metocean/pysmc","sub_path":"setup_smc.py","file_name":"setup_smc.py","file_ext":"py","file_size_in_byte":1347,"program_lang":"python","lang":"en","doc_type":"code","stars":4,"dataset":"github-code","pt":"17"} +{"seq_id":"30197999340","text":"import logging\n\nimport tensorflow as tf\n\nimport numpy as np\nfrom PIL import Image\nimport os\nimport sys\nimport math\nimport random\nimport cv2\nimport time\nfrom network import Network\nimport tensorflow_yolov3.carla.utils as utils\n\n# ==============================================================================\n# -- add PythonAPI for release mode --------------------------------------------\n# ==============================================================================\ntry:\n sys.path.append(os.path.dirname(os.path.dirname(os.path.abspath(__file__))) + '/carla')\nexcept IndexError:\n import traceback\n traceback.print_exc()\n\nimport carla\nfrom carla import ColorConverter as cc\n\nfrom agents.navigation.agent import Agent, AgentState\nfrom agents.navigation.local_planner import LocalPlanner\nfrom agents.navigation.global_route_planner import GlobalRoutePlanner\nfrom agents.navigation.global_route_planner_dao import GlobalRoutePlannerDAO\nfrom agents.navigation.local_planner import RoadOption\nfrom agents.tools.misc import is_within_distance_ahead, is_within_distance, compute_distance\n\n\nclass CarlaAgent(Agent):\n \"\"\"\n BasicAgent implements a basic agent that navigates scenes to reach a given\n target destination. This agent respects traffic lights and other vehicles.\n \"\"\"\n\n def __init__(self, vehicle, target_speed=20, image_cut=[115, 510]):\n \"\"\"\n\n :param vehicle: actor to apply to local planner logic onto\n \"\"\"\n super(CarlaAgent, self).__init__(vehicle)\n\n self._proximity_threshold = 10.0 # meters\n self._state = AgentState.NAVIGATING\n args_lateral_dict = {\n 'K_P': 1,\n 'K_D': 0.02,\n 'K_I': 0,\n 'dt': 1.0 / 20.0}\n self._local_planner = LocalPlanner(\n self._vehicle, opt_dict={'target_speed': target_speed,\n 'lateral_control_dict': args_lateral_dict})\n self._hop_resolution = 0.5\n self._path_seperation_hop = 3\n self._path_seperation_threshold = 1.0\n self._target_speed = target_speed\n self._grp = None\n\n self.route_trace = None\n\n # data from vehicle\n self.speed = 0\n self._radar_data = None\n self._obstacle_ahead = False\n\n # load network\n g1 = tf.Graph()\n\n with g1.as_default():\n self.drive_network = Network(model_name='Network', model_dir='/model_carla_agent/')\n\n self._image_cut = image_cut\n self._image_size = (88, 200, 3) # 아마 [세로, 가로, 차원(RGB)] 인듯?\n\n self.front_image = None\n\n self.bounding_boxes = None\n\n def set_destination(self, start_loc, end_loc, set_transform=True):\n \"\"\"\n This method creates a list of waypoints from agent's position to destination location\n based on the route returned by the global router\n \"\"\"\n\n start_waypoint = self._map.get_waypoint(start_loc.location)\n end_waypoint = self._map.get_waypoint(end_loc.location)\n\n control_reset = carla.VehicleControl()\n control_reset.steer, control_reset.throttle, control_reset.brake = 0.0, 0.0, 0.0\n\n start_loc.location.z += 0.5\n\n if set_transform:\n self._vehicle.apply_control(control_reset)\n self._vehicle.set_transform(start_loc)\n\n self.route_trace = self._trace_route(start_waypoint, end_waypoint)\n assert self.route_trace\n\n self._local_planner.set_global_plan(self.route_trace)\n\n self._local_planner.change_intersection_hcl(enter_hcl_len=15, exit_hcl_len=21)\n\n def _trace_route(self, start_waypoint, end_waypoint):\n \"\"\"\n This method sets up a global router and returns the optimal route\n from start_waypoint to end_waypoint\n \"\"\"\n\n # Setting up global router\n if self._grp is None:\n dao = GlobalRoutePlannerDAO(self._vehicle.get_world().get_map(), self._hop_resolution)\n grp = GlobalRoutePlanner(dao)\n grp.setup()\n self._grp = grp\n\n # Obtain route plan\n route = self._grp.trace_route(\n start_waypoint.transform.location,\n end_waypoint.transform.location)\n\n return route\n\n def run_step(self):\n \"\"\"\n Execute one step of navigation.\n :return: carla.VehicleControl\n \"\"\"\n\n self._state = AgentState.NAVIGATING\n # standard local planner behavior\n self._local_planner.buffer_waypoints()\n\n direction = self.get_high_level_command(convert=False)\n v = self._vehicle.get_velocity()\n speed = math.sqrt(v.x ** 2 + v.y ** 2 + v.z ** 2) # use m/s\n self.speed = speed * 3.6 # use km/s\n\n control = self._compute_action(self.front_image, speed, direction)\n return control\n\n def _compute_action(self, rgb_image, speed, direction=None):\n \"\"\"\n Calculate steer, gas, brake from image input\n :return: carla.VehicleControl\n \"\"\"\n '''\n # TODO scipy 제대로 되는지 확인\n # scipy 에서 imresize 가 depreciated 됐으므로 다른 방법으로 이미지 리사이즈\n # 이미지를 비율에 어느 정도 맞게 크롭 (395 * 800)\n rgb_image = rgb_image[self._image_cut[0]:self._image_cut[1], :]\n\n # 크롭한 이미지를 리사이징. 비율에 맞게 조절하는게 아니라 조금 찌그러지게 리사이징함. 원래 비율은 352 * 800\n image_input = scipy.misc.imresize(rgb_image, [self._image_size[0],\n self._image_size[1]])\n '''\n\n rgb_image.convert(cc.Raw)\n\n array = np.frombuffer(rgb_image.raw_data, dtype=np.dtype(\"uint8\"))\n array = np.reshape(array, (rgb_image.height, rgb_image.width, 4))\n array = array[self._image_cut[0]:self._image_cut[1], :, :3] # 필요 없는 부분을 잘라내고\n array = array[:, :, ::-1] # 채널 색상 순서 변경? 안 하면 색 이상하게 출력\n\n image_pil = Image.fromarray(array.astype('uint8'), 'RGB')\n image_pil = image_pil.resize((self._image_size[1], self._image_size[0])) # 원하는 크기로 리사이즈\n image_input = np.array(image_pil, dtype=np.dtype(\"uint8\"))\n\n image_input = image_input.astype(np.float32)\n image_input = np.multiply(image_input, 1.0 / 255.0)\n\n steer, acc, brake = self._compute_function(image_input, speed, direction, self.drive_network)\n\n if brake < 0.1:\n brake = 0.0\n\n if acc > brake:\n brake = 0.0\n\n # We limit speed to 35 km/h to avoid\n if speed > 10.0 and brake == 0.0:\n acc = 0.0\n\n control = carla.VehicleControl()\n control.steer = float(steer)\n control.throttle = float(acc)\n control.brake = float(brake)\n\n control.hand_brake = 0\n control.reverse = 0\n\n return control\n\n def _compute_function(self, image_input, speed, control_input, network):\n\n branches = network.network_tensor\n x = network.input_images\n dout = network.dout\n input_speed = network.input_data[1]\n\n image_input = image_input.reshape(\n (1, network.image_size[0], network.image_size[1], network.image_size[2]))\n\n # Normalize with the maximum speed from the training set ( 90 km/h)\n speed = np.array(speed / 25.0)\n\n speed = speed.reshape((1, 1))\n\n if control_input == RoadOption.LEFT:\n all_net = branches[2]\n elif control_input == RoadOption.RIGHT:\n all_net = branches[3]\n elif control_input == RoadOption.STRAIGHT:\n all_net = branches[1]\n elif control_input == RoadOption.LANEFOLLOW:\n all_net = branches[0]\n else:\n all_net = branches[0]\n\n feedDict = {x: image_input, input_speed: speed, dout: [1] * len(network.dropout_vec)}\n\n output_all = network.sess.run(all_net, feed_dict=feedDict)\n\n predicted_steers = (output_all[0][0])\n\n predicted_acc = (output_all[0][1])\n\n predicted_brake = (output_all[0][2])\n\n predicted_speed = network.sess.run(branches[4], feed_dict=feedDict)\n predicted_speed = predicted_speed[0][0]\n real_speed = speed * 25.0\n\n real_predicted = predicted_speed * 25.0\n if real_speed < 2.0 and real_predicted > 3.0:\n # If (Car Stooped) and\n # ( It should not have stopped, use the speed prediction branch for that)\n\n predicted_acc = 1 * (5.6 / 25.0 - speed) + predicted_acc\n\n predicted_brake = 0.0\n\n predicted_acc = predicted_acc[0][0]\n\n return predicted_steers, predicted_acc, predicted_brake\n\n def set_radar_data(self, radar_data):\n self._radar_data = radar_data\n","repo_name":"phoi5675/benchmark-for-carla-imitation-learning","sub_path":"benchmark_runner/carla_agent.py","file_name":"carla_agent.py","file_ext":"py","file_size_in_byte":8798,"program_lang":"python","lang":"en","doc_type":"code","stars":3,"dataset":"github-code","pt":"17"} +{"seq_id":"15586185564","text":"import os,sys\nfrom hicplus import model\n\n\n## Torch Related Dependencies\n# from torch.utils import data\n# import torch\n# import torch.nn as nn\n# import torch.optim as optim\n# from torch.autograd import Variable\n\nimport tensorflow as tf\n\n\n\n## Non-Torch Related Dependencies \nimport straw\nfrom scipy.sparse import csr_matrix, coo_matrix, vstack, hstack\nfrom scipy import sparse\nimport numpy as np\nfrom hicplus import utils\nfrom time import gmtime, strftime\nfrom datetime import datetime\nimport argparse\n\n\n\n\n\nstartTime = datetime.now()\n\nuse_gpu = 0 #opt.cuda\nprint(\"Num GPUs Available: \", len(tf.config.list_physical_devices('GPU')))\n\n#if use_gpu and not torch.cuda.is_available():\n# raise Exception(\"No GPU found, please run without --cuda\")\n\ndef predict(M,N,inmodel):\n\n prediction_1 = np.zeros((N, N))\n\n for low_resolution_samples, index in utils.divide(M):\n\n #print(index.shape)\n\n batch_size = low_resolution_samples.shape[0] #256\n\n # IPD: data.TensorDataset(input, targets) also think of inputs as (x_train, y_train)\n # lowres_set = data.TensorDataset(torch.from_numpy(low_resolution_samples), torch.from_numpy(np.zeros(low_resolution_samples.shape[0])))\n inputs = tf.convert_to_tensor(low_resolution_samples)\n targets = tf.convert_to_tensor(np.zeros(low_resolution_samples.shape[0]))\n lowres_set = tf.data.DataSet.from_tensor_slices((inputs, targets))\n\n try:\n # DataLoader(dataset, batchsize, shuffle)\n #lowres_loader = torch.utils.data.DataLoader(lowres_set, batch_size=batch_size, shuffle=False)\n lowres_loader = lowres_set.batch(batch_size)\n lowres_loader = lowres_loader.make_one_shot_iterator()\n except:\n continue\n\n hires_loader = lowres_loader\n\n m = model.Net(40, 28)\n # m.load_state_dict(torch.load(inmodel, map_location=torch.device('cpu')))\n with tf.device('/cpu:0'):\n # model = tf.keras.models.load_model(inmodel)\n m.load_weights(inmodel)\n\n\n\n # if torch.cuda.is_available():\n # m = m.cuda()\n\n # # IPD: Will have to ask about how to run a keras model on a gpu. However,\n # # I think we might not need to have this step if we have a gpu avalible\n # # since there is a setup to run the model on gpu...I think...\n # is_cuda_gpu_available = tf.test.is_gpu_available(cuda_only=True)\n # if is_cuda_gpu_available:\n # m = m.cuda()\n\n for i, v1 in enumerate(lowres_loader):\n _lowRes, _ = v1\n # _lowRes = Variable(_lowRes).float()\n _lowRes = tf.Variable(_lowRes)\n if use_gpu:\n _lowRes = _lowRes.cuda()\n y_prediction = m(_lowRes)\n\n\n y_predict = y_prediction.data.cpu().numpy()\n\n\n # recombine samples\n length = int(y_predict.shape[2])\n y_predict = np.reshape(y_predict, (y_predict.shape[0], length, length))\n\n\n for i in range(0, y_predict.shape[0]):\n\n x = int(index[i][1])\n y = int(index[i][2])\n #print np.count_nonzero(y_predict[i])\n prediction_1[x+6:x+34, y+6:y+34] = y_predict[i]\n\n return(prediction_1)\n\ndef chr_pred(hicfile, chrN1, chrN2, binsize, inmodel):\n\n # M is just a dense CRS matrix\n M = utils.matrix_extract(chrN1, chrN2, binsize, hicfile) \n #print(M.shape)\n N = M.shape[0]\n\n chr_Mat = predict(M, N, inmodel)\n\n\n# if Ncol > Nrow:\n# chr_Mat = chr_Mat[:Ncol, :Nrow]\n# chr_Mat = chr_Mat.T\n# if Nrow > Ncol: \n# chr_Mat = chr_Mat[:Nrow, :Ncol]\n# print(dat.head()) \n return(chr_Mat)\n\n\n\ndef writeBed(Mat, outname,binsize, chrN1,chrN2):\n with open(outname,'w') as chrom:\n r, c = Mat.nonzero()\n for i in range(r.size):\n contact = int(round(Mat[r[i],c[i]]))\n if contact == 0:\n continue\n #if r[i]*binsize > Len1 or (r[i]+1)*binsize > Len1:\n # continue\n #if c[i]*binsize > Len2 or (c[i]+1)*binsize > Len2:\n # continue\n line = [chrN1, r[i]*binsize, (r[i]+1)*binsize,\n chrN2, c[i]*binsize, (c[i]+1)*binsize, contact]\n chrom.write('chr'+str(line[0])+':'+str(line[1])+'-'+str(line[2])+\n '\\t'+'chr'+str(line[3])+':'+str(line[4])+'-'+str(line[5])+'\\t'+str(line[6])+'\\n')\n\n\n\n\ndef main(args):\n\n '''\n #### Arguments passed into parser (Delete later just for current understanding of variables)\n \n hicplus pred_chromosome\n usage: hicplus pred_chromosome [-h] [-i INPUTFILE] [-m MODEL] [-b BINSIZE] -c\n chrN1 chrN2\n\n optional arguments:\n -h, --help show this help message and exit\n -i INPUTFILE, --inputfile INPUTFILE\n path to a .hic file.\n -o OUTPUTFILE, --outputfile OUTPUTFILE\n path to an output file.\n -m MODEL, --model MODEL\n path to a model file.\n -b BINSIZE, --binsize BINSIZE\n predicted resolustion, e.g.10kb, 25kb...,\n default=10000\n -c chrN1 chrN2, --chrN chrN1 chrN2\n chromosome number\n '''\n\n chrN1, chrN2 = args.chrN \n binsize = args.binsize\n inmodel = args.model\n hicfile = args.inputfile\n #name = os.path.basename(inmodel).split('.')[0]\n #outname = 'chr'+str(chrN1)+'_'+name+'_'+str(binsize//1000)+'pred.txt'\n outname = args.outputfile\n Mat = chr_pred(hicfile,chrN1,chrN2,binsize,inmodel) # Predicted HiC Map\n print(Mat.shape)\n writeBed(Mat, outname, binsize,chrN1, chrN2)\n #print(enhM.shape)\n\nif __name__ == '__main__':\n main()\n\nprint(datetime.now() - startTime)\n","repo_name":"ivan-pd/Brown-Deep-Learning-HiCPlus","sub_path":"hicplus/pred_chromosome.py","file_name":"pred_chromosome.py","file_ext":"py","file_size_in_byte":5790,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"17"} +{"seq_id":"1903955172","text":"import requests_with_caching\nimport json\n\ndef get_movies_from_tastedive(s):\n baseurl = 'https://tastedive.com/api/similar'\n parameters = {'q': s,'type': 'movies', 'limit': 5}\n res = requests_with_caching.get(baseurl, params = parameters)\n return res.json()\n\ndef extract_movie_titles(dic):\n return [movie['Name'] for movie in dic['Similar']['Results']]\n\ndef get_related_titles(lst):\n movies = []\n for movie in lst:\n titles = extract_movie_titles(get_movies_from_tastedive(movie))\n for movie in titles:\n if movie not in movies:\n movies.append(movie)\n return movies\n\n\ndef get_movie_data(name):\n url = 'http://www.omdbapi.com/'\n params = {'t': name, 'r':'json'}\n res = requests_with_caching.get(url, params)\n return res.json() \n\ndef get_movie_rating(ratings):\n for rating in ratings['Ratings']:\n if rating['Source'] == 'Rotten Tomatoes':\n return int(rating['Value'][:2])\n return 0\n\ndef get_sorted_recommendations(movie):\n movies = get_related_titles(movie)\n return sorted(sorted(movies), key = lambda x: get_movie_rating(get_movie_data(x)), reverse = True)\n","repo_name":"bipubipu/learn_Python","sub_path":"movie_recom.py","file_name":"movie_recom.py","file_ext":"py","file_size_in_byte":1160,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"17"} +{"seq_id":"26921197272","text":"from pathlib import Path\nimport shutil\nimport random\nimport os\nimport csv\nimport superres.helpers as helpers\nfrom fastprogress import progress_bar\n\ndata_path = Path('/scratch/bpho')\nsources = data_path/'datasources'\nsrc = sources/'Airyscan_processed_data_from_the_server'\nsrc_hr = list(src.glob('*.czi'))\n\ndatasets = data_path/'datasets'\nsubset = datasets/'crappified_001'/'Airyscan_processed_data_from_the_server'\nsubset_lr = subset/'lr'\nsubset_lr_up = subset/'lr_up'\nsubset_hr = subset/'hr'\nvalid_pct = 0.2\ntest_pct = 0.1\n\nnum_tiles = 5\nscale = 4\nthreshold = 100\n\nif subset.exists(): shutil.rmtree(subset)\n\nvalid_split_idx = int(valid_pct * len(src_hr))\ntest_split_idx = int(test_pct * len(src_hr))\nnon_train_idx = valid_split_idx + test_split_idx\n\nvalid_ids = src_hr[0:valid_split_idx] #Is this seed fixed?\ntest_ids = src_hr[valid_split_idx: non_train_idx]\ntrain_ids = src_hr[non_train_idx:]\n\nfor fn in progress_bar(src_hr):\n if fn in valid_ids: \n subdir = 'valid'\n elif fn in train_ids:\n subdir = 'train'\n elif fn in test_ids:\n continue\n else:\n print('Stepped into no mankind island.')\n sys.exit(1)\n \n hr_dir = subset/'hr'/subdir\n lr_dir = subset/'lr'/subdir\n lr_up_dir = subset/'lr_up'/subdir \n base_name = fn.stem\n for fld in [hr_dir, lr_dir, lr_up_dir]: fld.mkdir(parents=True, exist_ok=True, mode=0o775)\n \n helpers.algo_crappify_movie_to_tifs(\n fn, hr_dir, lr_dir, lr_up_dir, base_name, max_scale=1.05, max_per_movie=False)\n\nfor subdir in ['valid','train']:\n untiled_files = [] #save image frames which doesn't satisfy the cropping criteria\n hr_dir = subset/'hr'/subdir\n lr_dir = subset/'lr'/subdir\n lr_up_dir = subset/'lr_up'/subdir \n print('The number of files in '+subdir+' set is '+str(len(list(hr_dir.iterdir()))))\n \n for tile_size in [128,256,512]: \n hr_ROI = subset/f'roi_hr_{tile_size}'/subdir\n lr_ROI = subset/f'roi_lr_{tile_size}'/subdir\n lr_up_ROI = subset/f'roi_lr_up_{tile_size}'/subdir\n #print('\\n', hr_ROI, '\\n', lr_ROI, '\\n', lr_up_ROI)\n print('Creating ROIs with tile size ' + str(tile_size))\n for hr_fn in progress_bar(list(hr_dir.iterdir())):\n #print('Processing ' + hr_fn.name + ', tile_size is ' + str(tile_size) + '.')\n lr_fn = lr_dir/hr_fn.name\n helpers.tif_to_tiles(lr_fn, hr_fn, hr_fn.stem, hr_ROI, lr_up_ROI, lr_ROI, size=tile_size,\n num_tiles=num_tiles, scale=scale, threshold=threshold, untiled_ls=untiled_files) \n\n with open(subset/(subdir+'_untiled_filelist.txt'), 'w') as f:\n for item in untiled_files:\n f.write(\"%s\\n\" % item)\n\ntest_dir = subset/'test'\ntest_dir.mkdir(parents=True, exist_ok=True, mode=0o775)\nfor fn in progress_bar(test_ids):\n shutil.copy(fn, test_dir/fn.stem)\n\nprint('\\n\\nAll done!')\n\n","repo_name":"WAMRI-AI/salk","sub_path":"uri/scripts/datasets/crappified_001_subset_002.py","file_name":"crappified_001_subset_002.py","file_ext":"py","file_size_in_byte":2897,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"17"} +{"seq_id":"37537857928","text":"import torch\nimport torch.nn as nn\nimport torch.nn.functional as F\nimport torch.optim as optim\nimport pickle\n\n#@ setting\ntask_name = 'cycle_navigation' #'modular_arithmetic', 'parity_check', 'even_pairs', 'cycle_navigation'\ntrain_step = 10_000\nepochs = 10\nbatch_size = 128\nbinarize_setting = 0\nin_dim = 3\nrand_dim = 3## Random dim fix to 3\nout_dim = 3\n\n'''\nbinarize_setting: determine wheter use 1/0 or 1/-1\n0: use 0/1\n1: use 1/-1\n'''\nclass Net(nn.Module):\n def __init__(self, in_dim, rand_dim, out_dim, binarize_setting):\n super().__init__()\n self.binarize_setting = binarize_setting\n\n self.enc1 = nn.Linear(in_dim+rand_dim, 128)\n self.enc2 = nn.Linear(128, 128)\n self.enc3 = nn.Linear(128, out_dim)\n self.dec1 = nn.Linear(out_dim, 128)\n self.dec2 = nn.Linear(128, 128)\n self.dec3 = nn.Linear(128, in_dim)\n\n self.activation = nn.ReLU()\n\n '''\n for m in self.modules():\n print('g',m)\n if isinstance(m, nn.Linear):\n torch.nn.init.normal_(m.weight.data, mean=0, std = 0.1)\n '''\n\n\n def binarize(self, x):\n x_detach = x.clone().detach()\n if self.binarize_setting==0:\n x = torch.where(x>0.5, x+(1-x_detach), x - x_detach)\n elif self.binarize_setting==1:\n x = torch.where(x > 0.0, x + (1 - x_detach), x - (x_detach+1))\n return x\n\n def sig_tanh(self, x):\n if self.binarize_setting==0:\n x = F.sigmoid(x)\n elif self.binarize_setting==1:\n x = F.tanh(x)\n return x\n\n def forward(self, x):\n x_out = self.activation(self.enc1(x))\n x_out = self.activation(self.enc2(x_out))\n x_out = self.enc3(x_out)\n x_out = self.binarize(x_out)\n x_recon = self.activation(self.dec1(x_out))\n x_recon = self.activation(self.dec2(x_recon))\n x_recon = self.dec3(x_recon)\n x_recon_b = self.binarize(x_recon)\n x_recon_s = self.sig_tanh(x_recon)\n return x_out, x_recon_b, x_recon_s\n\n def eval_(self):\n data_tmp = torch.zeros((3, 6))\n data_tmp[:,:in_dim] = torch.eye(in_dim)\n x_out = self.activation(self.enc1(data_tmp))\n x_out = self.activation(self.enc2(x_out))\n x_out = self.enc3(x_out)\n x_out = self.binarize(x_out)\n\n tmp = torch.zeros((8, 3))\n for num in range(8):\n tmp_num = num\n for idx in range(3):\n tmp[num,idx] = tmp_num%2\n tmp_num = tmp_num //2\n if binarize_setting ==1:\n tmp = tmp*2-1\n x_recon = self.activation(self.dec1(tmp))\n x_recon = self.activation(self.dec2(x_recon))\n x_recon = self.dec3(x_recon)\n x_recon = self.binarize(x_recon)\n return x_out, x_recon\n\n\n\n\ndef run(task_name, train_step, binarize_setting, in_dim, rand_dim,out_dim, batch_size, epochs):\n running_loss = [.0, .0, .0, .0, .0, .0]\n #loader = task_loader(task_name, train_step, batch_size)\n with open(file='data.pickle', mode='rb') as f:\n data = pickle.load(f)\n model = Net(in_dim, rand_dim, out_dim, binarize_setting)\n #optimizer = optim.SGD(model.parameters(), lr=0.001, momentum=0.5)\n loss_recons = nn.BCELoss()\n optimizer = optim.Adam(model.parameters(), lr=0.0005, )\n if binarize_setting==0:\n mean_out = 0.5\n elif binarize_setting==1:\n mean_out = 0.0\n\n parm1 = 0.0\n for epoch in range(epochs):\n for step in range(train_step): # loop over the dataset multiple times\n input_, length = data[step]\n #print('1',input_.shape) #(128, 7, 3)\n input_ = torch.from_numpy(input_)\n rand_pad = torch.randint(2,(128,length,rand_dim))\n input_noise = torch.cat((input_,rand_pad), dim=2)\n if binarize_setting == 1:\n input_ = input_*2-1\n input_noise = input_noise*2-1\n #print('2',input_noise.shape) #torch.Size([128, 7, 6])\n # zero the parameter gradients\n optimizer.zero_grad()\n\n # forward + backward + optimize\n x_out, x_recon_b, x_recon_s = model(input_noise)\n #print('3',x_out.shape) #torch.Size([128, 7, 3])\n #print('4',x_recon.shape) #torch.Size([128, 7, 3])\n x_out_flatten = torch.flatten(x_out, end_dim =1)\n #print('5',x_out_flatten.shape) #torch.Size([896, 3])\n\n loss_recon_b = torch.mean(torch.abs(x_recon_b-input_))\n #loss_recon_s = loss_recons(x_recon_s,input_)\n loss_recon = loss_recon_b\n\n if loss_recon ==0.0 :\n parm1 = 1\n\n loss_set_mean = torch.mean(torch.abs(torch.mean(x_out, (0,1))-mean_out))\n loss_cov_nondiag = torch.mean(torch.abs(torch.cov(x_out_flatten)-torch.diagonal(torch.cov(x_out_flatten))))\n loss_cov_diag = torch.mean(torch.abs(torch.diagonal(torch.cov(x_out_flatten))-((1-mean_out)**2)))\n loss = 50*loss_recon\\\n +parm1*loss_set_mean\\\n +parm1*loss_cov_nondiag\\\n +parm1*loss_cov_diag\n loss.backward()\n optimizer.step()\n\n # print statistics\n running_loss[0] += loss.item()\n running_loss[1] += loss_recon.item()\n running_loss[2] += loss_set_mean.item()\n running_loss[3] += loss_cov_nondiag.item()\n running_loss[4] += loss_cov_diag.item()\n term = 20\n if step % term == term-1: # print every 2000 mini-batches\n print(f'[{epoch} epoch {step + 1}] loss: {running_loss[0] / term:.3f}'\n f' loss_recon: {running_loss[1] / term:.3f}'\n f' loss_set_mean: {running_loss[2] / term:.3f}'\n f' loss_cov_nondiag: {running_loss[3] / term:.3f}'\n f' loss_cov_diag: {running_loss[4] / term:.3f}')\n if running_loss[1] == 0.0:\n print(model.eval_())\n running_loss = [.0, .0, .0, .0, .0, .0]\n\nrun(task_name, train_step, binarize_setting, in_dim, rand_dim,out_dim, batch_size, epochs)\n'''\nenc1.weight torch.Size([3, 6])\nenc1.bias torch.Size([3])\ndec1.weight torch.Size([3, 3])\ndec1.bias torch.Size([3])\ndec2.weight torch.Size([3, 3])\ndec2.bias torch.Size([3])\n'''\n\n","repo_name":"Pusheen-cat/CLeAR_2023","sub_path":"make_encoder/encoder.py","file_name":"encoder.py","file_ext":"py","file_size_in_byte":6344,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"17"} +{"seq_id":"24337764400","text":"\nfrom __future__ import annotations\n\nfrom typing import Optional\n\nimport io\nimport os\n\nfrom allmydata.scripts.types_ import (\n SubCommands,\n Parameters,\n Flags,\n)\n\nfrom twisted.internet import reactor, defer\nfrom twisted.python.usage import UsageError\nfrom twisted.python.filepath import (\n FilePath,\n)\n\nfrom allmydata.scripts.common import (\n BasedirOptions,\n NoDefaultBasedirOptions,\n write_introducer,\n)\nfrom allmydata.scripts.default_nodedir import _default_nodedir\nfrom allmydata.util import dictutil\nfrom allmydata.util.assertutil import precondition\nfrom allmydata.util.encodingutil import listdir_unicode, argv_to_unicode, quote_local_unicode_path, get_io_encoding\n\ni2p_provider: Listener\ntor_provider: Listener\n\nfrom allmydata.util import fileutil, i2p_provider, tor_provider, jsonbytes as json\n\nfrom ..listeners import ListenerConfig, Listener, TCPProvider, StaticProvider\n\ndef _get_listeners() -> dict[str, Listener]:\n \"\"\"\n Get all of the kinds of listeners we might be able to use.\n \"\"\"\n return {\n \"tor\": tor_provider,\n \"i2p\": i2p_provider,\n \"tcp\": TCPProvider(),\n \"none\": StaticProvider(\n available=True,\n hide_ip=False,\n config=defer.succeed(None),\n # This is supposed to be an IAddressFamily but we have none for\n # this kind of provider. We could implement new client and server\n # endpoint types that always fail and pass an IAddressFamily here\n # that uses those. Nothing would ever even ask for them (at\n # least, yet), let alone try to use them, so that's a lot of extra\n # work for no practical result so I'm not doing it now.\n address=None, # type: ignore[arg-type]\n ),\n }\n\n_LISTENERS = _get_listeners()\n\ndummy_tac = \"\"\"\nimport sys\nprint(\"Nodes created by Tahoe-LAFS v1.11.0 or later cannot be run by\")\nprint(\"releases of Tahoe-LAFS before v1.10.0.\")\nsys.exit(1)\n\"\"\"\n\ndef write_tac(basedir, nodetype):\n fileutil.write(os.path.join(basedir, \"tahoe-%s.tac\" % (nodetype,)), dummy_tac)\n\n\nWHERE_OPTS : Parameters = [\n (\"location\", None, None,\n \"Server location to advertise (e.g. tcp:example.org:12345)\"),\n (\"port\", None, None,\n \"Server endpoint to listen on (e.g. tcp:12345, or tcp:12345:interface=127.0.0.1.\"),\n (\"hostname\", None, None,\n \"Hostname to automatically set --location/--port when --listen=tcp\"),\n (\"listen\", None, \"tcp\",\n \"Comma-separated list of listener types (tcp,tor,i2p,none).\"),\n]\n\nTOR_OPTS : Parameters = [\n (\"tor-control-port\", None, None,\n \"Tor's control port endpoint descriptor string (e.g. tcp:127.0.0.1:9051 or unix:/var/run/tor/control)\"),\n (\"tor-executable\", None, None,\n \"The 'tor' executable to run (default is to search $PATH).\"),\n]\n\nTOR_FLAGS : Flags = [\n (\"tor-launch\", None, \"Launch a tor instead of connecting to a tor control port.\"),\n]\n\nI2P_OPTS : Parameters = [\n (\"i2p-sam-port\", None, None,\n \"I2P's SAM API port endpoint descriptor string (e.g. tcp:127.0.0.1:7656)\"),\n (\"i2p-executable\", None, None,\n \"(future) The 'i2prouter' executable to run (default is to search $PATH).\"),\n]\n\nI2P_FLAGS : Flags = [\n (\"i2p-launch\", None, \"(future) Launch an I2P router instead of connecting to a SAM API port.\"),\n]\n\ndef validate_where_options(o):\n if o['listen'] == \"none\":\n # no other arguments are accepted\n if o['hostname']:\n raise UsageError(\"--hostname cannot be used when --listen=none\")\n if o['port'] or o['location']:\n raise UsageError(\"--port/--location cannot be used when --listen=none\")\n # --location and --port: overrides all others, rejects all others\n if o['location'] and not o['port']:\n raise UsageError(\"--location must be used with --port\")\n if o['port'] and not o['location']:\n raise UsageError(\"--port must be used with --location\")\n\n if o['location'] and o['port']:\n if o['hostname']:\n raise UsageError(\"--hostname cannot be used with --location/--port\")\n # TODO: really, we should reject an explicit --listen= option (we\n # want them to omit it entirely, because --location/--port would\n # override anything --listen= might allocate). For now, just let it\n # pass, because that allows us to use --listen=tcp as the default in\n # optParameters, which (I think) gets included in the rendered --help\n # output, which is useful. In the future, let's reconsider the value\n # of that --help text (or achieve that documentation in some other\n # way), change the default to None, complain here if it's not None,\n # then change parseArgs() to transform the None into \"tcp\"\n else:\n # no --location and --port? expect --listen= (maybe the default), and\n # --listen=tcp requires --hostname. But --listen=none is special.\n if o['listen'] != \"none\" and o.get('join', None) is None:\n listeners = o['listen'].split(\",\")\n for l in listeners:\n if l not in _LISTENERS:\n raise UsageError(\n \"--listen= must be one/some of: \"\n f\"{', '.join(sorted(_LISTENERS))}\",\n )\n if 'tcp' in listeners and not o['hostname']:\n raise UsageError(\"--listen=tcp requires --hostname=\")\n if 'tcp' not in listeners and o['hostname']:\n raise UsageError(\"--listen= must be tcp to use --hostname\")\n\ndef validate_tor_options(o):\n use_tor = \"tor\" in o[\"listen\"].split(\",\")\n if use_tor or any((o[\"tor-launch\"], o[\"tor-control-port\"])):\n if not _LISTENERS[\"tor\"].is_available():\n raise UsageError(\n \"Specifying any Tor options requires the 'txtorcon' module\"\n )\n if not use_tor:\n if o[\"tor-launch\"]:\n raise UsageError(\"--tor-launch requires --listen=tor\")\n if o[\"tor-control-port\"]:\n raise UsageError(\"--tor-control-port= requires --listen=tor\")\n if o[\"tor-launch\"] and o[\"tor-control-port\"]:\n raise UsageError(\"use either --tor-launch or --tor-control-port=, not both\")\n\ndef validate_i2p_options(o):\n use_i2p = \"i2p\" in o[\"listen\"].split(\",\")\n if use_i2p or any((o[\"i2p-launch\"], o[\"i2p-sam-port\"])):\n if not _LISTENERS[\"i2p\"].is_available():\n raise UsageError(\n \"Specifying any I2P options requires the 'txi2p' module\"\n )\n if not use_i2p:\n if o[\"i2p-launch\"]:\n raise UsageError(\"--i2p-launch requires --listen=i2p\")\n if o[\"i2p-sam-port\"]:\n raise UsageError(\"--i2p-sam-port= requires --listen=i2p\")\n if o[\"i2p-launch\"] and o[\"i2p-sam-port\"]:\n raise UsageError(\"use either --i2p-launch or --i2p-sam-port=, not both\")\n if o[\"i2p-launch\"]:\n raise UsageError(\"--i2p-launch is under development\")\n\nclass _CreateBaseOptions(BasedirOptions):\n optFlags = [\n (\"hide-ip\", None, \"prohibit any configuration that would reveal the node's IP address\"),\n ]\n\n def postOptions(self):\n super(_CreateBaseOptions, self).postOptions()\n if self['hide-ip']:\n ip_hiders = dictutil.filter(lambda v: v.can_hide_ip(), _LISTENERS)\n available = dictutil.filter(lambda v: v.is_available(), ip_hiders)\n if not available:\n raise UsageError(\n \"--hide-ip was specified but no IP-hiding listener is installed.\\n\"\n \"Try one of these:\\n\" +\n \"\".join([\n f\"\\tpip install tahoe-lafs[{name}]\\n\"\n for name\n in ip_hiders\n ])\n )\n\nclass CreateClientOptions(_CreateBaseOptions):\n synopsis = \"[options] [NODEDIR]\"\n description = \"Create a client-only Tahoe-LAFS node (no storage server).\"\n\n optParameters = [\n # we provide 'create-node'-time options for the most common\n # configuration knobs. The rest can be controlled by editing\n # tahoe.cfg before node startup.\n\n (\"nickname\", \"n\", None, \"Specify the nickname for this node.\"),\n (\"introducer\", \"i\", None, \"Specify the introducer FURL to use.\"),\n (\"webport\", \"p\", \"tcp:3456:interface=127.0.0.1\",\n \"Specify which TCP port to run the HTTP interface on. Use 'none' to disable.\"),\n (\"basedir\", \"C\", None, \"Specify which Tahoe base directory should be used. This has the same effect as the global --node-directory option. [default: %s]\"\n % quote_local_unicode_path(_default_nodedir)),\n (\"shares-needed\", None, 3, \"Needed shares required for uploaded files.\"),\n (\"shares-happy\", None, 7, \"How many servers new files must be placed on.\"),\n (\"shares-total\", None, 10, \"Total shares required for uploaded files.\"),\n (\"join\", None, None, \"Join a grid with the given Invite Code.\"),\n ] # type: Parameters\n\n # This is overridden in order to ensure we get a \"Wrong number of\n # arguments.\" error when more than one argument is given.\n def parseArgs(self, basedir=None):\n BasedirOptions.parseArgs(self, basedir)\n for name in [\"shares-needed\", \"shares-happy\", \"shares-total\"]:\n try:\n int(self[name])\n except ValueError:\n raise UsageError(\n \"--{} must be an integer\".format(name)\n )\n\n\nclass CreateNodeOptions(CreateClientOptions):\n optFlags = [\n (\"no-storage\", None, \"Do not offer storage service to other nodes.\"),\n (\"storage-dir\", None, \"Path where the storage will be placed.\"),\n (\"helper\", None, \"Enable helper\"),\n ] + TOR_FLAGS + I2P_FLAGS\n\n synopsis = \"[options] [NODEDIR]\"\n description = \"Create a full Tahoe-LAFS node (client+server).\"\n optParameters = CreateClientOptions.optParameters + WHERE_OPTS + TOR_OPTS + I2P_OPTS\n\n def parseArgs(self, basedir=None):\n CreateClientOptions.parseArgs(self, basedir)\n validate_where_options(self)\n validate_tor_options(self)\n validate_i2p_options(self)\n\n\nclass CreateIntroducerOptions(NoDefaultBasedirOptions):\n subcommand_name = \"create-introducer\"\n description = \"Create a Tahoe-LAFS introducer.\"\n optFlags = [\n (\"hide-ip\", None, \"prohibit any configuration that would reveal the node's IP address\"),\n ] + TOR_FLAGS + I2P_FLAGS\n optParameters = NoDefaultBasedirOptions.optParameters + WHERE_OPTS + TOR_OPTS + I2P_OPTS\n def parseArgs(self, basedir=None):\n NoDefaultBasedirOptions.parseArgs(self, basedir)\n validate_where_options(self)\n validate_tor_options(self)\n validate_i2p_options(self)\n\n\ndef merge_config(\n left: Optional[ListenerConfig],\n right: Optional[ListenerConfig],\n) -> Optional[ListenerConfig]:\n \"\"\"\n Merge two listener configurations into one configuration representing\n both of them.\n\n If either is ``None`` then the result is ``None``. This supports the\n \"disable listeners\" functionality.\n\n :raise ValueError: If the keys in the node configs overlap.\n \"\"\"\n if left is None or right is None:\n return None\n\n overlap = set(left.node_config) & set(right.node_config)\n if overlap:\n raise ValueError(f\"Node configs overlap: {overlap}\")\n\n return ListenerConfig(\n list(left.tub_ports) + list(right.tub_ports),\n list(left.tub_locations) + list(right.tub_locations),\n dict(list(left.node_config.items()) + list(right.node_config.items())),\n )\n\n\nasync def write_node_config(c, config):\n # this is shared between clients and introducers\n c.write(\"# -*- mode: conf; coding: {c.encoding} -*-\\n\".format(c=c))\n c.write(\"\\n\")\n c.write(\"# This file controls the configuration of the Tahoe node that\\n\")\n c.write(\"# lives in this directory. It is only read at node startup.\\n\")\n c.write(\"# For details about the keys that can be set here, please\\n\")\n c.write(\"# read the 'docs/configuration.rst' file that came with your\\n\")\n c.write(\"# Tahoe installation.\\n\")\n c.write(\"\\n\\n\")\n\n if config[\"hide-ip\"]:\n c.write(\"[connections]\\n\")\n if _LISTENERS[\"tor\"].is_available():\n c.write(\"tcp = tor\\n\")\n else:\n # XXX What about i2p?\n c.write(\"tcp = disabled\\n\")\n c.write(\"\\n\")\n\n c.write(\"[node]\\n\")\n nickname = argv_to_unicode(config.get(\"nickname\") or \"\")\n c.write(\"nickname = %s\\n\" % (nickname,))\n if config[\"hide-ip\"]:\n c.write(\"reveal-IP-address = false\\n\")\n else:\n c.write(\"reveal-IP-address = true\\n\")\n\n # TODO: validate webport\n webport = argv_to_unicode(config.get(\"webport\") or \"none\")\n if webport.lower() == \"none\":\n webport = \"\"\n c.write(\"web.port = %s\\n\" % (webport,))\n c.write(\"web.static = public_html\\n\")\n\n listener_config = ListenerConfig([], [], {})\n for listener_name in config['listen'].split(\",\"):\n listener = _LISTENERS[listener_name]\n listener_config = merge_config(\n (await listener.create_config(reactor, config)),\n listener_config,\n )\n\n if listener_config is None:\n tub_ports = [\"disabled\"]\n tub_locations = [\"disabled\"]\n else:\n tub_ports = listener_config.tub_ports\n tub_locations = listener_config.tub_locations\n\n c.write(\"tub.port = %s\\n\" % \",\".join(tub_ports))\n c.write(\"tub.location = %s\\n\" % \",\".join(tub_locations))\n c.write(\"\\n\")\n\n c.write(\"#log_gatherer.furl =\\n\")\n c.write(\"#timeout.keepalive =\\n\")\n c.write(\"#timeout.disconnect =\\n\")\n c.write(\"#ssh.port = 8022\\n\")\n c.write(\"#ssh.authorized_keys_file = ~/.ssh/authorized_keys\\n\")\n c.write(\"\\n\")\n\n if listener_config is not None:\n for section, items in listener_config.node_config.items():\n c.write(f\"[{section}]\\n\")\n for k, v in items:\n c.write(f\"{k} = {v}\\n\")\n c.write(\"\\n\")\n\n\ndef write_client_config(c, config):\n introducer = config.get(\"introducer\", None)\n if introducer is not None:\n write_introducer(\n FilePath(config[\"basedir\"]),\n \"default\",\n introducer,\n )\n\n c.write(\"[client]\\n\")\n c.write(\"helper.furl =\\n\")\n c.write(\"\\n\")\n c.write(\"# Encoding parameters this client will use for newly-uploaded files\\n\")\n c.write(\"# This can be changed at any time: the encoding is saved in\\n\")\n c.write(\"# each filecap, and we can download old files with any encoding\\n\")\n c.write(\"# settings\\n\")\n c.write(\"shares.needed = {}\\n\".format(config['shares-needed']))\n c.write(\"shares.happy = {}\\n\".format(config['shares-happy']))\n c.write(\"shares.total = {}\\n\".format(config['shares-total']))\n c.write(\"\\n\")\n\n boolstr = {True:\"true\", False:\"false\"}\n c.write(\"[storage]\\n\")\n c.write(\"# Shall this node provide storage service?\\n\")\n storage_enabled = not config.get(\"no-storage\", None)\n c.write(\"enabled = %s\\n\" % boolstr[storage_enabled])\n c.write(\"#readonly =\\n\")\n c.write(\"reserved_space = 1G\\n\")\n storage_dir = config.get(\"storage-dir\")\n if storage_dir:\n c.write(\"storage_dir = %s\\n\" % (storage_dir,))\n else:\n c.write(\"#storage_dir =\\n\")\n c.write(\"#expire.enabled =\\n\")\n c.write(\"#expire.mode =\\n\")\n c.write(\"\\n\")\n\n c.write(\"[helper]\\n\")\n c.write(\"# Shall this node run a helper service that clients can use?\\n\")\n if config.get(\"helper\"):\n c.write(\"enabled = true\\n\")\n else:\n c.write(\"enabled = false\\n\")\n c.write(\"\\n\")\n\n\n@defer.inlineCallbacks\ndef _get_config_via_wormhole(config):\n out = config.stdout\n print(\"Opening wormhole with code '{}'\".format(config['join']), file=out)\n relay_url = config.parent['wormhole-server']\n print(\"Connecting to '{}'\".format(relay_url), file=out)\n\n wh = config.parent.wormhole.create(\n appid=config.parent['wormhole-invite-appid'],\n relay_url=relay_url,\n reactor=reactor,\n )\n code = str(config['join'])\n wh.set_code(code)\n yield wh.get_welcome()\n print(\"Connected to wormhole server\", file=out)\n\n intro = {\n u\"abilities\": {\n \"client-v1\": {},\n }\n }\n wh.send_message(json.dumps_bytes(intro))\n\n server_intro = yield wh.get_message()\n server_intro = json.loads(server_intro)\n\n print(\" received server introduction\", file=out)\n if u'abilities' not in server_intro:\n raise RuntimeError(\" Expected 'abilities' in server introduction\")\n if u'server-v1' not in server_intro['abilities']:\n raise RuntimeError(\" Expected 'server-v1' in server abilities\")\n\n remote_data = yield wh.get_message()\n print(\" received configuration\", file=out)\n defer.returnValue(json.loads(remote_data))\n\n\n@defer.inlineCallbacks\ndef create_node(config):\n out = config.stdout\n err = config.stderr\n basedir = config['basedir']\n # This should always be called with an absolute Unicode basedir.\n precondition(isinstance(basedir, str), basedir)\n\n if os.path.exists(basedir):\n if listdir_unicode(basedir):\n print(\"The base directory %s is not empty.\" % quote_local_unicode_path(basedir), file=err)\n print(\"To avoid clobbering anything, I am going to quit now.\", file=err)\n print(\"Please use a different directory, or empty this one.\", file=err)\n defer.returnValue(-1)\n # we're willing to use an empty directory\n else:\n os.mkdir(basedir)\n write_tac(basedir, \"client\")\n\n # if we're doing magic-wormhole stuff, do it now\n if config['join'] is not None:\n try:\n remote_config = yield _get_config_via_wormhole(config)\n except RuntimeError as e:\n print(str(e), file=err)\n defer.returnValue(1)\n\n # configuration we'll allow the inviter to set\n whitelist = [\n 'shares-happy', 'shares-needed', 'shares-total',\n 'introducer', 'nickname',\n ]\n sensitive_keys = ['introducer']\n\n print(\"Encoding: {shares-needed} of {shares-total} shares, on at least {shares-happy} servers\".format(**remote_config), file=out)\n print(\"Overriding the following config:\", file=out)\n\n for k in whitelist:\n v = remote_config.get(k, None)\n if v is not None:\n # we're faking usually argv-supplied options :/\n v_orig = v\n if isinstance(v, str):\n v = v.encode(get_io_encoding())\n config[k] = v\n if k not in sensitive_keys:\n if k not in ['shares-happy', 'shares-total', 'shares-needed']:\n print(\" {}: {}\".format(k, v_orig), file=out)\n else:\n print(\" {}: [sensitive data; see tahoe.cfg]\".format(k), file=out)\n\n fileutil.make_dirs(os.path.join(basedir, \"private\"), 0o700)\n cfg_name = os.path.join(basedir, \"tahoe.cfg\")\n with io.open(cfg_name, \"w\", encoding='utf-8') as c:\n yield defer.Deferred.fromCoroutine(write_node_config(c, config))\n write_client_config(c, config)\n\n print(\"Node created in %s\" % quote_local_unicode_path(basedir), file=out)\n tahoe_cfg = quote_local_unicode_path(os.path.join(basedir, \"tahoe.cfg\"))\n introducers_yaml = quote_local_unicode_path(\n os.path.join(basedir, \"private\", \"introducers.yaml\"),\n )\n if not config.get(\"introducer\", \"\"):\n print(\" Please add introducers to %s!\" % (introducers_yaml,), file=out)\n print(\" The node cannot connect to a grid without it.\", file=out)\n if not config.get(\"nickname\", \"\"):\n print(\" Please set [node]nickname= in %s\" % tahoe_cfg, file=out)\n defer.returnValue(0)\n\ndef create_client(config):\n config['no-storage'] = True\n config['listen'] = \"none\"\n return create_node(config)\n\n\n@defer.inlineCallbacks\ndef create_introducer(config):\n out = config.stdout\n err = config.stderr\n basedir = config['basedir']\n # This should always be called with an absolute Unicode basedir.\n precondition(isinstance(basedir, str), basedir)\n\n if os.path.exists(basedir):\n if listdir_unicode(basedir):\n print(\"The base directory %s is not empty.\" % quote_local_unicode_path(basedir), file=err)\n print(\"To avoid clobbering anything, I am going to quit now.\", file=err)\n print(\"Please use a different directory, or empty this one.\", file=err)\n defer.returnValue(-1)\n # we're willing to use an empty directory\n else:\n os.mkdir(basedir)\n write_tac(basedir, \"introducer\")\n\n fileutil.make_dirs(os.path.join(basedir, \"private\"), 0o700)\n cfg_name = os.path.join(basedir, \"tahoe.cfg\")\n with io.open(cfg_name, \"w\", encoding='utf-8') as c:\n yield defer.Deferred.fromCoroutine(write_node_config(c, config))\n\n print(\"Introducer created in %s\" % quote_local_unicode_path(basedir), file=out)\n defer.returnValue(0)\n\n\nsubCommands : SubCommands = [\n (\"create-node\", None, CreateNodeOptions, \"Create a node that acts as a client, server or both.\"),\n (\"create-client\", None, CreateClientOptions, \"Create a client node (with storage initially disabled).\"),\n (\"create-introducer\", None, CreateIntroducerOptions, \"Create an introducer node.\"),\n]\n\ndispatch = {\n \"create-node\": create_node,\n \"create-client\": create_client,\n \"create-introducer\": create_introducer,\n }\n","repo_name":"tahoe-lafs/tahoe-lafs","sub_path":"src/allmydata/scripts/create_node.py","file_name":"create_node.py","file_ext":"py","file_size_in_byte":21449,"program_lang":"python","lang":"en","doc_type":"code","stars":1256,"dataset":"github-code","pt":"17"} +{"seq_id":"6655875237","text":"\"\"\"\nsimple config parser handler\n\"\"\"\nimport time, sys, os\nimport treelib\n\n\n# example:\n#\n# exp_config = {\n# \"experiment\": \"test1\",\n# \"addresses\":\n# {\n# \"pc1\": \"tcp://192.168.100.4:5566\",\n# \"pc2\": \"tcp://192.168.100.8:5566\"\n# }\n# # pc_name : tcp addr and port\n# # every broker must know own pc name\n# }\n\nclass ConfigParser():\n \"\"\"\n\n \"\"\"\n # __slots__ = ()\n\n def __init__(self):\n # super().__init__()\n self.config = None\n pass\n\n def init_from_dict(self, exp_config):\n\n self.config = exp_config\n\n self.exp_tree = treelib.Tree()\n self.exp_tree.create_node(\"{} - {}\".format(\"experiment\", self.config[\"experiment\"]), 1)\n counter = 1\n last_counter = counter\n for broker in self.config[\"brokers\"]:\n print(broker)\n counter = counter + 1\n self.exp_tree.create_node(\"{} - {}\".format(\n broker, self.config[\"brokers\"][broker]), counter, parent=1)\n last_counter = counter\n for node in self.config[\"brokers\"][broker][\"nodes\"]:\n counter = counter + 1\n self.exp_tree.create_node(\"{} - {}\".format(\n node,\n self.config[\"brokers\"][broker][\"nodes\"][node]), counter, parent=last_counter)\n\n def init_from_yaml(self, path):\n pass # todo\n\n def get_brokers(self):\n return self.config[\"brokers\"]\n\n def get_nodes(self, broker):\n return self.config[\"brokers\"][broker][\"nodes\"]\n\n def get_devices(self, broker, node):\n return self.config[\"brokers\"][broker][\"nodes\"][node]\n\n def get_exp_info(self):\n return self.config[\"experiment\"]\n\n def show_pretty_graph(self):\n self.exp_tree.show()\n\n\n# https://stackoverflow.com/questions/4014621/a-python-class-that-acts-like-dict\n# https://stackoverflow.com/questions/682504/what-is-a-clean-pythonic-way-to-have-multiple-constructors-in-python\n# TODO\n\n\nif __name__ == \"__main__\":\n # example:\n\n c = ConfigParser()\n\n exp_config = {\n \"experiment\": \"test1\",\n \"description\": \"nice test experiment\",\n \"brokers\":\n {\n \"pc1\": {\n \"addr\": \"tcp://192.168.100.4:5566\", \"nodes\":\n {\n \"node1\": {\"description\": \"temp\", \"devices\": {}},\n \"node2\": {\"description\": \"temp\", \"devices\": {}},\n \"node3\": {\"description\": \"temp\", \"devices\": {}},\n },\n },\n \"pc2\": {\n \"addr\": \"tcp://192.168.100.8:5566\", \"nodes\":\n {\n \"node6\": {\"description\": \"temp\", \"devices\": {}},\n \"node4\": {\"description\": \"temp\", \"devices\": {}},\n \"node5\": {\"description\": \"temp\", \"devices\": {}},\n },\n }\n }\n }\n print(exp_config[\"brokers\"][\"pc1\"][\"addr\"])\n c.init_from_dict(exp_config)\n # c = ConfigParser(exp_config)\n print(c.get_brokers())\n print(c.get_nodes(\"pc1\"))\n c.show_pretty_graph()\n\n","repo_name":"houseofbigseals/plexus","sub_path":"src/plexus/utils/config_parser.py","file_name":"config_parser.py","file_ext":"py","file_size_in_byte":3091,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"17"} +{"seq_id":"7124669686","text":"import json\n\ndef suggest_medicine(disease):\n with open(\"../datasets/medicines.json\") as file:\n di = json.load(file)\n file.close()\n if disease in di:\n medicines = ', '.join(di[disease][:3])\n else:\n medicines = 'consult a doctor for medicines'\n return medicines","repo_name":"hvt16/healthcare","sub_path":"server/medicine_suggestion.py","file_name":"medicine_suggestion.py","file_ext":"py","file_size_in_byte":299,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"17"} +{"seq_id":"39853587646","text":"from typing import Optional\n\n\nclass ListNode:\n def __init__(self, x):\n self.val = x\n self.next = None\n\n\n# leetcode submit region begin(Prohibit modification and deletion)\n# Definition for singly-linked list.\n# class ListNode:\n# def __init__(self, val=0, next=None):\n# self.val = val\n# self.next = next\nclass Solution:\n def removeNthFromEnd(self, head: Optional[ListNode], n: int) -> Optional[ListNode]:\n # 前边指针先走 n 步\n quick, slow = head, head\n for _ in range(n):\n quick = quick.next\n \n # 考虑 len(head) == n 的情况\n if quick is None:\n return head.next\n \n # slow 停在了需要删除点的前边\n while quick is not None and quick.next is not None:\n slow = slow.next\n quick = quick.next\n \n slow.next = slow.next.next\n return head\n\n\n# leetcode submit region end(Prohibit modification and deletion)\n\nif __name__ == \"__main__\":\n node1 = ListNode(1)\n node2 = ListNode(2)\n node3 = ListNode(3)\n node4 = ListNode(4)\n node5 = ListNode(5)\n \n node1.next = node2\n node2.next = node3\n node3.next = node4\n node4.next = node5\n \n solution = Solution()\n res = solution.removeNthFromEnd(node1, 5)\n \n while res is not None:\n print(res.val)\n res = res.next\n","repo_name":"mmmwhy/algorithm_code","sub_path":"leetcode/editor/cn/[19]删除链表的倒数第 N 个结点.py","file_name":"[19]删除链表的倒数第 N 个结点.py","file_ext":"py","file_size_in_byte":1384,"program_lang":"python","lang":"en","doc_type":"code","stars":144,"dataset":"github-code","pt":"17"} +{"seq_id":"71660954891","text":"# https://www.acmicpc.net/problem/17471\n\nfrom itertools import combinations\nfrom collections import deque\n\ndef bfs(target) :\n visited = [False] * (n+1)\n q = deque()\n q.append(target[0])\n visited[target[0]] = True\n\n while q : \n x = q.popleft()\n for nx in graph[x] :\n if nx in target and not visited[nx] :\n visited[nx] = True\n q.append((nx))\n\n total = 0 \n\n for node in target :\n if not visited[node] :\n return int(1e9) \n total += value[node] \n return total\n\n\nn = int(input())\ngraph =[[] for _ in range(n+1)]\ncombi_lst = [i for i in range(1, n+1)]\nvalue = [0] + list(map(int,input().split()))\n\nanswer= int(1e9) \n\n\nfor a in range(1,n + 1) :\n lst = list(map(int,input().split()))\n del lst[0]\n for b in lst :\n graph[a].append(b)\n\nfor c in range(1, (n // 2) + 1) :\n lst = list(combinations(combi_lst, c))\n for l in lst :\n one = list(l)\n two = [i for i in combi_lst if i not in one]\n \n ototal = bfs(one)\n ttotal = bfs(two) \n \n if int(1e9) in [ototal, ttotal] : continue\n\n answer = min(answer, abs(ototal-ttotal))\n\nif answer < int(1e9) :\n print(answer)\nelse :\n print(-1)","repo_name":"M0o0o0o/Algorithm_Study","sub_path":"DFS_BFS/problem17471.py","file_name":"problem17471.py","file_ext":"py","file_size_in_byte":1249,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"15"} +{"seq_id":"8704156845","text":"import torch\nimport torch.nn as nn\nimport torch.nn.functional as F\n\n\n# paper: https://arxiv.org/pdf/1907.05062.pdf\n\ndef conv3x3x3(in_channels, out_channels, stride=1):\n return nn.Conv3d(in_channels, out_channels, kernel_size=3, stride=stride, padding=1, bias=False)\n\n\nclass ResidualBlock(nn.Module):\n def __init__(self, in_channels, out_channels, stride=1, downsample=None):\n super(ResidualBlock, self).__init__()\n self.conv1 = conv3x3x3(in_channels, out_channels, stride)\n self.bn1 = nn.BatchNorm3d(out_channels)\n self.relu = nn.ReLU(inplace=True)\n self.conv2 = conv3x3x3(out_channels, out_channels)\n self.bn2 = nn.BatchNorm3d(out_channels)\n self.downsample = downsample\n\n def forward(self, x):\n residual = x\n out = self.conv1(x)\n out = self.bn1(out)\n out = self.relu(out)\n out = self.conv2(out)\n out = self.bn2(out)\n if self.downsample:\n residual = self.downsample(x)\n out += residual\n out = self.relu(out)\n return out\n\n\nclass Fire_Encoder(nn.Module):\n def __init__(self, in_channel, start_channel):\n self.in_channel = in_channel\n self.start_channel = start_channel\n super(Fire_Encoder, self).__init__()\n self.encoder0 = self.encoder(self.in_channel, self.start_channel, bias=True)\n\n self.encoder1 = self.encoder(self.start_channel, self.start_channel * 2, stride=2, bias=True)\n\n self.encoder2 = self.encoder(self.start_channel * 2, self.start_channel * 4, stride=2, bias=True)\n\n self.residual_block1 = ResidualBlock(self.start_channel * 4, self.start_channel * 4)\n\n self.residual_block2 = ResidualBlock(self.start_channel * 4, self.start_channel * 4)\n\n self.residual_block3 = ResidualBlock(self.start_channel * 4, self.start_channel * 4)\n\n self.residual_block4 = ResidualBlock(self.start_channel * 4, self.start_channel * 4)\n\n def encoder(self, in_channels, out_channels, kernel_size=3, stride=1, padding=1, bias=True):\n layer = nn.Sequential(\n nn.Conv3d(in_channels, out_channels, kernel_size, stride=stride, padding=padding, bias=bias),\n nn.InstanceNorm3d(out_channels),\n nn.LeakyReLU())\n layer # .to(\"cuda\")\n return layer\n\n def forward(self, x):\n e0 = self.encoder0(x)\n e1 = self.encoder1(e0)\n e2 = self.encoder2(e1)\n e3 = self.residual_block1(e2)\n e4 = self.residual_block1(e3)\n e5 = self.residual_block1(e4)\n e6 = self.residual_block1(e5)\n\n return e6\n\n\nclass Synthesizer_Decoder(nn.Module):\n def __init__(self, start_channel):\n # self.in_channel = in_channel\n self.start_channel = start_channel\n\n ## Declarations #####\n super(Synthesizer_Decoder, self).__init__()\n self.rb1 = ResidualBlock(self.start_channel * 4, self.start_channel * 4, 1)\n self.rb2 = ResidualBlock(self.start_channel * 4, self.start_channel * 4, 1)\n self.rb3 = ResidualBlock(self.start_channel * 4, self.start_channel * 4, 1)\n self.rb4 = ResidualBlock(self.start_channel * 4, self.start_channel * 4, 1)\n\n self.up1 = self.decoder(self.start_channel * 4, self.start_channel * 2)\n self.up2 = self.decoder(self.start_channel * 2, self.start_channel * 1)\n\n self.cb = self.convblock(self.start_channel * 1, self.start_channel // 2)\n self.out = self.onecrossoneblock(self.start_channel // 2, 1)\n\n # Decoder upsampler block start #\n def decoder(self, in_channels, out_channels, kernel_size=2, stride=2, padding=0,\n output_padding=0, bias=True):\n layer = nn.Sequential(\n nn.ConvTranspose3d(in_channels, out_channels, kernel_size, stride=stride,\n padding=padding, output_padding=output_padding, bias=bias),\n nn.LeakyReLU())\n return layer\n\n def convblock(self, in_channels, out_channels, kernel_size=3,\n bias=False, batchnorm=False):\n layer = nn.Sequential(nn.Conv3d(in_channels, out_channels, kernel_size, bias=bias, padding=0), )\n return layer\n\n def onecrossoneblock(self, in_channels, out_channels=1, kernel_size=1,\n bias=False, batchnorm=False):\n layer = nn.Sequential(\n nn.Conv3d(in_channels, out_channels, kernel_size, bias=bias, padding=1),\n )\n return layer\n\n def forward(self, x):\n rout = self.rb1(x)\n rout = self.rb2(rout)\n rout = self.rb3(rout)\n rout = self.rb4(rout)\n dec1 = self.up1(rout)\n dec2 = self.up2(dec1)\n cbo = self.cb(dec2)\n output = self.out(cbo)\n return output\n\n\n# grid sampler code\n\nclass SpatialTransformer(nn.Module):\n \"\"\"\n N-D Spatial Transformer\n \"\"\"\n\n def __init__(self, size, is_affine=False, theta=None, mode='bilinear', affine_image_size=(2, 1, 128, 128, 128)):\n super().__init__()\n\n self.mode = mode\n self.isaffine = is_affine\n self.theta = theta\n self.affine_image_size = affine_image_size\n # create sampling grid\n # registering the grid as a buffer cleanly moves it to the GPU, but it also\n # adds it to the state dict. this is annoying since everything in the state dict\n # is included when saving weights to disk, so the model files are way bigger\n # than they need to be. so far, there does not appear to be an elegant solution.\n # see: https://discuss.pytorch.org/t/how-to-register-buffer-without-polluting-state-dict\n\n if (self.isaffine):\n grid = F.affine_grid(self.theta, self.affine_image_size, align_corners=False)\n # grid = grid.permute(0, 4, 1, 2, 3)\n self.register_buffer('grid', grid)\n else:\n vectors = [torch.arange(0, s) for s in size]\n grids = torch.meshgrid(vectors)\n grid = torch.stack(grids)\n grid = torch.unsqueeze(grid, 0)\n grid = grid.type(torch.FloatTensor)\n self.register_buffer('grid', grid)\n\n def forward(self, src, flow=None):\n if (self.isaffine):\n grid = F.affine_grid(self.theta, self.affine_image_size)\n\n warped_image = F.grid_sample(src, grid)\n\n # warped_image = warped_image.permute(0, 4, 1, 2, 3)\n return warped_image\n else:\n # new locations\n new_locs = self.grid + flow\n shape = flow.shape[2:]\n\n # need to normalize grid values to [-1, 1] for resampler\n for i in range(len(shape)):\n new_locs[:, i, ...] = 2 * (new_locs[:, i, ...] / (shape[i] - 1) - 0.5)\n\n # move channels dim to last position\n # also not sure why, but the channels need to be reversed\n if len(shape) == 2:\n new_locs = new_locs.permute(0, 2, 3, 1)\n new_locs = new_locs[..., [1, 0]]\n elif len(shape) == 3:\n new_locs = new_locs.permute(0, 2, 3, 4, 1)\n new_locs = new_locs[..., [2, 1, 0]]\n\n return F.grid_sample(src, new_locs, align_corners=True, mode=self.mode)\n\n\nclass Transformation_Deformable_Network(nn.Module):\n def __init__(self, start_channel):\n # self.in_channel = in_channel\n self.start_channel = start_channel\n super(Transformation_Deformable_Network, self).__init__()\n\n self.convblock1 = self.convblock(self.start_channel * 32, 8)\n self.convblock2 = self.convblock(self.start_channel * 32, 8)\n\n self.rb1 = ResidualBlock(16, 16, 1)\n\n ## Harcoded to get the output channels to 3 as deformable field has 3 fields ##\n self.convblock3 = self.convblock(16, 3)\n self.lkrelublock1 = self.leakyrelublock()\n self.lkrelublock2 = self.leakyrelublock()\n self.lkrelublock3 = self.leakyrelublock()\n\n self.inb1 = self.instancenormblock(3)\n self.inb2 = self.instancenormblock(3)\n\n self.tb1 = self.tanhblock()\n\n return;\n\n def convblock(self, in_channels, out_channels, kernel_size=3, bias=False, batchnorm=False):\n layer = nn.Sequential(nn.Conv3d(in_channels, out_channels, kernel_size, bias=bias, padding=1), )\n return layer\n\n def leakyrelublock(self):\n layer = nn.LeakyReLU()\n return layer\n\n def instancenormblock(self, out_channels):\n layer = nn.InstanceNorm3d(out_channels)\n return layer\n\n def tanhblock(self):\n layer = nn.Tanh()\n return layer\n\n def forward(self, gx, gy):\n cb1 = self.convblock1(gx)\n cb1 = self.lkrelublock1(cb1)\n cb2 = self.convblock2(gy)\n cb2 = self.lkrelublock2(cb2)\n\n cat_in = torch.cat((cb1, cb2), 1)\n\n rb = self.rb1(cat_in)\n print(rb.shape)\n ib1 = self.inb1(rb)\n print(ib1.shape)\n lk = self.lkrelublock3(ib1)\n cb3 = self.convblock3(lk)\n ib2 = self.inb2(cb3)\n tanhb1 = self.tb1(ib2)\n return tanhb1\n\n\ndef rmse_loss(input, target):\n y_true_f = input.view(-1)\n y_pred_f = target.view(-1)\n diff = y_true_f - y_pred_f\n mse = torch.mul(diff, diff).mean()\n rmse = torch.sqrt(mse)\n return rmse\n\n\ndef smoothloss(y_pred):\n dy = torch.abs(y_pred[:, :, 1:, :, :] - y_pred[:, :, :-1, :, :])\n dx = torch.abs(y_pred[:, :, :, 1:, :] - y_pred[:, :, :, :-1, :])\n dz = torch.abs(y_pred[:, :, :, :, 1:] - y_pred[:, :, :, :, :-1])\n return (torch.mean(dx * dx) + torch.mean(dy * dy) + torch.mean(dz * dz)) / 3.0\n","repo_name":"Himanshi1904/fire-implementation","sub_path":"Models.py","file_name":"Models.py","file_ext":"py","file_size_in_byte":9525,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"15"} +{"seq_id":"43137749332","text":"from tensorflow.keras.callbacks import TensorBoard\nfrom tensorflow.keras.callbacks import ModelCheckpoint\nfrom tensorflow.keras.callbacks import EarlyStopping\nfrom tensorflow.keras.models import load_model\nfrom tensorflow.keras.utils import Sequence\nfrom network.model import TextScannerModel\nfrom utils.visualise_callback import TBoardVisual\nfrom utils.sequence import SequenceData\nfrom utils.label import label_utils\nfrom utils import logger as log\nfrom utils import util\nfrom utils.label.label_maker import LabelGenerater\nimport logging\nimport conf\nimport os\nimport time\nimport math\nimport numpy as np\nimport cv2\nimport scipy.ndimage.filters as fi\nfrom utils import image_utils\nfrom utils.label.label import ImageLabel\nfrom tensorflow.keras.utils import to_categorical\nfrom tensorflow.keras.preprocessing.sequence import pad_sequences\n\nlogger = logging.getLogger(\"SequenceData\")\n\nclass LabelGenerater():\n def __init__(self, max_sequence, target_image_shape, charset):\n self.max_sequence = max_sequence\n self.target_image_shape = target_image_shape # [H,W]: [64,256]\n self.target_width = target_image_shape[1]\n self.target_height = target_image_shape[0]\n self.charset = charset\n\n def process(self, image_labels):\n\n # adjust the coordination\n shape = image_labels.image.shape[:2] # h,w\n boxes = image_labels.bboxes # [N,4,2] N: words number\n label = image_labels.label\n\n # # find the one bbox boundary\n # xmins = boxes[:, :, 0].min(axis=1)\n # xmaxs = np.maximum(boxes[:, :, 0].max(axis=1), xmins + 1)\n # ymins = boxes[:, :, 1].min(axis=1)\n # ymaxs = np.maximum(boxes[:, :, 1].max(axis=1), ymins + 1)\n\n character_segment = self.render_character_segemention(image_labels)\n localization_map = np.zeros(self.target_image_shape, dtype=np.float32)\n order_segments = np.zeros((*self.target_image_shape, self.max_sequence), dtype=np.float32)\n #order_maps = np.zeros((*self.target_image_shape, self.max_sequence), dtype=np.float32)\n\n assert boxes.shape[0] <= self.max_sequence, \\\n f\"the train/validate label text length[{len(image_labels.labels)}] must be less than pre-defined max sequence length[{self.max_sequence}]\"\n\n # process each character\n for i in range(boxes.shape[0]):\n # Y_hat_k is the normalized_gaussian map, comply with the name in the paper\n Y_hat_k = self.generate_Y_hat_k_by_gaussian_normalize(self.target_image_shape,\n boxes[i]) # xmins[i], xmaxs[i], ymins[i], ymaxs[i])\n if Y_hat_k is None:\n logger.warning(\"Y_%d generator failed,the char[%s] of [%s]\", i, label[i], label)\n Y_hat_k = np.zeros((self.target_image_shape))\n\n self.render_order_segment(order_segments[:, :, i], Y_hat_k, threshold=self.ζ)\n localization_map = self.render_localization_map(localization_map, Y_hat_k)\n #order_maps = order_segments * localization_map[:, :, np.newaxis]\n\n return character_segment, order_segments, localization_map\n\n # 围绕中心点做一个高斯分布,但是由于每个点的概率值过小,所以要做一个归一化,使得每个点的值归一化到[0,1]之间\n # Make a gaussian distribution with the center, and do normalization\n # def gaussian_normalize(self, shape, xmin, xmax, ymin, ymax):\n # @return a \"image\" with shape[H,W], which is filled by a gaussian distribution\n def generate_Y_hat_k_by_gaussian_normalize(self, shape, one_word_bboxes): # one_word_bboxes[4,2]\n # logger.debug(\"The word bbox : %r , image shape is : %r\", one_word_bboxes, shape)\n\n # find the one bbox boundary\n xmin = one_word_bboxes[:, 0].min()\n xmax = one_word_bboxes[:, 0].max()\n ymin = one_word_bboxes[:, 1].min()\n ymax = one_word_bboxes[:, 1].max()\n\n out = np.zeros(shape)\n h, w = shape[:2]\n # find the \"Center\" of polygon\n y = (ymax + ymin + 1) // 2\n x = (xmax + xmin + 1) // 2\n if x > w or y > h:\n logger.warning(\"标注超出图像范围,生成高斯样本失败:(xmin:%f, xmax:%f, ymin:%f, ymax:%f,w:%f,x:%f,h:%f,y:%f)\", xmin, xmax,\n ymin, ymax, w, x, h, y)\n return None\n\n # prepare the gaussian distribution,refer to paper <