diff --git "a/5564.jsonl" "b/5564.jsonl" new file mode 100644--- /dev/null +++ "b/5564.jsonl" @@ -0,0 +1,1556 @@ +{"seq_id":"41307057514","text":"\"\"\"\n! ----- Shock Detection Module -----\n\n-- Accidently coded this guess accidental things are blessing in disguise too. - Waass\n\"\"\"\n\nimport cv2\nimport mediapipe as mp\nimport time\nimport math\nfrom Modules.FaceMeshModule import FaceMeshDetector \n\n#! Global Variables\n#* Default Dimensions for Webcam: 1280 x 720 / Dimensions for Test Videos: 700 x 925\nWIDTH = 1280\nHEIGHT = 720\nDIMENTION = (WIDTH, HEIGHT)\n\n#! Defining smiling landmarks and hypotenus calculation\ndef shockPoints(img, faces):\n #* Face mesh landmarks to analyse\n left_idList1 = faces[0][103]\n left_idList2 = faces[0][52]\n right_idList1 = faces[0][282]\n right_idList2 = faces[0][333]\n\n #* Left corner and right corner are points for detecting face inside box\n left_corner = faces[0][137]\n left_cornerX, left_cornerY = left_corner[1], left_corner[2]\n \n right_corner = faces[0][366]\n right_cornerX, right_cornerY = right_corner[1], right_corner[2]\n points = [left_cornerX, left_cornerY, right_cornerX , right_cornerY]\n\n #* Smile detection points\n left_topX, left_topY = left_idList1[1], left_idList1[2] \n left_botX, left_botY = left_idList2[1], left_idList2[2]\n right_topX, right_topY = right_idList1[1], right_idList1[2]\n right_botX, right_botY = right_idList2[1], right_idList2[2] \n \n\n #* Drawing smile landmarks on the facemesh in green\n #cv2.circle(img, (left_idList1[1], left_idList1[2]), 3, (0,255,0), 2, cv2.FILLED)\n #cv2.circle(img, (left_idList2[1], left_idList2[2]), 3, (0,255,0), 2, cv2.FILLED)\n #cv2.circle(img, (right_idList1[1], right_idList1[2]), 3, (0,255,0), 2 , cv2.FILLED)\n #cv2.circle(img, (right_idList2[1], right_idList2[2]), 3, (0,255,0), 2 , cv2.FILLED)\n\n #* Calculation of distance between landmarks\n leftHypotenuse = math.hypot(left_topX - left_botX, left_topY - left_botY)\n rightHypotenuse = math.hypot(right_topX - right_botX, right_topY - right_botY)\n \n\n return leftHypotenuse, rightHypotenuse, points\n\n\n#! Detecting smile \ndef shockDetection(img, leftHypotenuse, rightHypotenuse , points):\n #* Optimal top left and right bottom coordinates for rectangle \n startPoint = (240, 100)\n endPoint = (440, 350)\n\n cv2.rectangle(img, startPoint, endPoint, (255,255,0), 2) \n \n print('Lefthyptonus: ' + str(leftHypotenuse))\n\n #* Face detection within box limits\n if(boxLimit(points)):\n if ((leftHypotenuse < 29)):\n cv2.putText(img, \"Oh no\", (200, 60), cv2.FONT_HERSHEY_PLAIN, 4, (255,0,0), 2)\n else:\n cv2.putText(img, \"BRO?\", (200, 60), cv2.FONT_HERSHEY_PLAIN, 4, (255,0,0), 2) \n\n\n#! Checks if the face corner points are inside the box or not. \n#! Returns true and face accordingly\ndef boxLimit(points):\n left = points[0]\n right = points[2]\n\n if (left > 235 and right < 435):\n return True\n else: \n return False\n\n#! Main function\ndef main():\n pTime = 0\n cap = cv2.VideoCapture(0)\n detector = FaceMeshDetector()\n\n while True:\n success, img = cap.read()\n img, faces = detector.findFaceMesh(img)\n\n #* FPS Calculation and Output\n cTime = time.time()\n fps = 1/(cTime-pTime)\n pTime = cTime\n #cv2.putText(img, f'FPS: {int(fps)}', (20,70), cv2.FONT_HERSHEY_PLAIN, 2, (0,0,255), 2)\n\n leftHypo, rightHypo , points = shockPoints(img, faces)\n shockDetection(img, leftHypo, rightHypo , points)\n\n #* Final Image Output\n resizedImg = cv2.resize(img, DIMENTION, interpolation=cv2.INTER_AREA)\n cv2.imshow('Image', resizedImg)\n\n if cv2.waitKey(20) & 0xFF == ord('q'):\n break\n\n\nif __name__ == \"__main__\":\n main()","repo_name":"waasiq/icare","sub_path":"src/shockDetection.py","file_name":"shockDetection.py","file_ext":"py","file_size_in_byte":3701,"program_lang":"python","lang":"en","doc_type":"code","stars":3,"dataset":"github-code","pt":"48"} +{"seq_id":"4658567455","text":"from flask import render_template, redirect, url_for, request, flash, jsonify\nfrom flask_login import login_required\n\nfrom .forms import AddForm, EditForm, ViewForm\nfrom .. import db, log, admin_required, user_plus_required\nfrom ..documents import upload_doc\nfrom . import invoice\nfrom ..models import Invoice, DeviceCategory, Device, Purchase\nfrom ..documents import get_doc_list\n\nfrom ..support import build_filter, get_ajax_table\nfrom ..tables_config import tables_configuration\nimport os, json\nfrom flask_uploads import UploadSet, configure_uploads, DOCUMENTS\n\n@invoice.route('/invoice/data', methods=['GET', 'POST'])\n@login_required\ndef source_data():\n return get_ajax_table(tables_configuration['invoice'])\n\n@invoice.route('/invoice', methods=['GET', 'POST'])\n@login_required\ndef invoices():\n _filter, _filter_form, a,b, c = build_filter(tables_configuration['invoice'])\n return render_template('base_multiple_items.html', title='facturen',\n filter=_filter, filter_form=_filter_form,\n config=tables_configuration['invoice'])\n\n\n@invoice.route('/invoice/add/', methods=['GET', 'POST'])\n@invoice.route('/invoice/add', methods=['GET', 'POST'])\n@login_required\n@user_plus_required\ndef add(id=-1):\n if id > -1:\n invoice = Invoice.query.get_or_404(int(id))\n form = AddForm(obj=invoice)\n purchase_data = []\n for purchase in invoice.purchases:\n purchase_data.append({\n 'id': purchase.id,\n 'value': float(purchase.value),\n 'category_id': purchase.device.category_id,\n 'device_id': purchase.device.id,\n 'commissioning': purchase.commissioning\n })\n else:\n form = AddForm()\n purchase_data = []\n if 'button' in request.form and request.form['button'] == 'Bewaar' and form.validate_on_submit():\n invoice = Invoice(\n number=form.number.data,\n since=form.since.data,\n info=form.info.data,\n supplier = form.supplier.data)\n db.session.add(invoice)\n purchase_data = json.loads(request.form['purchase-data'])\n for purchase in purchase_data:\n if purchase['device'] != '':\n try:\n new_purchase = Purchase(\n invoice=invoice,\n value=float(purchase['value'].replace(',', '.')),\n device_id=int(purchase['device']),\n commissioning=purchase['commissioning']\n )\n db.session.add(new_purchase)\n except Exception:\n pass\n db.session.commit()\n log.info('add: {}'.format(invoice.log()))\n return redirect(url_for('invoice.invoices'))\n select_list = {\n 'category': DeviceCategory.get_list_for_select_first_empty(),\n 'commissioning': list(zip([''] + get_doc_list('commissioning'), [''] + get_doc_list('commissioning'))),\n 'device': Device.get_list_for_select_first_empty()\n }\n return render_template('invoice/invoice.html', form=form, title='Voeg een factuur toe', role='add',\n route='invoice.invoices', subject='invoice', select_list=select_list,\n purchase_data=purchase_data)\n\n\n@invoice.route('/invoice/edit/', methods=['GET', 'POST'])\n@login_required\n@user_plus_required\ndef edit(id):\n invoice = Invoice.query.get_or_404(id)\n form = EditForm(obj=invoice)\n if form.validate_on_submit():\n if request.form['button'] == 'Bewaar':\n form.populate_obj(invoice)\n purchase_data = json.loads(request.form['purchase-data'])\n for purchase in purchase_data:\n try: # skip non-valid entries\n if int(purchase['purchase-id']) != -1:\n update_purchase = Purchase.query.get(int(purchase['purchase-id']))\n update_purchase.value = float(purchase['value'].replace(',', '.')),\n update_purchase.device_id = int(purchase['device']),\n update_purchase.commissioning = purchase['commissioning']\n elif int(purchase['device']) != -1:\n new_purchase = Purchase(\n invoice=invoice,\n value=float(purchase['value'].replace(',', '.')),\n device_id=int(purchase['device']),\n commissioning=purchase['commissioning']\n )\n db.session.add(new_purchase)\n except Exception:\n pass\n db.session.commit()\n log.info('edit : {}'.format(invoice.log()))\n return redirect(url_for('invoice.invoices'))\n select_list = {\n 'category': DeviceCategory.get_list_for_select_first_empty(),\n 'commissioning': list(zip([''] + get_doc_list('commissioning'), [''] + get_doc_list('commissioning'))),\n 'device': Device.get_list_for_select_first_empty()\n }\n purchase_data = []\n for purchase in invoice.purchases:\n purchase_data.append({\n 'id': purchase.id,\n 'value': str(float(purchase.value)).replace('.', ','),\n 'category_id': purchase.device.category_id,\n 'device_id': purchase.device.id,\n 'commissioning': purchase.commissioning\n })\n return render_template('invoice/invoice.html', form=form, title='Wijzig een factuur', role='edit',\n route='invoice.invoices', subject='invoice', select_list=select_list,\n purchase_data=purchase_data)\n\n\n@invoice.route('/invoice/view/', methods=['GET', 'POST'])\ndef view(id):\n invoice = Invoice.query.get_or_404(id)\n form = ViewForm(obj=invoice)\n if form.validate_on_submit():\n return redirect(url_for('invoice.invoices'))\n\n select_list = {\n 'category': DeviceCategory.get_list_for_select_first_empty(),\n 'commissioning': list(zip([''] + get_doc_list('commissioning'), [''] + get_doc_list('commissioning'))),\n 'device': Device.get_list_for_select_first_empty()\n }\n purchase_data = []\n for purchase in invoice.purchases:\n purchase_data.append({\n 'id': purchase.id,\n 'value': str(float(purchase.value)).replace('.', ','),\n 'category_id': purchase.device.category_id,\n 'device_id': purchase.device.id,\n 'commissioning': purchase.commissioning\n })\n return render_template('invoice/invoice.html', form=form, title='Bekijk een factuur', role='view',\n route='invoice.invoices', subject='invoice', select_list=select_list,\n purchase_data=purchase_data)\n\n@invoice.route('/invoice/delete/', methods=['GET', 'POST'])\n@login_required\n@user_plus_required\ndef delete(id):\n invoice = Invoice.query.get_or_404(id)\n log.info('delete: {}'.format(invoice.log()))\n db.session.delete(invoice)\n db.session.commit()\n return redirect(url_for('invoice.invoices'))\n\n@invoice.route('/invoice/item_ajax/', methods=['GET', 'POST'])\n@login_required\ndef item_ajax(jds):\n try:\n jd = json.loads(jds)\n if jd['action'] == 'category-changed':\n data = {\n 'device_options': Device.get_list_for_select_first_empty(int(jd['category-id'])),\n 'opaque_element_id': jd['opaque-element-id'],\n }\n return jsonify({\"status\": True, \"data\": data})\n except Exception as e:\n return jsonify({\"status\": False, 'details': f'{e}'})\n return jsonify({\"status\": False, 'details': f'Er is iets fout gegaan met action: {jd[\"action\"]}\\n{jds}'})\n\n\n@invoice.route('/invoice/add_asset/', methods=['GET', 'POST'])\n@login_required\n@user_plus_required\ndef add_asset(purchase_id):\n return redirect(url_for('asset.add', id=-1, qr=-1, purchase_id=purchase_id))\n","repo_name":"manuelborowski/ict-inventory","sub_path":"app/invoice/views.py","file_name":"views.py","file_ext":"py","file_size_in_byte":8054,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"48"} +{"seq_id":"69998575185","text":"#! python3\n# deleteUnneededFiles.py - deletes unneeded files.\n\nimport shutil\nimport os\nfrom pathlib import Path\n\n\n\ndef deleteUnneededFiles( \n folder,\n maxAllowableSize,\n Verbose = True):\n\n if (Verbose):\n print(\"Verbose: Folder is => \" + folder)\n print(\"Verbose: maxAllowableSize is => \" + str(maxAllowableSize))\n\n for foldername, subfolders, filenames in os.walk(folder):\n # print(f'Adding files in {foldername}...')\n for filename in filenames:\n fullFileName = Path(foldername, filename)\n fileSize = os.path.getsize(fullFileName)\n if (fileSize > maxAllowableSize):\n print(f'Whatif: File is {fileSize} bytes, deleting file -> {fullFileName}')\n # this is commented out for obvious reasons...\n # os.remove(fullFileName)\n else:\n if (Verbose):\n print(f'Verbose: File is under {maxAllowableSize} bytes, skipping file -> {fullFileName}')\n\n print('Done.')\n\n# Main program starts here\nmaxAllowableSize = 20\ndeleteUnneededFiles('.\\\\delicious', maxAllowableSize)\n","repo_name":"ashdar/automate-boringstuff","sub_path":"Chapter-010/deleteUnneededFiles.py","file_name":"deleteUnneededFiles.py","file_ext":"py","file_size_in_byte":1157,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"48"} +{"seq_id":"19109758555","text":"# Week 2 - Exercise 15-2\n# YC - Jul 23, 2019\nimport sqlite3\nfrom urllib.request import Request, urlopen\n\nconn = sqlite3.connect('emaildb.sqlite')\ncur = conn.cursor()\n\ncur.execute('DROP TABLE IF EXISTS Counts')\n\ncur.execute('''CREATE TABLE Counts (org TEXT, count INTEGER)''')\n\n# address = 'https://www.py4e.com/code3/mbox.txt'\n# req = Request(address, headers={'User-Agent': 'Mozilla/5.0'})\n# fh = urlopen(req).read()\n\nfname = 'mbox.txt'\nfh = open(fname)\nfor line in fh:\n\tif not line.startswith('From: '): continue\n\tpieces = line.split()\n\t#email = pieces[1]\n\torgpieces = pieces[1].split('@')\n\torg = orgpieces[1]\n\t#print(org)\n\tcur.execute('SELECT count FROM Counts WHERE org = ?', (org,))\n\trow = cur.fetchone()\n\tif row is None:\n\t\tcur.execute('''INSERT INTO Counts (org, count) VALUES (?, 1)''', (org,))\n\telse:\n\t\tcur.execute('UPDATE Counts SET count = count + 1 WHERE org = ?',(org,))\n\nsqlstr = 'SELECT org, count FROM Counts ORDER BY count DESC LIMIT 10'\n\nfor row in cur.execute(sqlstr):\n\tprint(str(row[0],), row[1])\n\nconn.commit()\ncur.close()\n\n\n","repo_name":"shell845/PY4E","sub_path":"exercise15-2.py","file_name":"exercise15-2.py","file_ext":"py","file_size_in_byte":1045,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"48"} +{"seq_id":"73160273425","text":"from __future__ import absolute_import\nfrom __future__ import division\nfrom __future__ import print_function\n\nimport os \nimport numpy as np \nimport tensorflow as tf \n\ndef _dream_process(image):\n\n batched_features = {\n 'images': image\n }\n return batched_features\n\ndef inputs(split, depth, max_epochs, n_repeats, cropped_size,\n seed=123, total_batch_size=1):\n \"\"\"Construct noise inputs for dream experiment.\n\n Args:\n split: 'noise' split to read from dataset;\n depth: number of channels;\n max_epochs: maximum epochs to go through the model;\n n_repeats: number of computed gradients / number of the same input to repeat;\n cropped_size: image size after cropping;\n seed: seed to produce pseudo randomness that we can replicate each time;\n total_batch_size: total number of images per batch.\n Returns: \n batched_features: a dictionary of the input data features.\n \"\"\"\n\n \"\"\"Dataset specs\"\"\"\n specs = {\n 'split': split,\n 'max_epochs': max_epochs,\n 'steps_per_epoch': n_repeats,\n 'batch_size': total_batch_size,\n 'image_size': cropped_size,\n 'depth': depth,\n 'num_classes': 10\n }\n\n \"\"\"Set random seed\"\"\"\n np.random.seed(seed)\n\n \"\"\"Initialize noise images\"\"\"\n noise_img_list = []\n for _ in range(max_epochs):\n one_noise_img = np.random.uniform(size=(\n specs['batch_size'],\n specs['depth'], specs['image_size'], specs['image_size']))*128 + 127.0\n \"\"\"Convert into 0. ~ 1. \"\"\"\n one_noise_img = one_noise_img * (1. / 255.)\n for _ in range(10*n_repeats):\n noise_img_list.append(one_noise_img)\n \"\"\"Transform into np array\"\"\"\n noise_img_matr = np.concatenate(noise_img_list, axis=0)\n\n \"\"\"Process dataset object\"\"\"\n # extract single instance \n dataset = tf.data.Dataset.from_tensor_slices((noise_img_matr))\n # create batched image dataset\n batched_dataset = dataset.batch(specs['batch_size'])\n # convert into feature\n batched_dataset = batched_dataset.map(_dream_process)\n # prefetch 1\n batched_dataset = batched_dataset.prefetch(1)\n\n return batched_dataset, specs\n","repo_name":"HAXRD/Capsule-Specific-Attacks","sub_path":"input_data/noise/noise_dream_input.py","file_name":"noise_dream_input.py","file_ext":"py","file_size_in_byte":2215,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"48"} +{"seq_id":"20754039741","text":"import tkinter as tk\nimport Recipes as rec\n\nj = 1\n\n\nclass Application(tk.Tk):\n def __init__(self):\n tk.Tk.__init__(self)\n self._frame = None\n self.switch_frame(startPage, None)\n self.geometry('1000x1000')\n\n # Deletes current frame and switches to new frame\n # If New frame takes input, make frame with that input\n def switch_frame(self, frame_class, input):\n new_frame = \"\"\n if input is None:\n new_frame = frame_class(self)\n else:\n new_frame = frame_class(self, input)\n if self._frame is not None:\n self._frame.destroy()\n self._frame = new_frame\n self._frame.pack()\n\n\n# Start Page links to all other pages\nclass startPage(tk.Frame):\n def __init__(self, master):\n tk.Frame.__init__(self, master)\n self.pack()\n tk.Label(self, text=\"Welcome to the Restaurant Bot\").grid(row=0, column=1)\n # Buttons for each different category\n recipes = tk.Button(self, height=2, width=12, command=lambda: master.switch_frame(allRecipes, None),\n text=\"All Recipes\", padx=20)\n recipes.grid(row=1, column=1)\n stockBtn = tk.Button(self, height=2, width=12, command=lambda: master.switch_frame(stock, None), text=\"Stock\",\n padx=20)\n stockBtn.grid(row=1, column=0)\n addBtn = tk.Button(self, height=2, width=12, command=lambda: master.switch_frame(addRecipeFrame, None),\n text=\"Add a Recipe\", padx=20)\n addBtn.grid(row=1, column=2)\n tk.Label(self, text=\"Recipes with\").grid(row=2, column=1)\n i = 0\n # Make buttons to go to recipes with each individual ingredients\n stocKJSON = rec.importJSON(\"Stock.txt\")\n col = 0\n row = 3\n for x in stocKJSON:\n z = tk.Button(self, height=2, width=12, command=lambda y=x: master.switch_frame(ingredientSpecific, y),\n text=x)\n z.grid(row=int(row), column=col)\n col = col + 1\n if col >= 3:\n row = row + 1\n col = 0\n\n\n# Displays all stock. Have button to edit stock for admins\nclass stock(tk.Frame):\n def __init__(self, master):\n super().__init__(master)\n self.master = master\n self.pack()\n tk.Label(self, text=\"Stock Management\").grid(row=0, column=1)\n self.button = tk.Button(self, height=2, width=12, command=lambda: master.switch_frame(startPage, None),\n text=\"Home\")\n self.button.grid(row=10, column=0)\n self.inp = rec.importJSON(\"Stock.txt\")\n y = 1\n # Make all the entrys\n self.entry = []\n for x in self.inp:\n val = tk.StringVar(self, str(self.inp[x][\"Quantity\"]))\n tk.Label(self, height=2, width=12, text=x).grid(row=y)\n self.entry.append(tk.Entry(self, textvariable=val))\n self.entry[y - 1].grid(row=y, column=1)\n y = y + 1\n tk.Button(self, height=2, width=12, command=self.updateValues, text=\"Save\").grid(row=10, column=2)\n\n def updateValues(self):\n r = 0\n for x in self.inp:\n self.inp[x][\"Quantity\"] = int(self.entry[r].get())\n r = r + 1\n print(self.inp)\n rec.updateFile(\"Stock.txt\", self.inp)\n rec.makeMenu(\"Stock.txt\", \"Recipes.txt\", \"Menu.txt\")\n\n\nclass addRecipeFrame(tk.Frame):\n def __init__(self, master):\n super().__init__(master)\n self.master = master\n self.pack()\n # Title\n tk.Label(self, text=\"Add Recipe\").grid(row=0, column=1)\n nameOfItem = tk.Entry(self)\n nameOfItem.grid(row=1, column=1)\n tk.Label(self, text=\"Item Name:\").grid(row=1, column=0)\n # Home Button\n self.button = tk.Button(self, height=2, width=12, command=lambda: master.switch_frame(startPage, None),\n text=\"Home\")\n self.button.grid(row=10, column=1)\n self.ingredientsOnScreen = 4\n tk.Button(self, text=\"Save and Quit\", command=lambda: saveAndQuit()).grid(row=10, column=2)\n testOption = rec.importJSON(\"Stock.txt\")\n # Make option menu for number of ingredient\n numOfIngredients = []\n optionMenuForEachIngredient = []\n for x in testOption:\n numOfIngredients.append(len(numOfIngredients) + 1)\n ingred = tk.StringVar(app)\n ingred.set(numOfIngredients[3])\n tk.Label(self, text=\"Number of Ingredients:\").grid(row=2, column=0)\n tk.OptionMenu(self, ingred, *numOfIngredients).grid(row=2, column=1)\n # Auto update on edits to number of ingredients\n ingred.trace_add('write', lambda *args: changeNumOfIngredients(ingred.get()))\n row = 3\n stockList = []\n for x in testOption:\n stockList.append(x)\n var = []\n i = 0\n inputs = []\n # Option menus for each ingredients\n for x in testOption:\n var.append(tk.StringVar(app))\n var[i].set(stockList[0])\n optionMenuForEachIngredient.append(tk.OptionMenu(self, var[i], *stockList))\n optionMenuForEachIngredient[i].grid(row=row, column=0)\n inputs.append(tk.Entry(self))\n inputs[i].grid(row=row, column=1)\n\n row = row + 1\n var[i].trace_add('write', lambda *args, z=i: print(z))\n i = i + 1\n\n # Changes the number of option menus on screen\n def changeNumOfIngredients(z):\n num = int(ingred.get())\n while self.ingredientsOnScreen > num:\n optionMenuForEachIngredient[self.ingredientsOnScreen - 1].grid_forget()\n inputs[self.ingredientsOnScreen - 1].grid_forget()\n self.ingredientsOnScreen = self.ingredientsOnScreen - 1\n while self.ingredientsOnScreen < num:\n optionMenuForEachIngredient[self.ingredientsOnScreen].grid(row=self.ingredientsOnScreen + 3)\n inputs[self.ingredientsOnScreen].grid(row=self.ingredientsOnScreen + 3, column=1)\n self.ingredientsOnScreen = self.ingredientsOnScreen + 1\n\n def saveAndQuit():\n finalList = []\n for z in range(self.ingredientsOnScreen):\n\n a_dict = {}\n if inputs[z].get() == '':\n print(\"Error\")\n continue\n if not inputs[z].get().isdigit():\n print(inputs[z].get() + \" is not a int\")\n continue\n intVal = int(inputs[z].get())\n a_dict[var[z].get()] = intVal\n finalList.append(a_dict)\n if len(finalList) is 0:\n print(\"Error No item Added\")\n else:\n addRecipeFunction(\"Recipes.txt\", nameOfItem.get(), finalList)\n master.switch_frame(startPage, None)\n\n\n# Shows recipes with specified ingredients\nclass ingredientSpecific(tk.Frame):\n def __init__(self, master, ingredient):\n super().__init__(master)\n self.master = master\n self.pack()\n self.ingredient = ingredient\n self.create_widgets(master, ingredient)\n self.button = tk.Button(self, height=2, width=12, command=lambda: master.switch_frame(startPage, None),\n text=\"Home\")\n self.button.grid(row=10, column=2)\n\n def create_widgets(self, master, ingredient):\n global j\n menu = rec.importJSON(\"Menu.txt\")\n tk.Label(self, text=\"Recipes with: \" + self.ingredient).grid(row=0, column=2)\n row = 1\n col = 0\n order = []\n for x in menu:\n for b in x.get(\"Items\"):\n\n if b.get(ingredient) is not None:\n btn = tk.Button(self, height=2, width=12, command=lambda y=x.get(\"Name\"): orderAndReset(\"Menu.txt\",\n \"Stock.txt\",\n y,\n \"Recipes.txt\"),\n text=x.get(\"Name\"))\n btn.grid(row=row, column=col, padx=10, pady=10)\n col = col + 1\n if col > 5:\n row = row + 1\n col = 0\n\n\nclass allRecipes(tk.Frame):\n def __init__(self, master):\n super().__init__(master)\n self.master = master\n self.pack()\n self.create_widgets(master)\n\n def create_widgets(self, master):\n global j\n menu = rec.importJSON(\"Menu.txt\")\n tk.Label(self, text=\"All Recipes\").grid(row=0, column=2)\n i = 0\n col = 0\n order = []\n for x in menu:\n order.append(\"\")\n order[i] = tk.Button(self, height=2, width=12,\n command=lambda y=x.get(\"Name\"): orderAndReset(\"Menu.txt\", \"Stock.txt\", y,\n \"Recipes.txt\"),\n text=x.get(\"Name\"))\n order[i].grid(row=j, column=col, padx=10, pady=10)\n i = i + 1\n col = col + 1\n if col > 5:\n j = j + 1\n col = 0\n button = tk.Button(self, height=2, width=12, command=lambda: master.switch_frame(startPage, None), text=\"Home\")\n button.grid(row=j + 1, column=2)\n\n\n##Takes recipe\ndef orderAndReset(fmenu, stock, item, recipes):\n rec.order(fmenu, stock, item, recipes)\n global j\n j = 1\n app.switch_frame(startPage, None)\n\n\ndef addRecipeFunction(fileName, itemName, ingredients):\n test = rec.importJSON(fileName).get(\"Recipes\")\n test.append({\"Name\": itemName, \"Items\": ingredients})\n rec.updateFile(fileName, {\"Recipes\": test})\n rec.makeMenu(\"Stock.txt\", \"Recipes.txt\", \"Menu.txt\")\n\n\napp = Application()\n\n# addRecipe(\"Recipes.txt\", \"Bmac Burger\", [{\"Lettuce\":1}, {\"Buns\":3}, {\"Patty\":3}])\n\napp.mainloop()\n","repo_name":"bmac400/RestrauntBot","sub_path":"Interface.py","file_name":"Interface.py","file_ext":"py","file_size_in_byte":10169,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"48"} +{"seq_id":"5104612494","text":"from spotify_connect_scrobbler import credentials\n\n\ndef test_save(tmpdir):\n creds_file_path = tmpdir.join(\"creds.json\")\n\n lastfm = credentials.LastfmCredentials(\"some_key\")\n spotify = credentials.SpotifyCredentials(\n \"some_access\",\n \"Bearer\",\n \"refreshing\",\n \"scoping\")\n creds = credentials.Credentials(lastfm, spotify)\n creds.save(creds_file_path)\n\n data = creds_file_path.read()\n assert data == ('{\"lastfm\": {\"session_key\": \"some_key\"}, '\n '\"spotify\": {\"access_token\": \"some_access\", '\n '\"token_type\": \"Bearer\", \"refresh_token\": \"refreshing\", '\n '\"scope\": \"scoping\"}}')\n\n\ndef test_load():\n creds = credentials.load('tests/fixtures/credentials.json')\n\n assert creds.lastfm.session_key == \"other_key\"\n assert creds.spotify.access_token == \"other_access\"\n assert creds.spotify.token_type == \"Bearer\"\n assert creds.spotify.refresh_token == \"more refreshing\"\n assert creds.spotify.scope == \"scoped\"\n","repo_name":"jeschkies/spotify-connect-scrobbler","sub_path":"tests/test_credentials.py","file_name":"test_credentials.py","file_ext":"py","file_size_in_byte":1036,"program_lang":"python","lang":"en","doc_type":"code","stars":6,"dataset":"github-code","pt":"48"} +{"seq_id":"41943506131","text":"# -*- coding:utf-8 -*-\nimport functools\nimport re\nimport time\nimport logging\n\nfrom prettytable import PrettyTable,ALL\nfrom method import log,res_table,check_db,get_sid,get_rac_state\nfrom connection.ora_conn import ora_all,ora_no_fetch,ora_func\nfrom connection.ssh_input import ssh_input_noprint\n\n# logging\nlogging.basicConfig(format=\"%(levelname)s\\t%(asctime)s\\t%(message)s\",filename=\"ora_expdp.log\")\nlogger = logging.getLogger(__name__)\nlogger.setLevel(logging.DEBUG)\n\n\n\n\n# input the prallel if you want\n@log\ndef input_parallel(os_args,degree):\n if degree == 0:\n degree = 1\n else:\n pass\n cpu_cnt = int(ssh_input_noprint(os_args,'''cat /proc/cpuinfo | grep \"processor\" |wc -l''')[0].replace('\\n',''))\n p_tmp = cpu_cnt // 2 + cpu_cnt % 2 \n print(f\"\\nINFO:导出环境的逻辑CPU数为{cpu_cnt},推荐并行度应不超过{p_tmp},用户选择并行度为{degree}\")\n if degree > p_tmp:\n print(\"WARRNING:请不要选择大于1/2倍逻辑CPU数的并行度!\")\n return 'no'\n return degree\n\n# get the schemas's DEFAULT_TABLESPACE and DEFAULT_TEMP\n@log\ndef default_info(sync_obj,db_args,mode):\n sync_obj = sync_obj.upper()\n if sync_obj == \"FULL_EXPDP\":\n select_deflt_info_sql = '''select distinct b.username,a.tablespace_name,b.TEMPORARY_TABLESPACE,b.profile from dba_tablespaces a, dba_users b,dba_segments c \\\n where a.tablespace_name not in ('SYSTEM','SYSAUX') and a.contents = 'PERMANENT' \\\n and a.tablespace_name=c.tablespace_name and b.username=c.owner \\\n group by b.username,a.tablespace_name,b.TEMPORARY_TABLESPACE,b.profile\n'''\n else:\n schemas = \"','\".join(list(set([i.split('.')[0] for i in sync_obj.split(',')])))\n select_deflt_info_sql = f'''select distinct b.username,a.tablespace_name,b.TEMPORARY_TABLESPACE,b.profile from dba_tablespaces a, dba_users b,dba_segments c \\\n where a.tablespace_name not in ('SYSTEM','SYSAUX') and a.contents = 'PERMANENT' \\\n and a.tablespace_name=c.tablespace_name and b.username=c.owner and username in ('{schemas}')\\\n group by b.username,a.tablespace_name,b.TEMPORARY_TABLESPACE,b.profile\n'''\n deflt_info,title = ora_all(db_args,select_deflt_info_sql,mode)\n if deflt_info !=[]:\n info_table = res_table(deflt_info,title)\n print(\"\\nINFO:导出对象用户的策略、默认表空间及默认临时表空间信息如下:\")\n print(info_table)\n else:\n pass\n return deflt_info\n\n# generate some sql for init tbs\n@log \ndef get_init_tbs_sql(db_args,deflt_info,mode,dbf_path):\n tbs_list = list(set([i[1] for i in deflt_info]))\n temp_tbs_list = list(set([i[2] for i in deflt_info]))\n\n init_tbs_sql_list = []\n init_temp_sql_list = []\n dbf_dir = dbf_path\n for tbs_name in tbs_list:\n select_dbf_cnt_sql = f\"SELECT count(*) from dba_data_files where tablespace_name='{tbs_name}'\"\n datafile_cnt,_ = ora_all(db_args,select_dbf_cnt_sql,mode)\n create_tbs_sql = f\"create tablespace {tbs_name} datafile '{dbf_dir}/{tbs_name}01.dbf' size 10m autoextend on;\".replace('//','/')\n init_tbs_sql_list.append(create_tbs_sql)\n for dbf_id in range(2,datafile_cnt[0][0]+1):\n add_db_file_sql = f\"alter tablespace {tbs_name} add datafile '{dbf_dir}/{tbs_name}{dbf_id}.dbf' size 10m autoextend on;\".replace('//','/')\n init_tbs_sql_list.append(add_db_file_sql)\n for temp_tbs_name in temp_tbs_list:\n create_temp_tbs_sql = f\"create temporary tablespace {tbs_name} tempfile '{dbf_dir}/{temp_tbs_name}01.dbf' size 10m autoextend on;\".replace('//','/')\n init_temp_sql_list.append(create_temp_tbs_sql)\n print(\"\\nINFO:根据导出数据库环境生成的数据表空间初始化语句如下:\\n###\")\n print('\\n'.join(init_tbs_sql_list))\n print(\"###\")\n print(\"\\nINFO:根据导出数据库环境生成的默认临时表空间初始化语句如下:\\n###\")\n print('\\n'.join(init_temp_sql_list))\n print(\"###\")\n print(\"\\nINFO:请根据实际情况在目标环境运行初始化表空间的语句.\")\n return init_tbs_sql_list,init_temp_sql_list\n\n\n# estimate the size of this expdp\n@log\ndef estimate_size_expdp(sync_obj,os_args,sid,db_user,db_pwd):\n print(\"\\nINFO:现在开始预估导出文件大小,可能会花费些许时间.\")\n if '.' not in sync_obj and sync_obj != 'FULL_EXPDP':\n estimate_size_cmd = f'''source ~/.bash_profile\\nexport ORACLE_SID={sid}\\nexpdp {db_user}/{db_pwd} schemas={sync_obj} ESTIMATE_ONLY=y'''\n elif sync_obj == 'FULL_EXPDP':\n estimate_size_cmd = f'''source ~/.bash_profile\\nexport ORACLE_SID={sid}\\nexpdp {db_user}/{db_pwd} full=y ESTIMATE_ONLY=y'''\n else:\n estimate_size_cmd = f'''source ~/.bash_profile\\nexport ORACLE_SID={sid}\\nexpdp {db_user}/{db_pwd} tables={sync_obj} ESTIMATE_ONLY=y'''\n estimate_size_res = ssh_input_noprint(os_args,estimate_size_cmd)\n estimate_size_tmp = [i for i in estimate_size_res if 'Total estimation using BLOCKS method:' in i][0]\n estimate_size = estimate_size_tmp.split(':')[-1].replace('\\n','')\n return estimate_size\n\n\n# check the profile for users and get the ddl sql\n@log\ndef check_profile(db_args,mode,profile_list):\n profile_list = [i for i in profile_list if i !='DEFAULT' and i!='MONITORING_PROFILE']\n\n if profile_list == []:\n print(\"\\nINFO:目标数据库无需添加新的用户profile策略.\")\n return profile_list\n else:\n func_name = 'PROFILE'\n ddl_list = []\n for profile in profile_list:\n profile_ddl_res = ora_func(db_args,func_name,profile,mode)\n ddl_list.append(profile_ddl_res)\n print(\"\\nINFO:根据导出数据库环境生成的用户profile策略ddl语句如下:\\n###\")\n print('\\n'.join(ddl_list))\n return profile_ddl_res\n\n\n# precheck before expdp and generate the expdp and cmd\n@log\ndef check_expdp(mode,sync_obj,sys_user,sys_passwd,db_args,ssh_port,degree,path,dbf_path):\n sync_obj = sync_obj.upper()\n obj_list = tuple(sync_obj.split(','))\n\n ip,db_user,db_port,db_pwd,db_sid = db_args\n os_args = [ip,ssh_port,sys_user,sys_passwd]\n sid = get_sid(db_args,mode)\n \n mytime=time.strftime(\"%Y%m%d%H%M\", time.localtime())\n deflt_info = default_info(sync_obj,db_args,mode)\n if deflt_info ==[]:\n print(\"\\nERROR:数据库用户不存在,请检查后重新输入!\")\n return \"none user\"\n\n # schemas expdp\n if '.' not in sync_obj and sync_obj != 'FULL_EXPDP':\n check_obj_sql = f\"select SEGMENT_NAME from dba_segments where owner in {obj_list} \"\n check_obj_sql = check_obj_sql.replace(',)',')')\n check_obj,_ = ora_all(db_args,check_obj_sql,mode)\n \n if check_obj== []:\n print(f\"WARRING:用户 {sync_obj} 不存在!请检查你要导出的对象是否正确.\")\n return 1\n estimate_size = estimate_size_expdp(sync_obj,os_args,sid,db_user,db_pwd)\n print(f\"\\nINFO:导出对象预估大小:{estimate_size}.\")\n parallel = input_parallel(os_args,degree)\n if parallel == 'no':\n return 'no'\n elif parallel == 1:\n expdp_cmd = f'''source ~/.bash_profile\\nexport ORACLE_SID={sid}\\nexpdp {db_user}/{db_pwd} schemas={sync_obj} directory=mc_dump_dir dumpfile=schemas_{mytime}.dmp logfile=schemas_{mytime}.log'''\n impdp_cmd = f'''source ~/.bash_profile\\nexport ORACLE_SID=\\nimpdp \"'\" / as sysdba \"'\" schemas={sync_obj} directory=mc_dump_dir dumpfile=schemas_{mytime}.dmp logfile=impdp_schemas_{mytime}.log'''\n else:\n rac = get_rac_state(db_args,mode)\n if rac == 'TRUE':\n expdp_cmd = f'''source ~/.bash_profile\\nexport ORACLE_SID={sid}\\nexpdp {db_user}/{db_pwd} schemas={sync_obj} directory=mc_dump_dir parallel={parallel} cluster=n dumpfile=schemas_{mytime}_%U.dmp logfile=schemas_{mytime}.log'''\n impdp_cmd = f'''source ~/.bash_profile\\nexport ORACLE_SID=\\nimpdp \"'\" / as sysdba \"'\" schemas={sync_obj} directory=mc_dump_dir parallel={parallel} cluster=n dumpfile=schemas_{mytime}_%U.dmp logfile=impdp_schemas_{mytime}.log'''\n\n else:\n expdp_cmd = f'''source ~/.bash_profile\\nexport ORACLE_SID={sid}\\nexpdp {db_user}/{db_pwd} schemas={sync_obj} directory=mc_dump_dir parallel={parallel} dumpfile=schemas_{mytime}_%U.dmp logfile=schemas_{mytime}.log'''\n impdp_cmd = f'''source ~/.bash_profile\\nexport ORACLE_SID=\\nimpdp \"'\" / as sysdba \"'\" schemas={sync_obj} directory=mc_dump_dir parallel={parallel} dumpfile=schemas_{mytime}_%U.dmp logfile=impdp_schemas_{mytime}.log'''\n # full db expdp\n elif sync_obj == 'FULL_EXPDP':\n estimate_size = estimate_size_expdp(sync_obj,os_args,sid,db_user,db_pwd)\n print(f\"\\nINFO:导出对象预估大小:{estimate_size}.\")\n parallel = input_parallel(os_args,degree)\n if parallel == 'no':\n return 'no'\n elif parallel == 1:\n expdp_cmd = f'''source ~/.bash_profile\\nexport ORACLE_SID={sid}\\nexpdp {db_user}/{db_pwd} directory=mc_dump_dir dumpfile=full_{mytime}.dmp logfile=full_{mytime}.log full=y'''\n impdp_cmd = f'''source ~/.bash_profile\\nexport ORACLE_SID=\\nimpdp \"'\" / as sysdba \"'\" directory=mc_dump_dir dumpfile=full_{mytime}.dmp logfile=impdp_full_{mytime}.log full=y'''\n \n else:\n rac = get_rac_state(db_args,mode)\n if rac == 'TRUE':\n expdp_cmd = f'''source ~/.bash_profile\\nexport ORACLE_SID={sid}\\nexpdp {db_user}/{db_pwd} directory=mc_dump_dir cluster=n parallel={parallel} dumpfile=full_{mytime}_%U.dmp logfile=full_{mytime}.log full=y'''\n impdp_cmd = f'''source ~/.bash_profile\\nexport ORACLE_SID=\\nimpdp \"'\" / as sysdba \"'\" directory=mc_dump_dir cluster=n parallel={parallel} dumpfile=full_{mytime}_%U.dmp logfile=impdp_full_{mytime}.log full=y'''\n\n else:\n expdp_cmd = f'''source ~/.bash_profile\\nexport ORACLE_SID={sid}\\nexpdp {db_user}/{db_pwd} directory=mc_dump_dir parallel={parallel} dumpfile=full_{mytime}_%U.dmp logfile=full_{mytime}.log full=y'''\n impdp_cmd = f'''source ~/.bash_profile\\nexport ORACLE_SID=\\nimpdp \"'\" / as sysdba \"'\" directory=mc_dump_dir parallel={parallel} dumpfile=full_{mytime}_%U.dmp logfile=impdp_full_{mytime}.log full=y'''\n \n # tables expdp\n else:\n \n for obj in obj_list:\n owner,table = obj.split('.')\n check_obj_sql = f\"select segment_name from dba_segments where owner = '{owner}' and segment_name = '{table}'\" \n check_obj,_ = ora_all(db_args,check_obj_sql,mode)\n if check_obj==[]:\n print(f\"WARRING:表 {owner}.{table} 不存在!请检查你要导出的对象是否正确.\")\n return 1\n estimate_size = estimate_size_expdp(sync_obj,os_args,sid,db_user,db_pwd)\n print(f\"\\nINFO:导出对象预估大小:{estimate_size}.\")\n parallel = input_parallel(os_args,degree) \n if parallel == 'no':\n return 'no'\n elif parallel == 1:\n expdp_cmd = f'''source ~/.bash_profile\\nexport ORACLE_SID={sid}\\nexpdp {db_user}/{db_pwd} tables={sync_obj} directory=mc_dump_dir dumpfile=tables_{mytime}.dmp logfile=tables_{mytime}.log '''\n impdp_cmd = f'''source ~/.bash_profile\\nexport ORACLE_SID=\\nimpdp \"'\" / as sysdba \"'\" tables={sync_obj} directory=mc_dump_dir dumpfile=tables_{mytime}.dmp logfile=impdp_tables_{mytime}.log '''\n \n else:\n rac = get_rac_state(db_args,mode)\n if rac == 'TRUE':\n expdp_cmd = f'''source ~/.bash_profile\\nexport ORACLE_SID={sid}\\nexpdp {db_user}/{db_pwd} tables={sync_obj} directory=mc_dump_dir cluster=n parallel={parallel } dumpfile=tables_{mytime}_%U.dmp logfile=tables_{mytime}.log '''\n impdp_cmd = f'''source ~/.bash_profile\\nexport ORACLE_SID=\\nimpdp \"'\" / as sysdba \"'\" tables={sync_obj} directory=mc_dump_dir cluster=n parallel={parallel } dumpfile=tables_{mytime}_%U.dmp logfile=impdp_tables_{mytime}.log '''\n \n else:\n expdp_cmd = f'''source ~/.bash_profile\\nexport ORACLE_SID={sid}\\nexpdp {db_user}/{db_pwd} tables={sync_obj} directory=mc_dump_dir parallel={parallel } dumpfile=tables_{mytime}_%U.dmp logfile=tables_{mytime}.log '''\n impdp_cmd = f'''source ~/.bash_profile\\nexport ORACLE_SID=\\nimpdp \"'\" / as sysdba \"'\" tables={sync_obj} directory=mc_dump_dir parallel={parallel } dumpfile=tables_{mytime}_%U.dmp logfile=impdp_tables_{mytime}.log '''\n\n \n \n print(f\"\\nINFO:导出命令为:\\n###\\n{expdp_cmd}\\n###\")\n \n return expdp_cmd,impdp_cmd,deflt_info\n\n\n\n\n\n\n\n","repo_name":"zhangqzqz/oracle_ops_deploy","sub_path":"ora_expdp/ora_expdp_method.py","file_name":"ora_expdp_method.py","file_ext":"py","file_size_in_byte":12749,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"48"} +{"seq_id":"36153558200","text":"\"\"\"\nProvides a ``Motor`` subclass for Smaract positioners. All numbers in\nmicrometers.\n\nControls these via a MAX IV Tango device,\nhttps://gitlab.maxiv.lu.se/kits-maxiv/dev-maxiv-mcs\n\"\"\"\n\ntry:\n import tango\nexcept ImportError:\n pass\nfrom . import Motor\nimport time\n\n\nclass SmaractLinearMotor(Motor):\n \"\"\"\n Single Smaract motor axis.\n \"\"\"\n def __init__(self, device, axis, velocity=None, frequency=None, **kwargs):\n \"\"\"\n :param device: Path to the MCS Tango device\n :type device: str\n :param axis: Axis number on the controller\n :type axis: int\n :param velocity: Initialize velocity, defaults to None\n :type velocity: float\n :param ``**kwargs``: Passed on to the ``Motor`` base class\n \"\"\"\n super().__init__(**kwargs)\n self.proxy = tango.DeviceProxy(device)\n self.proxy.set_source(tango.DevSource.DEV)\n self.axis = int(axis)\n if velocity is not None:\n attr = 'velocity_%d' % self.axis\n self.proxy.write_attribute(attr, velocity * 1e3)\n if frequency is not None:\n self.frequency(frequency)\n\n @property\n def dial_position(self):\n attr = 'position_%d' % self.axis\n return self.proxy.read_attribute(attr).value * 1e-3\n\n @dial_position.setter\n def dial_position(self, pos):\n attr = 'position_%d' % self.axis\n self.proxy.write_attribute(attr, pos * 1e3)\n\n def busy(self):\n attr = 'state_%d' % self.axis\n return not (self.proxy.read_attribute(attr).value == tango.DevState.ON)\n\n def home(self):\n print('\\nhoming %s...' % self.name)\n self.proxy.arbitraryCommand(\"FRM%u,2,60000,1\" % self.axis)\n while self.busy():\n time.sleep(.1)\n print('homing done')\n \n def frequency(self, freq):\n # set the maximum closed loop frequency of the positioner\n self.proxy.arbitraryCommand(f\"SCLF{self.axis:d},{int(freq):d}\") \n\n def stop(self):\n self.proxy.stopAll() # safety first\n\n\nclass SmaractRotationMotor(SmaractLinearMotor):\n @property\n def dial_position(self):\n attr = 'angle_%d' % self.axis\n result = self.proxy.read_attribute(attr).value\n result = result.split(',')\n pos = int(result[0])\n rev = int(result[1])\n pos = pos * 1e-6 + rev * 360\n return pos\n\n @dial_position.setter\n def dial_position(self, pos):\n angle = int(1e6 * (pos % 360))\n rev = int(pos // 360)\n attr = 'angle_%d' % self.axis\n val = '%d,%d' % (angle, rev)\n self.proxy.write_attribute(attr, val)\n","repo_name":"maxiv-science/contrast","sub_path":"contrast/motors/SmaractMotor.py","file_name":"SmaractMotor.py","file_ext":"py","file_size_in_byte":2629,"program_lang":"python","lang":"en","doc_type":"code","stars":5,"dataset":"github-code","pt":"48"} +{"seq_id":"43059796949","text":"# -*- coding: utf-8 -*-\nfrom sklearn import datasets\nimport inquirer\nimport evaluateMetaheuristicas as evaluate\n\n\"\"\"# DataBase Selection\"\"\"\nquestions = [\n inquirer.List('base',\n message=\"Select DataBase:\",\n choices=['Digits', 'Wine', 'Breast Cancer'],\n ),\n]\nanswers = inquirer.prompt(questions)\n\ndef functionDigits():\n print(\"DataBase Digits Selected\")\n dataBase = datasets.load_digits()\n return dataBase\n\ndef functionWine():\n print(\"DataBase Wine Selected\")\n dataBase = datasets.load_wine()\n return dataBase\n\ndef functionBreast():\n print(\"DataBase Breast Cancer Selected\")\n dataBase = datasets.load_breast_cancer()\n return dataBase\n\ndef default():\n print(\"Select one Database:\")\n\nif __name__ == \"__main__\":\n switch = {\n \"Digits\": functionDigits,\n \"Wine\": functionWine,\n \"Breast Cancer\": functionBreast\n }\n\n case = switch.get(answers[\"base\"], default)\n dataBase = case()\n evaluate.evaluateMetaheuristicas(dataBase)\n","repo_name":"AndrePauloFM/Metaheuristics-Ensemble-Classifiers","sub_path":"main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":1023,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"48"} +{"seq_id":"20205936159","text":"\"\"\"\nfunctions for building interaction matrices and solving them\n\"\"\"\n\nimport numpy as np\nimport miepy\nfrom scipy.sparse.linalg import bicgstab\nfrom miepy.cpp.vsh_translation import vsh_translation_numpy as vsh_translation\n\ndef solve_linear_system(tmatrix, p_src, method):\n \"\"\"Solve the linear system p_inc = p_src - tmatrix*p_inc\n size\n Arguments:\n tmatrix[N,2,rmax,N,2,rmax] particle aggregate tmatrix\n p_src[N,2,rmax] source scattering coefficients\n method solver method ('exact', 'bicgstab')\n \"\"\"\n Nparticles = tmatrix.shape[0]\n rmax = p_src.shape[-1]\n size = Nparticles*2*rmax\n\n return miepy.cpp.interactions.solve_linear_system(tmatrix.reshape(size, size), p_src.reshape(-1), method=method).reshape([Nparticles,2,rmax])\n\ndef interactions_precomputation(positions, k, lmax):\n \"\"\"Get the relative r,theta,phi positions of the particles and precomputed zn function\n\n Arguments:\n positions[N,3] particles positions\n k medium wavenumber\n lmax maximum number of multipoles\n \n Returns:\n r[idx], theta[idx], phi[idx], zn[nmax,idx] (idx enumerates i,j and j > i)\n \"\"\"\n Nparticles = positions.shape[0]\n size = int(Nparticles*(Nparticles-1)/2)\n r_ji = np.zeros(size, dtype=float)\n theta_ji = np.zeros(size, dtype=float)\n phi_ji = np.zeros(size, dtype=float)\n\n idx = 0\n for i in range(Nparticles):\n for j in range(i+1, Nparticles):\n pi = positions[i]\n pj = positions[j]\n dji = pi - pj\n r_ji[idx] = np.linalg.norm(dji)\n theta_ji[idx] = np.arccos(dji[2]/r_ji[idx])\n phi_ji[idx] = np.arctan2(dji[1], dji[0])\n\n idx +=1\n\n nmax = 2*lmax + 1\n zn_values = np.zeros((nmax, size), dtype=complex)\n for n in range(nmax):\n zn_values[n] = miepy.vsh.special.spherical_hn(n, k*r_ji)\n\n return r_ji, theta_ji, phi_ji, zn_values\n\ndef sphere_aggregate_tmatrix(positions, mie, k):\n \"\"\"Obtain the particle-centered aggregate T-matrix for a cluster of spheres\n Returns T[N,2,rmax,N,2,rmax]\n \n Arguments:\n positions[N,3] particles positions\n mie[N,2,lmax] mie scattering coefficients\n k medium wavenumber\n \"\"\"\n Nparticles = positions.shape[0]\n lmax = mie.shape[-1]\n rmax = miepy.vsh.lmax_to_rmax(lmax)\n return miepy.cpp.interactions.sphere_aggregate_tmatrix(positions, mie.reshape([Nparticles,-1]), k).reshape([Nparticles,2,rmax,Nparticles,2,rmax])\n\n\ndef sphere_aggregate_tmatrix_periodic(positions, mie, k, symmetry, k_hat):\n \"\"\"Obtain the particle-centered aggregate T-matrix for a cluster of spheres with a given periodic symmetry\n Returns T[N,2,rmax,N,2,rmax]\n \n Arguments:\n positions[N,3] particles positions\n mie[N,2,lmax] mie scattering coefficients\n k medium wavenumber\n symmetry type of symmetry\n k_hat unit k-vector\n \"\"\"\n\n Nparticles = positions.shape[0]\n lmax = mie.shape[-1]\n rmax = miepy.vsh.lmax_to_rmax(lmax)\n # agg_tmatrix = np.zeros(shape=(Nparticles, 2, rmax, Nparticles, 2, rmax), dtype=complex)\n agg_tmatrix = sphere_aggregate_tmatrix(positions, mie, k)\n\n xpos, ypos, zpos = symmetry.generate(5000) \n cells = np.array([xpos,ypos,zpos]).T\n\n\n for i in range(Nparticles):\n for j in range(Nparticles):\n dr = positions[i] - (cells + positions[j])\n rad, theta, phi = miepy.coordinates.cart_to_sph(dr[:,0], dr[:,1], dr[:,2])\n for r,n,m in miepy.mode_indices(lmax):\n for s,v,u in miepy.mode_indices(lmax):\n phase_factor = np.exp(-1j*k*(k_hat[0]*xpos + k_hat[1]*ypos + k_hat[2]*zpos))\n A_transfer, B_transfer = vsh_translation(m, n, u, v, \n rad, theta, phi, k, miepy.vsh_mode.outgoing)\n for a in range(2):\n for b in range(2):\n val = (A_transfer, B_transfer)[(a+b)%2]*phase_factor\n agg_tmatrix[i,a,r,j,b,s] += np.sum(val)*mie[j,b,v-1]\n\n return agg_tmatrix\n\n#TODO this function is more general than above and can be used for both cases (change only the einsum)\ndef particle_aggregate_tmatrix(positions, tmatrix, k):\n \"\"\"Obtain the particle-centered aggregate T-matrix for a cluster of particles\n Returns T[N,2,rmax,N,2,rmax]\n \n Arguments:\n positions[N,3] particles positions\n tmatrix[N,2,rmax,2,rmax] single particle T-matrices\n k medium wavenumber\n \"\"\"\n\n Nparticles = positions.shape[0]\n rmax = tmatrix.shape[-1]\n lmax = miepy.vsh.rmax_to_lmax(rmax)\n\n return miepy.cpp.interactions.particle_aggregate_tmatrix(positions, tmatrix.reshape([Nparticles,-1]), k).reshape([Nparticles,2,rmax,Nparticles,2,rmax])\n\ndef reflection_matrix_nia(positions, mie, k, reflected, z):\n \"\"\"Obtain the particle-centered aggregate T-matrix for a cluster of spheres\n Returns T[N,2,rmax,N,2,rmax]\n \n Arguments:\n positions[N,3] particles positions\n mie[N,2,lmax] mie scattering coefficients\n k medium wavenumber\n z z coordinate of interface\n \"\"\"\n Nparticles = positions.shape[0]\n lmax = mie.shape[-1]\n rmax = miepy.vsh.lmax_to_rmax(lmax)\n R = miepy.cpp.interactions.reflection_matrix_nia(positions, mie.reshape([Nparticles,-1]), k, reflected, z).reshape([Nparticles,2,rmax,Nparticles,2,rmax])\n return R\n\n","repo_name":"johnaparker/miepy","sub_path":"miepy/interactions.py","file_name":"interactions.py","file_ext":"py","file_size_in_byte":5700,"program_lang":"python","lang":"en","doc_type":"code","stars":27,"dataset":"github-code","pt":"48"} +{"seq_id":"767638390","text":"\"\"\"PIL based font support for p5.\n\n:author: Abhik Pal\n:date: 2018-07\n\n\"\"\"\nimport contextlib\nimport functools\nimport textwrap\n\nimport PIL\nfrom PIL import Image\nfrom PIL import ImageDraw\nfrom PIL import ImageFont\n\n__all__ = ['create_font', 'load_font', 'text', 'text_font', 'render_font']\n\n_rendering = False\n_canvas = None\n_canvas_draw = None\n\n_font_family = ImageFont.load_default()\n\ndef _ensure_rendering(func):\n \"\"\"Ensure that rendering mode is enabled.\n \"\"\"\n @functools.wraps(func)\n def rfunc(*args, **kwargs):\n if not _rendering:\n fname = func.__name__\n err_msg = \"{} can only be called with rendering enabled\"\n raise ValueError(err_msg.format(fname))\n return func(*args, **kwargs)\n return rfunc\n\ndef create_font(name, size):\n \"\"\"Create the given font at the appropriate size.\n\n \"\"\"\n if name.endswith('ttf'):\n _font_family = ImageFont.truetype(name, size)\n elif name.endswith('pil'):\n _font_family = ImageFont.load(name)\n else:\n raise NotImplementedError(\"Font type not supported.\")\n\n return _font_family\n\ndef load_font(font_name):\n \"\"\"Loads the given font into a font object\n\n :rtype: PIL.ImageFont.\n\n \"\"\"\n return create_font(font_name, 10)\n\n@_ensure_rendering\ndef text(text_string, position, wrap_at=None):\n \"\"\"Draw the given text on the screen and save the image.\n\n :param text_string: text to display\n :type text_string: str\n\n :param position: position of the text on the screen\n :type position: tuple\n\n :param wrap_at: specifies the text wrapping column (defaults to\n None)\n :type wrap_at: int\n\n :returns: actual text that was drawn to the image (when wrapping\n is not set, this is just the unmodified text_string)\n :rtype: str\n\n \"\"\"\n if not (wrap_at is None):\n text_string = textwrap.fill(text_string, wrap_at)\n _canvas_draw.text(position, text_string, font=_font_family)\n return text_string\n\ndef text_font(font):\n \"\"\"Set current text font.\n\n :param font:\n :type font: PIL.ImageFont.ImageFont\n\n \"\"\"\n global _font_family\n _font_family = font\n\n@contextlib.contextmanager\ndef render_font(size=(640, 260), filename='pfont-test.png'):\n global _canvas\n global _canvas_draw\n global _rendering\n\n _canvas = Image.new('RGB', size, color=(51, 51, 51))\n _canvas_draw = ImageDraw.Draw(_canvas)\n _rendering = True\n\n yield\n\n _rendering = False\n _canvas.save(filename)\n","repo_name":"p5py/p5-ideas","sub_path":"pfont/pfont.py","file_name":"pfont.py","file_ext":"py","file_size_in_byte":2481,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"48"} +{"seq_id":"12110383784","text":"from PyQt5.QtWidgets import QApplication, QWidget, QLabel, QGridLayout\nfrom PyQt5.QtCore import Qt\nimport sys\n\nclass Example(QWidget):\n\tdef __init__(self):\n\t\tsuper().__init__()\n\t\tself.initUI()\n\n\tdef initUI(self):\n\n\t\tgrid = QGridLayout()\n\t\tself.setLayout(grid)\n\t\tx = 0\n\t\ty = 0\n\t\tself.text = f\"x={x}, y={y}\"\n\n\t\tself.label = QLabel(self.text ,self)\n\n\t\tself.setMouseTracking(True)\n\n\t\tself.setGeometry(300, 300, 400, 400)\n\t\tself.setWindowTitle(\"Event Object\")\n\t\tself.show()\n\t\t\n\tdef mouseMoveEvent(self, e):\n\t\tx = e.x()\n\t\ty = e.y()\n\t\ttext = f\"x={x}, y={y}\"\n\t\t# print(text)\n\t\tself.label.setText(text)\n\n\tdef keyPressEvent(self, e):\n\t\tif e.key() == Qt.Key_Escape:\n\t\t\tprint(\"got it!\")\n\t\t\tself.close()\n\ndef main():\n\tapp = QApplication(sys.argv)\n\tex = Example()\n\tsys.exit(app.exec_())\n\nif __name__=='__main__':\n\tmain()","repo_name":"relaxcn/learn-pyqt5","sub_path":"signal/event_object.py","file_name":"event_object.py","file_ext":"py","file_size_in_byte":806,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"48"} +{"seq_id":"71955254867","text":"# Part 1: What is the power consumption of the submarine? [ 1092896 ]\n\nwith open('3_data.txt', 'rt') as data:\n data_list = [line.strip() for line in data.readlines()]\n\ngamma_rate = ''\nepsilon_rate = ''\n\ndef binary_to_decimal(binary):\n decimal, i = 0, 0\n while (binary != 0):\n decimal = decimal + (binary % 10) * pow(2, i)\n binary //= 10\n i += 1\n return decimal\n\nfor c in range(len(data_list[0])):\n zeros = 0\n ones = 0\n for r in range(len(data_list)):\n if (data_list[r][c] == '0'):\n zeros += 1\n else:\n ones += 1\n if (zeros > ones):\n gamma_rate += '0'\n epsilon_rate += '1'\n else:\n gamma_rate += '1'\n epsilon_rate += '0'\n\nprint(binary_to_decimal(int(gamma_rate)) * binary_to_decimal(int(epsilon_rate)))","repo_name":"danielletrinh/adventofcode-2021","sub_path":"1-9/3/3a.py","file_name":"3a.py","file_ext":"py","file_size_in_byte":811,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"48"} +{"seq_id":"12802744207","text":"from fastai2.vision.all import *\n\nimport argparse\nfrom pathlib import Path\nfrom azure.cognitiveservices.search.imagesearch import ImageSearchClient as api\nfrom msrest.authentication import CognitiveServicesCredentials as auth\n\ndef search_images_bing(key, term, min_sz=128, numimages=100):\n client = api('https://api.cognitive.microsoft.com', auth(key))\n return L(client.images.search(query=term, count=numimages, min_height=min_sz, min_width=min_sz).value)\n\ndef stringToList(string):\n listRes = list(string.split(\",\"))\n return listRes\n\ndef download_dataset(toplevelclass,subclasses,key,numimages,suffix):\n path = Path(toplevelclass)\n \n if not path.exists():\n path.mkdir()\n for o in subclasses:\n dest = (path/o)\n dest.mkdir(exist_ok=True)\n results = search_images_bing(key, f'{o} {suffix}', numimages=numimages)\n download_images(dest, urls=results.attrgot('content_url'))\n \n fns = get_image_files(path)\n failed = verify_images(fns)\n failed.map(Path.unlink)\n print(f\"Number of items in search: {len(fns)}. Number of Failed downloads: {len(failed)}. Number of downloaded images: {len(fns)-len(failed)}\")\n\nif __name__ == '__main__':\n\tparser = argparse.ArgumentParser(description='Download bunch of images from Bing Image Search.')\n\tparser.add_argument('--classifier', help='Top level class of image objects you want', required=True)\n\tparser.add_argument('--subclasses', help='Comma separated list of subclasses of images to fetch', required=True)\n\tparser.add_argument('--key', help='Azure Bing Search API key', required=True)\n\tparser.add_argument('--numimages', help='Number of images per class to fetch', type=int, default=50)\n\tparser.add_argument('--nosuffix', help='Optional flag to not suffix subsclass with top level class in image search', nargs='?',type=bool, const=True, default=False)\n\targs = parser.parse_args()\n\tsuffix = '' if args.nosuffix else args.classifier\n\tdownload_dataset(toplevelclass=args.classifier, subclasses=stringToList(args.subclasses), key=args.key, numimages=args.numimages, suffix=suffix )\n","repo_name":"gopitk/image-dataset-builder","sub_path":"get_dataset_from_bing.py","file_name":"get_dataset_from_bing.py","file_ext":"py","file_size_in_byte":2110,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"48"} +{"seq_id":"15847256531","text":"import os\nimport time\n\nfrom Crypto.Hash import keccak\n\n\nclass FusionFactory:\n allele_num = 2\n\n noise_num = 128\n bit_per_noise = 2\n noise_value_range = 2 ** bit_per_noise\n\n exclusive_attrs_num = 3\n bit_per_exclusive_attrs = 4\n total_exclusive_attrs_bit_num = exclusive_attrs_num * bit_per_exclusive_attrs * allele_num\n\n bin_attrs_num = 7\n bit_per_bin_attrs = 1\n\n attrs_num = exclusive_attrs_num + bin_attrs_num\n\n bit_per_attrs_swap = 2\n attrs_per_swap = 2 ** bit_per_attrs_swap\n\n bit_per_noise_mutation_pos = 4\n noise_per_mutation = 2 ** bit_per_noise_mutation_pos\n\n bit_per_attrs_mutation_pos = 4\n attrs_per_mutation = 2 ** bit_per_attrs_mutation_pos\n\n def __init__(self):\n pass\n\n def mix_code(self, noise1, attrs1, noise2, attrs2, entropy=None):\n \"\"\"\n Given code of crypko 1 & 2, return a genetic combination - may have a random factor\n :param noise1: noise of matron\n :param attrs1: attrs of matron\n :param noise2: noise of sire\n :param attrs2: attrs of sire\n :param entropy: values used to ensure randomness\n :return: The code that are supposed to be passed down the derivative\n \"\"\"\n # TODO: use global function in function body and change view to pure\n\n # naively and boldly use block timestamp for randomness\n # however, this should works fine, since it is one of the strongest sources of entropy in solidity\n # and the entropy of the mapping from noise/attrs to the value of the crypko is too high\n # to be manipulated by miner.\n # potentially we can split the concatenation below to get more random numbers\n\n if entropy is None:\n entropy = (\n round(time.time()),\n\n # block.blockhash(block.number - 1), # TODO: remove `block.` for higher solidity version\n # block.coinbase,\n # block.difficulty,\n )\n\n rand = self.keccak( # TODO: add back `abi.encodePacked(` for solidity v0.5+\n noise1,\n attrs1,\n noise2,\n attrs2,\n *entropy\n )\n\n # 1. recombine noise\n # merge origins' noise into derivative's noise\n new_noise, rand = self.recombine_batch(\n noise1,\n noise2,\n self.noise_num,\n self.bit_per_noise,\n 0,\n rand\n )\n\n # since recombining the noise only used\n # 128 bits of the random number (at the end)\n # we can use the remaining 128 bits (at the front)\n # require(rand >> self.noiseNum == 0);\n\n # recombine origins' exclusive attributes, dominant and recessive, into derivative's\n # Note: since dominant gene is on the left, and here we work reversed\n # so we recombine the recessive attributes first, and then the dominant\n # use exclusiveAttrsNum * alleleNum = 6 bits\n exclusive_attrs, rand = self.recombine(\n attrs1,\n attrs2,\n self.exclusive_attrs_num * self.allele_num,\n self.bit_per_exclusive_attrs,\n self.get_mask(self.bit_per_exclusive_attrs, 0),\n rand\n )\n\n # merge origins' binary attrs into derivative's\n # use binAttrsNum * alleleNum = 14 bits\n bin_attrs, rand = self.recombine_batch(\n attrs1,\n attrs2,\n self.bin_attrs_num * self.allele_num,\n self.bit_per_bin_attrs,\n self.total_exclusive_attrs_bit_num,\n rand\n )\n\n # since bin and exclusive attributes are on different bits,\n # we add them up to get the complete attributes\n # require(binAttrs & exclusiveAttrs == 0);\n new_attrs = bin_attrs + exclusive_attrs\n\n # up until here, we right shift rand for 20 bits\n # remaining 108 bits for the rest\n\n # 2. swap alleles\n new_attrs, rand = self.swap_dominant_recessive(new_attrs, rand)\n\n # 3. mutate\n new_noise, rand = self.mutate_noise(new_noise, rand) # ~4000 gas\n new_attrs, rand = self.mutate_attrs(new_attrs, rand)\n\n return new_noise, new_attrs\n\n def swap_dominant_recessive(self, derivative_attrs, rand):\n start_index = 0\n for i in range(self.exclusive_attrs_num):\n if rand % self.attrs_per_swap == 0: # 25% possibility\n derivative_attrs = self.mutate(\n derivative_attrs,\n self.swap_bits(derivative_attrs, start_index, self.bit_per_exclusive_attrs),\n self.get_mask(self.bit_per_exclusive_attrs * self.allele_num, start_index)\n )\n rand >>= self.bit_per_attrs_swap\n start_index += self.bit_per_exclusive_attrs * self.allele_num\n derivative_attrs, rand = self.swap_dominant_recessive_bin_attrs(derivative_attrs, rand, start_index)\n return derivative_attrs, rand\n\n def swap_dominant_recessive_bin_attrs(self, derivative_attrs, rand, position):\n attrs_mask = 0x5555555555555555555555555555555555555555555555555555555555555555\n rand_mask = (((rand >> 1) | rand) & attrs_mask) << position\n dominant_attrs = (((derivative_attrs >> 1) & ~rand_mask) | (derivative_attrs & rand_mask)) & attrs_mask\n rand_mask <<= 1\n recessive_attrs = (((derivative_attrs << 1) & ~rand_mask) | (derivative_attrs & rand_mask)) & (attrs_mask << 1)\n bin_attrs_mask = self.get_mask(self.bin_attrs_num * self.allele_num, position)\n derivative_attrs = self.mutate(derivative_attrs, (dominant_attrs | recessive_attrs) & bin_attrs_mask,\n bin_attrs_mask)\n rand >>= 2 * self.bin_attrs_num\n return derivative_attrs, rand\n\n def mutate_noise(self, derivative_noise, rand):\n # mutate every 16 noise\n for idx in range(0, self.noise_num, self.noise_per_mutation): # 8 times\n # the first four bits indicate the position to mutate\n mutation_pos = (rand % self.noise_per_mutation + idx) * self.bit_per_noise\n rand >>= self.bit_per_noise_mutation_pos\n\n # the next two bits indicate the value to mutate\n mutation = rand % self.noise_value_range << mutation_pos\n rand >>= self.bit_per_noise\n\n # replace the gene at mutationPos with the mutation\n derivative_noise = self.mutate(derivative_noise, mutation, self.get_mask(self.bit_per_noise, mutation_pos))\n return derivative_noise, rand\n\n def mutate_attrs(self, derivative_attrs, rand):\n attr_to_mutate = rand % self.attrs_per_mutation\n\n # a mutation only happens on a dominant attribute.\n # since there are 14 attrs in total, we mutate just one of the attrs\n # the possibility for every attribute to mutate should be 1/16 for dominant and 0 for recessive\n if attr_to_mutate >= self.attrs_num:\n # no mutation if random num >= 14\n return derivative_attrs, rand >> self.bit_per_attrs_mutation_pos + self.bit_per_exclusive_attrs\n\n if attr_to_mutate < self.exclusive_attrs_num:\n # the position of the gene to mutate. it should be the allele on the left\n mutation_pos = self.allele_num * self.bit_per_exclusive_attrs * attr_to_mutate + \\\n self.bit_per_exclusive_attrs\n mutation_bit_num = self.bit_per_exclusive_attrs\n else:\n mutation_pos = self.total_exclusive_attrs_bit_num + self.allele_num * (\n attr_to_mutate - self.exclusive_attrs_num) * self.bit_per_bin_attrs + self.bit_per_bin_attrs\n mutation_bit_num = self.bit_per_bin_attrs\n rand >>= self.bit_per_attrs_mutation_pos\n mutation_mask = self.get_mask(mutation_bit_num, mutation_pos)\n mutation = rand % 2 ** mutation_bit_num << mutation_pos\n derivative_attrs = self.mutate(derivative_attrs, mutation, mutation_mask)\n\n # TODO: comment line below. This is not necessary, just for code completeness.\n rand >>= self.bit_per_exclusive_attrs\n\n # we used at most 8 bits (or 5 if we mutate on binary attributes, or 4 if no mutation)\n # remaining 256 - 216 - 8 = 32 free bits!\n return derivative_attrs, rand\n\n # some helper function of computation to tidy up the codes\n\n @staticmethod\n def get_mask(size, position):\n # binary mask with `size` number of 1 and followed by `position` number of 0\n return 2 ** size - 1 << position\n\n @staticmethod\n def swap_bits(attrs, start_idx, bit_num):\n # swap the gene of size `bitNum` at `startIdx` of `attrs`\n attrs >>= start_idx\n recessive = attrs % (2 ** bit_num)\n dominant = (attrs >> bit_num) % (2 ** bit_num)\n return ((recessive << bit_num) + dominant) << start_idx\n\n @staticmethod\n def recombine(matron, sire, repetition, step, mask, rand):\n \"\"\"\n Recombine code of matron and sire into the derivative according to the choice\n :param matron: matron's noise or attributes\n :param sire: sire's noise or attributes\n :param repetition: repeated times\n :param step: step for moving the mask\n :param mask: mask indicating the position of the currently relevant gene\n :param rand: a random number reading from right to left\n\n If a bit is 0, choose matron's gene, and if 1, choose sire's gene\n \"\"\"\n derivative = 0\n for i in range(repetition):\n # 50% possibility choosing one of the origins\n derivative += (matron if rand % 2 == 0 else sire) & mask\n mask <<= step\n rand >>= 1\n return derivative, rand\n\n def recombine_batch(self, matron, sire, repetition, step, position, rand):\n \"\"\"\n Recombine code of matron and sire into the derivative according to the choice\n :param matron: matron's noise or attributes\n :param sire: sire's noise or attributes\n :param repetition: repeated times\n :param step: step for moving the mask\n :param position: indicating the starting position\n :param rand: a random number reading from right to left\n\n If a bit is 0, choose matron's gene, and if 1, choose sire's gene\n \"\"\"\n rand_dup = self.duplicate_bits(rand, step)\n rand_dup <<= position\n mask = self.get_mask(step * repetition, position)\n derivative = ((~rand_dup & matron) | (rand_dup & sire)) & mask\n rand >>= repetition\n return derivative, rand\n\n @staticmethod\n def duplicate_bits(input_val, count):\n \"\"\"\n Duplicate every bit for `count` times, ignore the highest bits\n Only works when count == 1 (do nothing) or count == 2\n\n >>> FusionFactory.duplicate_bits(0b01101011, 2)\n 11001111\n\n :param input_val: The input number\n :param count: The number duplicate bits for each input bit\n \"\"\"\n if count == 1:\n return input_val\n elif count == 2:\n mask1 = 0x00000000000000000000000000000000ffffffffffffffff0000000000000000\n mask2 = 0x000000000000000000000000000000000000000000000000ffffffffffffffff\n input_val = ((input_val & mask1) << 64) | (input_val & mask2)\n mask1 = 0x0000000000000000ffffffff000000000000000000000000ffffffff00000000\n mask2 = 0x000000000000000000000000ffffffff000000000000000000000000ffffffff\n input_val = ((input_val & mask1) << 32) | (input_val & mask2)\n mask1 = 0x00000000ffff000000000000ffff000000000000ffff000000000000ffff0000\n mask2 = 0x000000000000ffff000000000000ffff000000000000ffff000000000000ffff\n input_val = ((input_val & mask1) << 16) | (input_val & mask2)\n mask1 = 0x0000ff000000ff000000ff000000ff000000ff000000ff000000ff000000ff00\n mask2 = 0x000000ff000000ff000000ff000000ff000000ff000000ff000000ff000000ff\n input_val = ((input_val & mask1) << 8) | (input_val & mask2)\n mask1 = 0x00f000f000f000f000f000f000f000f000f000f000f000f000f000f000f000f0\n mask2 = 0x000f000f000f000f000f000f000f000f000f000f000f000f000f000f000f000f\n input_val = ((input_val & mask1) << 4) | (input_val & mask2)\n mask1 = 0x0c0c0c0c0c0c0c0c0c0c0c0c0c0c0c0c0c0c0c0c0c0c0c0c0c0c0c0c0c0c0c0c\n mask2 = 0x0303030303030303030303030303030303030303030303030303030303030303\n input_val = ((input_val & mask1) << 2) | (input_val & mask2)\n mask1 = 0x2222222222222222222222222222222222222222222222222222222222222222\n mask2 = 0x1111111111111111111111111111111111111111111111111111111111111111\n input_val = ((input_val & mask1) << 1) | (input_val & mask2)\n input_val = (input_val << 1) | input_val\n return input_val\n else:\n raise ValueError # not supported\n\n @staticmethod\n def mutate(derivative, mutation, mask):\n \"\"\"\n Mutate the gene at the `mask` position of the derivative code to `mutation`\n \"\"\"\n return derivative & ~mask + mutation\n\n @staticmethod\n def keccak(*args):\n keccak_hash = keccak.new(digest_bits=256)\n for i in args:\n keccak_hash.update(i.to_bytes(len(bin(i)) - 1, 'big'))\n return int(keccak_hash.hexdigest(), 16)\n\n\ndef binary_average(values, bits):\n bitmap = [\n [(j & (2 ** i)) >> i for j in values] for i in range(bits)\n ]\n averages = [\n round(sum(i) / len(i)) for i in bitmap\n ]\n return sum(\n i << n for n, i in enumerate(averages)\n )\n\n\ndef approximate(noise1, attrs1, noise2, attrs2, average=1):\n attrs = []\n\n factory = FusionFactory()\n for _ in range(average):\n attrs.append(factory.mix_code(noise1, attrs1, noise2, attrs2,\n entropy=(int.from_bytes(os.urandom(64), 'big'),))[1])\n\n return binary_average(attrs, 38)\n\n\nif __name__ == '__main__':\n n1 = 90473127252118133248908235787953752405933676411820653807769447369544567230866\n a1 = 52818018743\n n2 = 3741807294364386106505680355724161895371676705092164253676086926199092543794\n a2 = 52818020023\n\n print(f'In [0]: {bin(a1)}')\n print(f'In [1]: {bin(a2)}')\n\n print()\n for i in range(10):\n na3 = approximate(n1, a1, n2, a2)\n print(f'Out[{i}]: {bin(na3)}')\n\n n3 = 90587641027505316411294546399164831736118732119729757568075160231330036711826\n a3 = 52818022407\n\n print(f'\\nOut[0]: {bin(a3)}')\n","repo_name":"3wayHimself/crypko.py","sub_path":"crypko/fusion_factory.py","file_name":"fusion_factory.py","file_ext":"py","file_size_in_byte":14557,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"48"} +{"seq_id":"71613851027","text":"from keras.datasets import cifar10 \r\n\r\n(x_train, y_train), (x_test, y_test) = cifar10.load_data()\r\n\r\nnum_classes = 10\r\nprint(x_train.shape)\r\nprint(y_train.shape)\r\nprint(x_test.shape)\r\nprint(y_test.shape)\r\n\r\nimport numpy as np \r\nimport matplotlib.pyplot as plt \r\nfig, axes = plt.subplots(num_classes, 10, figsize = (15, 15)) \r\n\r\n# visualization\r\nfor i in range(num_classes): \r\n indice = np.where(y_train == i)[0] \r\n for j in range(10): \r\n axes[i][j].imshow(x_train[indice[j]]) \r\n axes[i][j].set_xticks([])\r\n axes[i][j].set_yticks([]) \r\nplt.tight_layout() \r\nplt.show() ","repo_name":"XieJiongyan/Machine_learning","sub_path":"CNN_to_image_classification/ctic_visualization.py","file_name":"ctic_visualization.py","file_ext":"py","file_size_in_byte":594,"program_lang":"python","lang":"en","doc_type":"code","stars":2,"dataset":"github-code","pt":"48"} +{"seq_id":"7263792103","text":"# Load icons from UIAssets\nimport tkinter\nimport os\nimport platform\nimport json\nfrom json.decoder import JSONDecodeError\n\n# FileHandler locations\nraw = os.path.join(os.getcwd(),\"Editor\")\nIconDir = os.path.join(raw,\"UIAssets\")\ndataLocations = \"\"\ntemplates = \"\"\n\n# Logos\ncrumbl_logo = os.path.join(IconDir,\"favicon.png\")\nengine_logo = os.path.join(IconDir,\"logo.png\")\nstudio_logo = os.path.join(IconDir,\"corp_logo.png\")\n\n# Ribbon icons\nrun_asset = os.path.join(IconDir,\"run.png\")\nbuild_asset = os.path.join(IconDir,\"build.png\")\n\nselect_asset = os.path.join(IconDir,\"select.png\")\nmove_asset = os.path.join(IconDir,\"move.png\")\nrotate_asset = os.path.join(IconDir,\"rotate.png\")\nresize_asset = os.path.join(IconDir,\"resize.png\")\n\nruler_asset = os.path.join(IconDir,\"ruler.png\")\n\nnew_layer_asset = os.path.join(IconDir,\"newlayer.png\")\nnew_scene_asset = os.path.join(IconDir,\"newscene.png\")\n\nnew_text_asset = os.path.join(IconDir,\"newtext.png\")\nnew_button_asset = os.path.join(IconDir,\"newbutton.png\")\nnew_slider_asset = os.path.join(IconDir,\"newSlider.png\")\nnew_entry_asset = os.path.join(IconDir,\"newEntry.png\")\nnew_checkbutton_asset = os.path.join(IconDir,\"newCheckbutton.png\")\nnew_rbutton_asset = os.path.join(IconDir,\"newRadioButton.png\")\nnew_dropdown_asset = os.path.join(IconDir,\"newDropdown.png\")\nnew_object_asset = os.path.join(IconDir,\"newObject.png\")\nnew_cbutton_asset = os.path.join(IconDir,\"checkbutton.png\")\nnew_switch_asset = os.path.join(IconDir,\"switch.png\")\n\n# Settings icons\nsv_dark_asset = os.path.join(IconDir,\"SVDarkMode.png\")\nsv_light_asset = os.path.join(IconDir,\"SVLightMode.png\")\nforest_dark_asset = os.path.join(IconDir,\"ForestDarkMode.png\")\nforest_light_asset = os.path.join(IconDir,\"ForestLightMode.png\")\ntk_dark_asset = os.path.join(IconDir,\"tkDarkMode.png\")\ntk_light_asset = os.path.join(IconDir,\"tkLightMode.png\")\nchangeImage = os.path.join(IconDir,\"changedsetting.png\")\n\n# Splash screen assets\nlauncherSplash = os.path.join(IconDir,\"normalSplash.png\")\nprojectSplash = os.path.join(IconDir,\"projectSplash.png\")\n\n# Launcher assets\nnew_project_asset = os.path.join(IconDir,\"newProject.png\")\nopen_project_asset = os.path.join(IconDir,\"open.png\")\ngit_clone_asset = os.path.join(IconDir,\"git.png\")\nsettings_asset = os.path.join(IconDir,\"settings.png\")\nnoFile_asset = os.path.join(IconDir,\"noFile.png\")\n\n# Fonts, as used by ttf modules\ndefaultFont = os.path.join(IconDir,\"Source_Sans_Pro\",\"SourceSansPro-Regular.ttf\")\n\n\n# JSON handling\n# Data layouts\ntemplateData = {\"templateNames\":[\"Blank\"],\"templateLoctaions\":[\"NoTemplate/\"],\"templateThumbnails\":[\"NoTemplate/noPack.png\"],\"templateDescriptions\":[\"Blank editor project with minimal engine bindings\"],\"templateTypes\":[\"All\"],\"platforms\":[\"Windows\",\"Mac\",\"Linux\"]}\nsettingData = {\"theme\":\"sun_valley\",\"darkMode\":True,\"author\":\"placeholder\"}\nrecentFileData = {\"recentFilenames\":[],\"recentLocations\":[],\"recentDates\":[],\"objectTemplates\":[]}\nprojectData = {\"Title\":\"\",\"author\":\"NULL\",\"uiLayout\":[],\"fileStructure\":[],\"chosenPlatforms\":[\"\"],\"reccomendedPlatforms\":[\"Windows\",\"Mac\",\"Linux\"],\"specialInformation\":[]}\n\nopenProject = \"\"\n\n# Functions (Stolen from visualized because it just works)\ndef get_save_loc():\n global dataLocations\n global templates\n userOS = platform.system()\n usrHome = os.path.expanduser(\"~\")\n if userOS == \"Windows\":\n dataLocations = os.path.join(usrHome,\"AppData/Roaming/CrumblStudios/crumbl2D\")\n try:\n os.mkdir(os.path.join(usrHome,\"AppData/Roaming/CrumblStudios/\"))\n except FileExistsError:\n pass\n else:\n dataLocations = os.path.join(usrHome,\".crumbl2D\")\n print(\"Data location is %s\" %dataLocations)\n \n if os.path.join(dataLocations,\"settings.json\"):\n try:\n os.mkdir(dataLocations)\n templates = os.path.join(dataLocations,\"templates\")\n os.mkdir(templates)\n print(\"Data folder generated... file will be generated by json decoder\")\n except FileExistsError:\n print(\"\\033[33m FILEHANDLER: Data folder found, however settings.json was not found\\033[0m\")\n else:\n print(\"Save folder found!\")\n templates = os.path.join(dataLocations,\"templates\")\n print(\"Template location is %s\" %templates)\n return dataLocations\n\ndef save_setting_data(data):\n with open(os.path.join(dataLocations, 'userData.json'), 'w') as save_file:\n json.dump(data, save_file)\n\ndef get_setting_data(data_layout = settingData):\n try:\n with open(os.path.join(dataLocations, 'userData.json')) as save_file:\n print(\"SETTINGS: attempting to load file...\")\n return json.load(save_file)\n except JSONDecodeError:\n print(\"\\033[31m SETTINGS: JSON can't decode...\\033[0m\")\n with open(os.path.join(dataLocations, 'userData.json'), 'w') as save_file_2:\n json.dump(data_layout, save_file_2)\n return data_layout\n except FileNotFoundError:\n print(\"SETTINGS: file not found,generating...\")\n with open(os.path.join(dataLocations, 'userData.json'), 'w') as save_file_3:\n json.dump(data_layout, save_file_3)\n return data_layout\n\ndef save_template_data(data):\n with open(os.path.join(templates, 'templateData.ceTemplates'), 'w') as save_file:\n json.dump(data, save_file)\n\ndef get_template_data(data_layout = templateData):\n global templates\n try:\n with open(os.path.join(templates, 'templateData.ceTemplates')) as save_file:\n print(\"TEMPLATES: attempting to load file...\")\n return json.load(save_file)\n except JSONDecodeError:\n print(\"\\033[31mTEMPLATES: JSON can't decode...\\033[0m\")\n with open(os.path.join(templates, 'templateData.ceTemplates'), 'w') as save_file_2:\n json.dump(data_layout, save_file_2)\n return data_layout\n except FileNotFoundError:\n print(\"\\033[33mTEMPLATES: file not found, generating template data file\\033[0m\")\n try:\n with open(os.path.join(templates, 'templateData.ceTemplates'), 'w') as save_file_3:\n json.dump(data_layout, save_file_3)\n except FileNotFoundError:\n print(\"TEMPLATES: No directory found, generating template data folder\")\n os.mkdir(templates)\n with open(os.path.join(templates, 'templateData.ceTemplates'), 'w') as save_file_3:\n json.dump(data_layout, save_file_3)\n return data_layout\n\ndef save_user_data(data):\n with open(os.path.join(dataLocations, 'userdata.json'), 'w') as save_file:\n json.dump(data, save_file)\n\ndef get_user_data(data_layout = recentFileData):\n try:\n with open(os.path.join(dataLocations, 'userdata.json')) as save_file:\n print(\"USERDATA: attempting to load file...\")\n return json.load(save_file)\n except JSONDecodeError:\n print(\"USERDATA: JSON can't decode...\")\n with open(os.path.join(dataLocations, 'userdata.json'), 'w') as save_file_2:\n json.dump(data_layout, save_file_2)\n return data_layout\n except FileNotFoundError:\n print(\"USERDATA: file not found, generating template data file\")\n try:\n with open(os.path.join(dataLocations, 'userdata.json'), 'w') as save_file_3:\n json.dump(data_layout, save_file_3)\n except FileNotFoundError:\n print(\"\\033[31m USERDATA: No directory found, generating template data folder\\033[0m\")\n with open(os.path.join(dataLocations, 'userdata.json'), 'w') as save_file_3:\n json.dump(data_layout, save_file_3)\n return data_layout\n\ndef loadData(dir,statusText,statusBar,dataStyle = projectData):\n statusText.set(\"Getting project files: loading JSON data\")\n dataStyle = {\"Title\":\"\",\"author\":\"NULL\",\"uiLayout\":[],\"fileStructure\":[]}\n try:\n with open(os.path.join(dir, 'userdata.json')) as save_file:\n print(\"USERDATA: attempting to load file...\")\n return json.load(save_file)\n except JSONDecodeError:\n print(\"\\033[31mUSERDATA: JSON can't decode...\\033[0m\")\n with open(os.path.join(dir, 'userdata.json'), 'w') as save_file_2:\n json.dump(dataStyle, save_file_2)\n return dataStyle\n except FileNotFoundError:\n print(\"USERDATA: file not found, generating template data file\")\n try:\n with open(os.path.join(dir, 'userdata.json'), 'w') as save_file_3:\n json.dump(dataStyle, save_file_3)\n except FileNotFoundError:\n print(\"USERDATA: No directory found, generating template data folder\")\n with open(os.path.join(dir, 'userdata.json'), 'w') as save_file_3:\n json.dump(dataStyle, save_file_3)\n return dataStyle\n statusBar.step(25)\n\n# File handling for project creation/ opening\n\ndef createData(dir,title,statusText,statusBar):\n statusText.set(\"Creating project files 0%\")\n os.makedirs(dir)\n statusText.set(\"Creating project files 5%\")\n statusBar.step(5)\n\ndef openFiles(dir,title,statusText,statusBar):\n statusText.set(\"Loading project files 0%\")\n openProject = dir\n statusText.set(\"Loading project files 5%\")\n statusBar.step(5)\n","repo_name":"Crumbl-Studios/Crumbl-2D","sub_path":"Editor/fileHandler.py","file_name":"fileHandler.py","file_ext":"py","file_size_in_byte":9170,"program_lang":"python","lang":"en","doc_type":"code","stars":3,"dataset":"github-code","pt":"48"} +{"seq_id":"40966037995","text":"def solution(genres, plays):\n answer = []\n # 같은 장르끼리 dict에 plays 수만큼 저장하기\n dic = dict()\n for i in range(len(genres)):\n if genres[i] not in dic:\n dic[genres[i]] = plays[i]\n else:\n dic[genres[i]] = dic.get(genres[i]) + plays[i]\n\n # 각각의 plays수를 저장하는 list 만들기\n songs = []\n for i in range(len(genres)):\n songs.append([i, genres[i], plays[i]])\n songs = sorted(songs, key=lambda x: (x[2],x[0]), reverse=True) # plays 큰 순서대로\n # 3번) 재생 횟수가 같을 경우에는, 고유 번호가 낮은 노래먼저! -> 여러 개의 요소 인 경우 :튜플로 사용 가능\n print(songs)\n\n # plays수 (value값) 순으로 정렬하기\n dic = sorted(dic, reverse=True)\n\n # 각 genre에서 재생수가 많은 곡 두 개 정해서 list-up\n # 이미 정렬되어 있는 것을 기준으로 !\n for genre in dic: # 1번 ) 가장 많이 재생된 장르 순서대로\n count = 0\n for i in range(len(songs)): # 장르 내에서 많이 재생된 노래 먼저 수록\n if genre == songs[i][1] and count < 2:\n answer.append(songs[i][0])\n count += 1\n elif count >= 2:\n break\n return answer\n\n\nif __name__ == \"__main__\":\n genres = ['classic', 'pop', 'classic', 'classic', 'pop']\n plqys = [500, 600, 150, 800, 2500]\n print(solution(genres,plqys))","repo_name":"mindobiee/Programmers","sub_path":"유형별 문제/Hash/[3] 베스트 앨범.py","file_name":"[3] 베스트 앨범.py","file_ext":"py","file_size_in_byte":1466,"program_lang":"python","lang":"ko","doc_type":"code","stars":0,"dataset":"github-code","pt":"48"} +{"seq_id":"19789386971","text":"from sqlalchemy import (\n Column, Integer,\n MetaData, String, Table,\n Enum as PgEnum,DateTime,\n ForeignKey, ForeignKeyConstraint\n)\nfrom sqlalchemy.dialects.postgresql import UUID\nfrom enum import Enum, unique\n\n\n@unique\nclass UnitType(Enum):\n offer = \"OFFER\"\n category = \"CATEGORY\"\n\nconvention = {\n 'all_column_names': lambda constraint, table: '_'.join([\n column.name for column in constraint.columns.values()\n ]),\n 'ix': 'ix__%(table_name)s__%(all_column_names)s',\n 'uq': 'uq__%(table_name)s__%(all_column_names)s',\n 'ck': 'ck__%(table_name)s__%(constraint_name)s',\n 'fk': 'fk__%(table_name)s__%(all_column_names)s__%(referred_table_name)s',\n 'pk': 'pk__%(table_name)s'\n}\n\nmetadata = MetaData(naming_convention=convention)\n\nproducts_table = Table(\n 'items',\n metadata,\n Column('id', UUID, primary_key=True),\n Column('name', String, nullable=False),\n Column('type', PgEnum(UnitType, name='type'), nullable=False),\n Column('parentId', String, nullable=True),\n Column('price', Integer, nullable=True),\n Column('date', DateTime(timezone=True), nullable=True),\n\n)\n\nrelations_table = Table(\n 'relations',\n metadata,\n Column('unit_id', String, primary_key=True),\n Column('relative_id', String, primary_key=True),\n)\n","repo_name":"ivasnev/RestFull-API-WeMarket","sub_path":"WeMarket/db/schema.py","file_name":"schema.py","file_ext":"py","file_size_in_byte":1291,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"48"} +{"seq_id":"37927607741","text":"'''\nEste programa cria uma lista dos artigos de revistas da science direct e respectivos links do Sci-hub para download\nAceita como input um ficheiro do tipo .txt com as citações dos artigos que se obtem no site da sciencedirect\n\n'''\n\nimport sys\n\ndef get_content(file_to_load):\n line_list=[]\n ficheiro = open(file_to_load, 'r')\n line=ficheiro.readline()\n while line:\n line_list.append(line.strip('\\n'))\n line=ficheiro.readline()\n #print(line_list)\n return line_list\n\ndef get_titles_doi(line_list):\n for item in line_list:\n doi_index=item.find('doi.org')\n if(doi_index!=-1):\n title=line_list[line_list.index(item)-6]\n title=title[:len(title)-1]\n doi=item[8+8:len(item)-1]\n print(title)\n print('http://sci-hub.tw/'+doi)\n print('')\n\n\nget_titles_doi(get_content(sys.argv[1]))","repo_name":"nflveiga/SciMed","sub_path":"GetJournals.py","file_name":"GetJournals.py","file_ext":"py","file_size_in_byte":888,"program_lang":"python","lang":"pt","doc_type":"code","stars":0,"dataset":"github-code","pt":"48"} +{"seq_id":"18185331903","text":"import helperFunctions\nimport random\nfrom providerData import ProviderData\n\n#This file contains the classes Member and MemberData which\n#makes up the part of the data repository concerning member information.\n\n#The Member class contains all personal information of one member.\nclass Member:\n #The constructor is the only time the member number is\n #allowed to be set.\n def __init__(self, number : int):\n self.memberName = None\n self.memberNumber = number\n self.memberAddress = None\n self.memberCity = None\n self.memberState = None\n self.memberZip = None\n #Return true if any of the fields besides memberNumber are already filled.\n def checkFilled(self) -> bool:\n if self.memberName or self.memberAddress or self.memberCity or\\\n self.memberState or self.memberZip:\n return True\n return False\n #Fills all of the fields of the class except for memberNumber.\n #Returns false and does not do anything if any of the fields are already filled.\n #Returns true otherwise.\n def fillMember(self) -> bool:\n if self.checkFilled() == True:\n return False\n self.memberName = helperFunctions.informationPrompter(\"member's name\", 1, 25)\n self.memberAddress = helperFunctions.informationPrompter(\"member's address\", 1, 25)\n self.memberCity = helperFunctions.informationPrompter(\"member's city\", 1, 14)\n self.memberState = helperFunctions.informationPrompter(\"member's state\", 2, 2)\n self.memberZip = helperFunctions.informationPrompter(\"member's zip code\", 5, 5)\n #Displays through all fields aside memberNumber and asks the user if they would like to\n #change them, then lets the user do so.\n #Returns false and does nothing if none of the fields are filled yet.\n #Otherwise, returns true.\n def adjustMember(self) -> bool:\n if self.checkFilled() == False:\n return False\n if self.memberName:\n print(\"The current member name is: \" + self.memberName + \". Do you want to change it?\")\n if helperFunctions.yesNoPrompter():\n self.memberName = helperFunctions.informationPrompter(\"member's name\", 1, 25)\n if self.memberAddress:\n print(\"The current member address is: \" + self.memberAddress + \". Do you want to change it?\")\n if helperFunctions.yesNoPrompter():\n self.memberAddress = helperFunctions.informationPrompter(\"member's address\", 1, 25)\n if self.memberCity: \n print(\"The current member city is: \" + self.memberCity + \". Do you want to change it?\")\n if helperFunctions.yesNoPrompter():\n self.memberCity = helperFunctions.informationPrompter(\"member's city\", 1, 14)\n if self.memberState:\n print(\"The current member state is: \" + self.memberState + \". Do you want to change it?\")\n if helperFunctions.yesNoPrompter():\n self.memberState = helperFunctions.informationPrompter(\"member's state\", 2, 2)\n if self.memberZip:\n print(\"The current member zip code is: \" + self.memberZip + \". Do you want to change it?\")\n if helperFunctions.yesNoPrompter():\n self.memberZip = helperFunctions.informationPrompter(\"member's zip code\", 5, 5)\n\nclass MemberData(ProviderData):\n def __init__(self):\n super().__init__()\n self.memberTable = dict()\n #Range of numbers that area a valid member number\n self.maxNumber = 999999999\n self.minNumber = 100000000\n\n #Randomly generates an unused member number.\n #Seed parameter only exists for unit tests.\n def generateMemberNumber(self, seed=None) -> int:\n random.seed(seed)\n memberNumber = -1\n validNumber = False\n while validNumber == False:\n memberNumber = random.randint(self.minNumber, self.maxNumber)\n if memberNumber not in self.memberTable:\n validNumber = True\n return memberNumber\n\n #Creates Member class with valid number, then lets the user fill in the\n #member information, and then stores the member in the table.\n def insertMember(self):\n number = self.generateMemberNumber()\n member = Member(number)\n member.fillMember()\n self.memberTable[member.memberNumber] = member\n print(\"The member number is: \" + str(number))\n\n #Takes a member number as an input and checks if it is in the dictionary.\n #If it is, remove it and remove true.\n #Otherwise, remove false.\n def removeMember(self, number : int) -> bool:\n if number not in self.memberTable:\n return False\n del self.memberTable[number]\n return True\n\n def retrieveMember(self, number : int) -> Member:\n if number not in self.memberTable:\n return None\n return self.memberTable[number]\n\n # Validates Member ID for login access to ChocAn\n def validateMember(self, number) -> Member:\n if helperFunctions.validNumberCheck(number): # checks if number is a 9 digit numerical value\n member = self.retrieveMember(int(number)) # searches data repository for existing member id\n if member is not None:\n print(\"Login Successful\")\n return member\n\n else:\n print(\"Error: Invalid Member ID\")\n return None\n\n else:\n print(\"Error: Not a valid 9 digit ID\")\n return None","repo_name":"iwnl-daniel/The-ChocAn-Simulator","sub_path":"memberData.py","file_name":"memberData.py","file_ext":"py","file_size_in_byte":5496,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"48"} +{"seq_id":"74847808144","text":"#!/usr/bin/env python\n# coding: utf-8\n\n# ## Goal: Indexes for the flash drougth project\n# \n# In this notebook, I am working to a script the calculates indexes we need for the flash drougth project. These will be timeseries for the area-integrated Rhine basin. \n# \n# \n# ### The indexes we need are: \n# \n# - SPI standardized precipitation index. Variable: precipitation\n# - SPEI standardized precipitation/evapotranspiration index. Variable: precipitation - potential evapotranspiration\n# - ESI/SESR evaporative stress index/standardized evaporative stress ratio. Variable: evapotranspiration/potential evapotranspiration\n# - SMI soil moisture index. Variable: soil moisture\n# \n# ### Input variables for the script\n# \n# - Variable to standardize \n# - Time scale (For now we test all variables for 7, 14, 21, 28 day time scales)\n\nimport xarray as xr\nimport numpy as np\nimport pandas as pd\nimport matplotlib.pyplot as plt\nimport sys\n\nimport rpy2\nimport rpy2.robjects as robjects\nfrom rpy2.robjects.packages import importr\nfrom rpy2.robjects import pandas2ri\n# import functions (and packages) from R\nr_time_series = robjects.r('ts')\n\ndef read_in_ERA5(var, diri, basin, detrended=False):\n if detrended:\n ds = xr.open_dataset(f'{diri}/{basin}/{var}_{basin}_detrend.nc')\n else:\n ds = xr.open_dataset(f'{diri}/{basin}/{var}_{basin}.nc')\n\n da = ds[var]\n return da\n\n\ndef make_index_timeseries(var, diri,basin, detrended=False):\n if var == 'mrsos' or var == 'SWIs':\n da = read_in_ERA5(var, diri, basin, detrended)\n elif var == 'pr': \n da = read_in_ERA5(var, diri, basin, detrended)\n da[da < 0 ] = 0\n elif var == 'wb':\n da_pr = read_in_ERA5('pr', diri, basin, detrended)\n da_pet = read_in_ERA5('pet', diri, basin, detrended)\n da = da_pr - da_pet\n elif var == 'es':\n da_et = read_in_ERA5('et', diri, basin, detrended)\n da_pet = read_in_ERA5('pet', diri, basin, detrended)\n da_et[da_et < 0 ] = 0\n da_pet[da_pet < 0] = 0\n da = da_et / da_pet\n da[da > 5] = 5 \n return da\n\n\ndef calc_standardized_index_daily(da, scale):\n SPEI_package = importr('SPEI')\n r_spei_function = robjects.r['spei']\n\n # convert to R timeseries\n r_da = r_time_series(robjects.FloatVector(da.values), start = robjects.IntVector([da.time.dt.year[0].values, da.time.dt.month[0].values]), frequency = 365)\n r_standardized_index = r_spei_function(r_da, scale=scale, na_rm=True, distribution='log-Logistic',verbose=False)\n\n\n # put standardized index in DataArray\n da_standardized_index = da.copy(deep=True)\n da_standardized_index.values = xr.DataArray(pandas2ri.ri2py_vector(r_standardized_index.rx2('fitted')))\n \n return da_standardized_index\n\n\ndef calc_index_to_netcdf(var, diri, diro, basin, scale, detrended=False):\n\n da = make_index_timeseries(var, diri,basin, detrended)\n da_standardized_index = calc_standardized_index_daily(da, scale)\n\n # define data with variable attributes as Xarray dataset\n\n if var == 'pr':\n indexname = f'SPI-{scale}'\n explanation = 'precipitation'\n elif var == 'mrsos':\n indexname = f'SMI-{scale}'\n explanation = 'top layer soil moisture'\n elif var == 'SWIs':\n indexname = f'SWIs-{scale}'\n explanation = 'top layer soil water index'\n elif var == 'wb':\n indexname = f'SPEI-{scale}'\n explanation = 'water balance (pr - PET)'\n elif var == 'es':\n indexname = f'ESI-{scale}'\n explanation = 'evaporative stress (ET - PET)'\n\n\n var_attr = {'units': '-', \n 'standard_name': f'{indexname}_{scale}d',\n 'long_name': f'{indexname} standardized index of {var} ({explanation}) on scale: {scale}d. ',\n }\n\n coords={'time': (['time'], da_standardized_index.time.data, da_standardized_index.time.attrs)}\n \n ds_new = xr.Dataset(\n data_vars=dict(\n index=(['time'], \n da_standardized_index.data, \n var_attr,\n )),\n coords=coords\n )\n\n # da_standardized_index.name = indexname\n # da_standardized_index.attrs = var_attr\n # ds_new = da_standardized_index.to_dataset\n\n ds_new.time.encoding = {'zlib': False,\n 'shuffle': False,\n 'complevel': 0,\n 'fletcher32': False,\n 'contiguous': False,\n 'dtype': np.dtype('float64'),\n 'units': 'days since 1850-01-01 00:00:00',\n 'calendar': 'proleptic_gregorian'\n }\n\n ds_new.index.encoding = {'_FillValue': np.nan,\n 'missing_value':np.nan,\n 'dtype': np.dtype('float64'),\n 'zlib': False\n }\n\n # ds_new['index'].rename(indexname)\n ds_new[indexname] = ds_new['index']\n ds_new = ds_new.drop(['index'])\n\n if detrended:\n filo=f'{indexname}_{basin}_detrended.nc'\n else: \n filo=f'{indexname}_{basin}.nc'\n ds_new.to_netcdf(f'{diro}/{filo}')\n\n\n\ndef main():\n detrended=True\n basin = 'Danube'\n diri='/scratch/nkkw/Karin/P2_flashdroughts/meteodata_ERA5/'\n diro = '/scratch/nklm/Px_flashdroughts/indices_ERA5'\n for var in ['pr','SWIs','wb','es']:\n # for var in ['es',]:\n for scale in [7,14,21,28]:\n #for scale in [7,28]:\n calc_index_to_netcdf(var, diri, diro, basin, scale,detrended)\n\n\nif __name__ == '__main__':\n sys.exit(main())\n","repo_name":"lmuntjewerf/flash_droughts","sub_path":"index_definitions/calc_indices.py","file_name":"calc_indices.py","file_ext":"py","file_size_in_byte":5553,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"48"} +{"seq_id":"16177139301","text":"#CHECK EVERYTHING\nfrom kivy.app import App\nfrom kivy.core.window import Window\nfrom kivy.graphics import Color, Line\nfrom kivy.uix.gridlayout import GridLayout\nfrom kivy.uix.label import Label\nfrom kivy.uix.button import Button\nfrom kivy.uix.textinput import TextInput\n\n# Screen size and color\nWindow.size = (400, 600)\n\nclass Layout(GridLayout):\n def __init__(self, **kwargs):\n super(Layout, self).__init__(**kwargs)\n\n self.width = Window.size[0]\n self.height = Window.size[1]\n self.add_gradient()\n\n\n\n def add_gradient(self):\n alpha_channel_rate = 0\n increase_rate = 1 / self.width\n\n for sep in range(self.width):\n self.canvas.add(Color(rgba=(100/225, 0, 190/255, alpha_channel_rate)))\n self.canvas.add(Line(points=[sep, 0, sep, self.height], width=1))\n alpha_channel_rate += increase_rate\n\n # Landing Page\n self.cols = 1\n self.padding = 100\n self.spacing = 30\n self.title = Label(\n text='Lvcky Guesses',\n color=(0,0,0.5,1),\n font_size= 50\n )\n self.add_widget(self.title)\n\n # Adding Landing page buttons\n self.start = Button(\n text='START',\n font_size=15,\n )\n self.add_widget(self.start)\n self.start.bind(on_press=self.displayStart)\n\n\n self.instructions = Button(\n text='INSTRUCTIONS',\n font_size=15,\n )\n self.add_widget(self.instructions)\n\n self.end = Button(\n text='END',\n font_size=15,\n )\n self.add_widget(self.end)\n\n def displayStart(self,instance):\n self.land = Label(\n text=\"Lvcky Guesses\",\n font_size= 50\n )\n self.add_widget(self.land)\n\n self.quest = Label(\n text='Can you guess the 6 lucky Numbers?',\n font_size= 15\n )\n self.add_widget(self.quest)\n\nWindow.size = (400, 600)\n\nclass Entry(GridLayout):\n def __init__(self, **kwargs):\n super(Entry, self).__init__(**kwargs)\n\n self.cols = 1\n self.padding = 100\n self.spacing = 30\n self.title = Label(\n text='Lvcky Guesses',\n color=(0, 0, 0.5, 1),\n font_size=50\n )\n self.add_widget(self.title)\n\n self.quest = Label(\n text='Can you guess the 6 lucky Numbers?',\n font_size=15\n )\n self.add_widget(self.quest)\n\n self.range = Label(\n text='Enter your guess (1-99): ',\n font_size=15\n )\n self.add_widget(self.range)\n\n self.player = TextInput(\n hint_text=\"Player Guess: \",\n multiline=False,\n font_size=15,\n size=(20,20)\n )\n\n self.add_widget(self.player)\n\n self.attempts = GridLayout()\n self.cols = 1\n self.attempbox = Label(text='Your Attempts = 6 ')\n self.add_widget(self.attempbox)\n\n # Input Button\n self.input = Button(text='ENTER')\n self.add_widget(self.input)\n\n # Input Message Display\n self.display = Label(text='Result on Entry')\n self.add_widget(self.display)\n\n # Adding Reveal Box\n self.reveal = Label(text='The Lucky Numbers are: ')\n self.add_widget(self.reveal)\n\n\n\n\nclass Lucky(App):\n def build(self):\n return Entry()\n\nif __name__ == '__main__':\n Lucky().run()\n","repo_name":"Techn1calUchiha/USSD","sub_path":"main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":3462,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"48"} +{"seq_id":"10876534655","text":"# *args allow as to give unlimited positional arguments in to the function\n# since it is tuple we can access it by index\n# args[0] or args[3]\ndef add(*args):\n sum = 0\n for n in args:\n sum += n\n return sum\n\n\nprint(add(8, 4, 6, 10))\n","repo_name":"vicknesh22/100_days_of_python","sub_path":"day27/playground.py","file_name":"playground.py","file_ext":"py","file_size_in_byte":247,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"48"} +{"seq_id":"29853675042","text":"\nfrom datetime import datetime\nfrom game import State\nfrom dual_network import DN_OUTPUT_SIZE\nimport pickle\nimport os\n\n\ndef first_player_value(ended_state):\n if ended_state.is_lose():\n return -1 if ended_state.is_first_player() else 1\n return 0\n\n\ndef write_data(history):\n now = datetime.now()\n os.makedirs('./data/', exist_ok=True)\n path = './data/{:04}{:02}{:02}{:02}{:02}{:02}.history'.format(\n now.year, now.month, now.day, now.hour, now.minute, now.second)\n with open(path, mode='wb') as f:\n pickle.dump(history, f)\n\n\ndef play(record):\n history = []\n actions = [int(i) for i in record.split()]\n state = State()\n\n for action in actions:\n policies = [0] * DN_OUTPUT_SIZE\n policies[action] = 1\n\n history.append([[state.pieces, state.enemy_pieces], policies, None])\n\n state = state.next(action)\n\n # print(state)\n\n value = first_player_value(state)\n for i in range(len(history)):\n history[i][2] = value\n value = -value\n return history\n\n\ndef generate_data_from_records(record):\n history = []\n\n for i in range(len(record)):\n h = play(record[i])\n history.extend(h)\n\n write_data(history)\n","repo_name":"moon44432/gomokupp-zero","sub_path":"generate_data.py","file_name":"generate_data.py","file_ext":"py","file_size_in_byte":1212,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"48"} +{"seq_id":"42528201700","text":"'''\nLess than 17, advise to \"Hit\"\nGreater than or equal to 17, but less than 21, advise to \"Stay\"\nExactly 21, advise \"Blackjac\nOver 21, advise \"Already Busted\n\nLet's write a python program to give basic blackjack playing advice during a game by asking the player for cards.\nFirst, ask the user for three playing cards (A, 2, 3, 4, 5, 6, 7, 8, 9, 10, J, Q, or K). \nThen, figure out the point value of each card individually. Number cards are worth their number, \nall face cards are worth 10. At this point, assume aces are worth 1. Use the following rules to determine the advice:\n\nAces can be worth 11 if they won't put the total point value of both cards over 21.\nRemember that you can have multiple aces in a hand. \nTry generating a list of all possible hand values by doubling the number of values in the output whenever you encounter an ace. \nFor one half, add 1, for the other, add 11. This ensures if you have multiple aces that you account for the full range of possible values.\n'''\n # q = int(input(\"How many cards do you have? : \"))\n# user_cards = input(\"What 3 cards do you have? : \")\n\n# user_cards_list = []\n\n# user_cards_list.append(user_cards)\n#getting card data and inputting it into a list\nuser_cards_dict = {\n \"J\": 10,\n \"K\": 10,\n \"Q\": 10,\n \"2\": 2,\n \"3\": 3,\n \"4\": 4,\n \"5\": 5,\n \"6\": 6,\n \"7\": 7,\n \"8\": 8,\n \"9\": 9,\n \"10\": 10,\n \"A\": 1\n}\n\ndef cards():\n user_cards_list = [] #q = int(input(\"How many cards do you have? : \"))\n for i in range(3):\n # q = int(input(\"How many cards do you have? : \"))\n\n if i < 3: #i < q:\n # q = int(input(\"How many cards do you have : \"))\n user_cards = input(\"What 3 card do you have?(Letters must be in Caps) : \")\n # user_cards.upper()\n #print(type(user_cards))\n user_cards_list.append(user_cards)\n #i += 1\n continue\n else: \n print(\"Please try again\")\n return user_cards_list\n# cards()\n# print(user_cards_list) #test to see if cards are being added to my list\n\n\n# c2 = 2\n# c3 = 3\n# c4 = 4\n# c5 = 5\n# c6 = 6\n# c7 = 7\n# c8 = 8\n# c9 = 9\n# c10 = 10\n# J = 10\n# Q = 10\n# K = 10\n# A = 1\n# A = 11\n\n# print(type(c8))\n\n# total = 0\nmax_total = 21\n\ndef points(user_cards_list):\n total = 0\n # max_total = 21\n if \"J\" in user_cards_list:\n total += 10\n if \"Q\" in user_cards_list:\n total += 10\n if \"K\" in user_cards_list:\n total += 10\n if \"A\" in user_cards_list and total > 10:\n total += 1\n if \"A\" in user_cards_list and total < 10:\n total += 11\n if \"2\" in user_cards_list:\n total += 2\n if \"3\" in user_cards_list:\n total += 3\n if \"4\" in user_cards_list:\n total += 4\n if \"5\" in user_cards_list:\n total += 5\n if \"6\" in user_cards_list:\n total += 6\n if \"7\" in user_cards_list:\n total += 7\n if \"8\" in user_cards_list:\n total += 8\n if \"9\" in user_cards_list:\n total += 9\n if \"10\" in user_cards_list:\n total += 10\n # else:\n # print(\"Try some other shit I can't fix this code\")\n return total\n\n# print(type(points()))\n# points()\n# print(points())\n# print(total) #test to see if total is being read, it is not.\n\n#blackjack or nah checker\ndef blackjack(total):\n if total < 17:\n print(\"HIT\")\n #break\n elif total >= 17 and total < max_total:\n print(\"Stay\")\n #break\n elif total == max_total:\n print(\"BLACKJACK!!!!!!!!\")\n #break\n elif total > max_total:\n print(\"Already bussssssteddd\")\n #break\n else:\n print(\"Please try again later\")\n #break\n print(total)\nblackjack(points(cards())) #points = total essentially\n","repo_name":"PdxCodeGuild/class_mudpuppy","sub_path":"Assignments/Haoua/PYTHON/lab19.py","file_name":"lab19.py","file_ext":"py","file_size_in_byte":3695,"program_lang":"python","lang":"en","doc_type":"code","stars":3,"dataset":"github-code","pt":"48"} +{"seq_id":"74742190225","text":"from vm_manager.helpers.rbd_manager import RbdManager\n\nCEPH_CONF = \"/etc/ceph/ceph.conf\"\nPOOL_NAME = \"rbd\"\n\nIMG_SIZE = \"4M\"\nIMG_NAME = \"img1\"\nDEFAULT_NS = \"vm\"\nNS1 = \"namespace1\"\nNS2 = \"namespace2\"\n\nif __name__ == \"__main__\":\n\n with RbdManager(CEPH_CONF, POOL_NAME) as rbd:\n\n try:\n # Create namespace\n print(\"Create namespaces \" + NS1 + \" and \" + NS2)\n for ns in [NS1, NS2]:\n try:\n rbd.create_namespace(ns)\n except Exception as err:\n print(\"Could not create namespace \" + ns + \": \" + str(err))\n\n ns_list = rbd.list_namespaces()\n print(\"Namespace list: \" + str(ns_list))\n for ns in [NS1, NS2]:\n if ns not in ns_list:\n raise Exception(\"Could not create namespace \" + ns)\n\n # Set namespace NS1\n print(\"Set namespace \" + NS1)\n rbd.set_namespace(NS1)\n\n if rbd.get_namespace() != NS1:\n raise Exception(\"Could not set namespace \" + NS1)\n\n # Create image\n print(\"Create image \" + IMG_NAME)\n rbd.create_image(IMG_NAME, IMG_SIZE)\n\n img_list = rbd.list_images()\n print(\n \"Image list from namespace \"\n + rbd.get_namespace()\n + \": \"\n + str(img_list)\n )\n\n if IMG_NAME not in img_list:\n raise Exception(\n \"Image \" + IMG_NAME + \" not in namespace \" + NS1\n )\n\n # Switch to NS2\n print(\"Set namespace \" + NS2)\n rbd.set_namespace(NS2)\n\n img_list = rbd.list_images()\n print(\n \"Image list from namespace \"\n + rbd.get_namespace()\n + \": \"\n + str(img_list)\n )\n\n if IMG_NAME in img_list:\n raise Exception(\n \"Image \" + IMG_NAME + \" should not be in namespace \" + NS2\n )\n\n # Back to NS1\n print(\"Set namespace \" + NS1)\n rbd.set_namespace(NS1)\n\n # Remove images\n print(\"Remove image \" + IMG_NAME)\n rbd.remove_image(IMG_NAME)\n\n img_list = rbd.list_images()\n print(\n \"Image list from namespace \"\n + rbd.get_namespace()\n + \": \"\n + str(img_list)\n )\n if IMG_NAME in img_list:\n raise Exception(\n \"Could not remove \" + IMG_NAME + \" from namespace \" + NS1\n )\n\n # Default namespace\n rbd.set_namespace(DEFAULT_NS)\n\n # Remove namespaces\n print(\"Remove namespaces \" + NS1 + \" and \" + NS2)\n rbd.remove_namespace(NS1)\n rbd.remove_namespace(NS2)\n\n ns_list = rbd.list_namespaces()\n print(\"Namespace list: \" + str(ns_list))\n\n for ns in [NS1, NS2]:\n if ns in img_list:\n raise Exception(\n \"Namespace \" + ns + \" could not be removed\"\n )\n\n print(\"Test finished\")\n\n finally:\n # Cleanup\n for ns in [NS1, NS2]:\n if rbd.namespace_exists(ns):\n rbd.set_namespace(ns)\n for img in rbd.list_images():\n rbd.remove_image(img)\n rbd.set_namespace(DEFAULT_NS)\n print(\"Remove namespace \" + ns)\n rbd.remove_namespace(ns)\n print(\"Namespace list: \" + str(rbd.list_namespaces()))\n","repo_name":"seapath/vm_manager","sub_path":"vm_manager/helpers/tests/rbd_manager/create_rbd_namespace.py","file_name":"create_rbd_namespace.py","file_ext":"py","file_size_in_byte":3705,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"48"} +{"seq_id":"8091227955","text":"\"\"\"\nCompute unique devices in a district over a month\n\"\"\"\nimport json\nimport sys, time\nimport os\nimport requests\nimport pdb\nimport pandas as pd\n\nfrom datetime import date, datetime\nfrom pathlib import Path\nfrom string import Template\n\nfrom dataproducts.util.utils import create_json, get_data_from_blob, post_data_to_blob, \\\n push_metric_event, get_location_info, verify_state_district\nfrom dataproducts.resources.queries import district_devices_monthly\n\n\nclass DistrictMonthly:\n\n def __init__(self, data_store_location, druid_hostname, execution_date, location_search):\n self.data_store_location = Path(data_store_location)\n self.druid_hostname = druid_hostname\n self.execution_date = execution_date\n self.location_search = location_search\n self.config = {}\n\n\n def unique_users(self, result_loc_, date_, state_):\n \"\"\"\n Query druid for unique users by district over a month for a state\n :param result_loc_: pathlib.Path object to store resultant CSV\n :param date_: datetime object to pass for query and path\n :param query_: json query template\n :param state_: the state to be used in query\n :return: None\n \"\"\"\n slug_ = result_loc_.name\n year = date_.year\n month = date_.month\n if month != 1:\n start_date = datetime(year, month - 1, 1)\n else:\n start_date = datetime(year - 1, 12, 1)\n query = Template(district_devices_monthly.init())\n query = query.substitute(app=self.config['context']['pdata']['id']['app'],\n portal=self.config['context']['pdata']['id']['portal'],\n state=state_,\n start_date=start_date.strftime('%Y-%m-%dT00:00:00+00:00'),\n end_date=date_.strftime('%Y-%m-%dT00:00:00+00:00'))\n url = \"{}druid/v2/\".format(self.druid_hostname)\n headers = {\n 'Content-Type': \"application/json\"\n }\n response = requests.request(\"POST\", url, data=query, headers=headers)\n if response.status_code == 200:\n if len(response.json()) == 0:\n return\n data = []\n for response in response.json():\n data.append(response['event'])\n df = pd.DataFrame(data).fillna('Unknown')\n df.to_csv(result_loc_.parent.joinpath(date_.strftime(\"%Y-%m-%d\"),\n \"{}_monthly.csv\".format(slug_)), index=False)\n post_data_to_blob(result_loc_.parent.joinpath(date_.strftime(\"%Y-%m-%d\"),\n \"{}_monthly.csv\".format(slug_)), backup=True)\n df['District'] = df.get('District', pd.Series(index=df.index, name='District'))\n df['Unique Devices'] = df['Unique Devices'].astype(int)\n df = verify_state_district(result_loc_.parent.joinpath(date_.strftime('%Y-%m-%d')), state_, df)\n df = df[['District', 'Unique Devices']]\n df = df.groupby('District').sum().reset_index()\n df.to_csv(result_loc_.joinpath(\"aggregated_unique_users_summary.csv\"), index=False)\n create_json(result_loc_.joinpath(\"aggregated_unique_users_summary.csv\"))\n post_data_to_blob(result_loc_.joinpath(\"aggregated_unique_users_summary.csv\"))\n else:\n with open(result_loc_.parent.joinpath('error_log.log'), 'a') as f:\n f.write(state_ + 'summary ' + response.status_code + response.text)\n\n\n def init(self):\n start_time_sec = int(round(time.time()))\n\n analysis_date = datetime.strptime(self.execution_date, \"%d/%m/%Y\")\n result_loc = self.data_store_location.joinpath('district_reports')\n result_loc.mkdir(exist_ok=True)\n result_loc.joinpath(analysis_date.strftime(\"%Y-%m-%d\")).mkdir(exist_ok=True)\n self.data_store_location.joinpath('config').mkdir(exist_ok=True)\n get_data_from_blob(result_loc.joinpath('slug_state_mapping.csv'))\n tenant_info = pd.read_csv(result_loc.joinpath('slug_state_mapping.csv'))\n get_location_info(result_loc_=result_loc, location_search_=self.location_search,\n date_=analysis_date)\n get_data_from_blob(self.data_store_location.joinpath('config', 'diksha_config.json'))\n with open(self.data_store_location.joinpath('config', 'diksha_config.json'), 'r') as f:\n self.config = json.loads(f.read())\n for ind, row in tenant_info.iterrows():\n print(row['state'])\n result_loc.joinpath(row[\"slug\"]).mkdir(exist_ok=True)\n if isinstance(row['state'], str):\n self.unique_users(result_loc_=result_loc.joinpath(row[\"slug\"]), date_=analysis_date,\n state_=row['state'])\n\n end_time_sec = int(round(time.time()))\n time_taken = end_time_sec - start_time_sec\n metrics = [\n {\n \"metric\": \"timeTakenSecs\",\n \"value\": time_taken\n },\n {\n \"metric\": \"date\",\n \"value\": analysis_date.strftime(\"%Y-%m-%d\")\n }\n ]\n push_metric_event(metrics, \"District Monthly Report\")","repo_name":"Sunbird-Ed/sunbird-data-products","sub_path":"python-scripts/src/main/python/dataproducts/services/location/district_monthly.py","file_name":"district_monthly.py","file_ext":"py","file_size_in_byte":5325,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"48"} +{"seq_id":"8583301666","text":"from os import listdir\nfrom os.path import isfile, join\n\nindex = {}\n\nmypath = '_data'\ntxtFiles = [ f for f in listdir(mypath) if isfile(join(mypath,f)) ]\n\nfor fileName in txtFiles:\n openFile = open(\"_data/\" + fileName, \"rU\")\n for line in openFile:\n splitLine = line.split(\" \")\n for word in splitLine:\n if word in index:\n \tindex[word]['count'] += 1\n \tindex[word]['files'].append(fileName)\n else:\n index[word] = {}\n index[word]['count'] = 1\n index[word]['files'] = [fileName]\n\nprint(index)\n","repo_name":"regerahul/practice_1","sub_path":"gtm/practice_1.py","file_name":"practice_1.py","file_ext":"py","file_size_in_byte":537,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"48"} +{"seq_id":"2494319881","text":"import pandas as pd\nimport numpy as np\nimport random\nfrom IPython.display import Image\nimport collections\nfrom sklearn.datasets import load_breast_cancer\nfrom sklearn.preprocessing import StandardScaler\nfrom sklearn.metrics import confusion_matrix\nfrom statistics import mode\n\n\n\ndef euclidean_distance(a,b):\n return np.linalg.norm(a - b)\n\ndef create_clusters(X, centroids): \n\n labels = []\n for i, x in enumerate(X):\n closest_centroid_idx, _ = min_distance(x, centroids)\n labels.append(closest_centroid_idx)\n return np.array(labels)\n\ndef min_distance(sample, centroids):\n distance = [euclidean_distance(sample, centroid) for centroid in centroids]\n distance_min_index = np.argmin(distance)\n return distance_min_index, distance\n\ndef select_centroids(X,K):\n \n centroids = []\n random_sample_idx = np.random.choice(X.shape[0], 1, replace=False)\n centroids.append(X[random_sample_idx][0])\n \n #pick next k-1 centroids\n \n for i in range(K-1):\n distances = []\n #find the closest centroid for each data point\n\n for sample in X:\n temp = []\n for c in centroids:\n distance = euclidean_distance(sample, c)\n temp.append(distance)\n distances.append(min(temp))\n \n #choose the max distance from distances as next centroids \n next_centroid = X[np.argmax(distances)]\n centroids.append(next_centroid)\n return centroids\n\ndef kmeans(X:np.ndarray, K:int, centroids=None, max_iter=30, tolerance=1e-2):\n \n # num_sample, num_features = X.shape\n \n if centroids == 'kmeans++':\n centroids = select_centroids(X, K)\n else:\n #initialize centroids\n random_sample_idx = np.random.choice(X.shape[0], K, replace=False)\n centroids = X[random_sample_idx]\n \n \n for i in range(max_iter):\n #update cluster\n labels = create_clusters(X, centroids)\n \n #update centroids\n prev_centroids = centroids\n \n new_centroids = []\n for i in range(K):\n label_idx_per_cluster = np.where(labels==i)\n new_mean = np.mean(X[label_idx_per_cluster], axis=0)\n new_centroids.append(new_mean)\n centroids = new_centroids\n\n diff = euclidean_distance(np.array(prev_centroids), np.array(centroids))\n if diff <= tolerance:\n break\n return np.array(centroids), labels\n\n\ndef likely_confusion_matrix(y, labels):\n labels = [1-i for i in labels]\n labels = np.array(labels)\n y_pred = np.zeros(len(y))\n for y_i in np.unique(y):\n mode_ = mode(labels[labels == y_i])\n y_pred[labels == mode_] = y_i\n\n acc = np.mean(y==y_pred)\n matrix = pd.DataFrame(confusion_matrix(y, y_pred)).rename({0: 'False', 1:'True'}).rename(columns={0: 'False', 1:'True'})\n return acc, y_pred, matrix\n\n\n## 1D kmean implementation\n\ndef initialize_centroids(X, K):\n centroids_dict = collections.defaultdict()\n centroid = np.random.choice(X,K)\n for c in centroid:\n centroids_dict[c] = []\n return centroids_dict\n\ndef initiate_clusters(X, centroids):\n clusters_list = list(centroids.keys())\n clusters = centroids\n for x in X:\n distances = []\n for c in centroids.keys():\n distance = np.sqrt(np.sum(np.square(x - c)))\n distances.append(distance)\n min_distance = min(distances)\n cluster_idx = distances.index(min_distance) \n cluster = clusters_list[cluster_idx]\n clusters[cluster].append(x)\n return clusters\n\ndef new_centroids(clusters, X):\n centroids = clusters.keys()\n new_cluster = collections.defaultdict()\n for i, cluster in enumerate(centroids):\n new_mean = np.around(np.mean(clusters[cluster]),2)\n new_cluster[new_mean] = []\n return new_cluster\n\ndef reassign(new_cluster, X):\n new_cluster_centroids = list(new_cluster.keys())\n\n for x in X:\n distances = []\n for c in new_cluster_centroids:\n distance = np.sqrt(np.sum(np.square(x - c)))\n distances.append(distance)\n min_distance = min(distances)\n cluster_idx = distances.index(min_distance) \n cluster = new_cluster_centroids[cluster_idx]\n new_cluster[cluster].append(x)\n return new_cluster\n\ndef find_label(cluster, X):\n clusters = list(cluster.values())\n labels = []\n for x in X:\n for i, each_cluster in enumerate(clusters):\n if x in each_cluster:\n label = list(cluster.keys())[i]\n labels.append(label)\n return labels\n\ndef kmeans_1D(X:np.ndarray, K:int, centroids=None, max_iter=30, tolerance=1e-2):\n # initiate the k centroids - default dict\n centroids = initialize_centroids(X, K)\n \n for iter_ in range(max_iter): \n clusters = initiate_clusters(X, centroids)\n \n prev_centroids = np.array(list(centroids.keys()))\n centroids = reassign(clusters, X)\n current_centroids = np.array(list(centroids.keys()))\n \n diff = np.mean(prev_centroids - current_centroids)\n \n if diff < tolerance:\n labels = find_label(centroids, X)\n centroids = list(centroids.keys())\n return centroids, labels","repo_name":"summerzhang423/cluster","sub_path":"kmeans.py","file_name":"kmeans.py","file_ext":"py","file_size_in_byte":5267,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"48"} +{"seq_id":"8126633811","text":"# Definition for a binary tree node.\n# class TreeNode:\n# def __init__(self, val=0, left=None, right=None):\n# self.val = val\n# self.left = left\n# self.right = right\nclass BSTIterator:\n\n def __init__(self, root: Optional[TreeNode]):\n self.stack = [root]\n p = root\n while p.left:\n self.stack.append(p.left)\n p = p.left\n\n \n def next(self) -> int:\n node = self.stack.pop()\n # one step to the right\n if node.right:\n tmp = node.right\n self.stack.append(tmp)\n while tmp.left:\n self.stack.append(tmp.left)\n tmp = tmp.left\n return node.val\n\n def hasNext(self) -> bool:\n return len(self.stack) > 0\n \n\n\n# Your BSTIterator object will be instantiated and called as such:\n# obj = BSTIterator(root)\n# param_1 = obj.next()\n# param_2 = obj.hasNext()","repo_name":"YingbingZhu/python_leetcode","sub_path":"tree/173. Binary Search Tree Iterator.py","file_name":"173. Binary Search Tree Iterator.py","file_ext":"py","file_size_in_byte":924,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"48"} +{"seq_id":"35079099431","text":"# import pandas as pd\nimport numpy as np\nimport matplotlib.pyplot as plt\nfrom sklearn.linear_model import LinearRegression\n\nx = np.arange(1, 10)\ny = np.array([28, 25, 26, 31, 32, 29, 30, 35, 36])\nplt.scatter(x, y)\nplt.show()\n\n\nx = x.reshape(-1, 1)\ny = y.reshape(-1, 1)\nreg = LinearRegression()\nreg.fit(x, y)\nyhat = reg.predict(x)\n\n\nplt.scatter(x, y)\nplt.plot(x, yhat)\nplt.show()\n","repo_name":"Rohambadi/Machine-learning","sub_path":"maclearn/4.py","file_name":"4.py","file_ext":"py","file_size_in_byte":379,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"48"} +{"seq_id":"25456724707","text":"import discord\nimport os\nfrom dbHandler import DBManager\nfrom cManager import CManager\nfrom dotenv import load_dotenv\n\nload_dotenv()\n\n# Managers initiated\ndbManager = DBManager()\ncManager = CManager(dbManager)\n\n# Initial tables created\ndbManager.CreateTable()\n\nclient = discord.Client()\n\n@client.event\nasync def on_ready():\n print('We have logged in as {0.user}'.format(client))\n\n@client.event\nasync def on_message(message):\n if message.author == client.user:\n return\n\n triggered = dbManager.GetAutoMessageResponse(message.content)\n if triggered:\n await message.channel.send(triggered)\n return\n\n args = message.content.split(\"//\")\n if len(args) > 1:\n command = args[1]\n if len(args) > 2:\n if command == 'add':\n await cManager.add(message, args)\n return\n if command == 'rm':\n await cManager.rm(message, args)\n return\n else:\n if command == 'ping':\n await message.channel.send('PONG!')\n return\n if command == 'reset':\n await cManager.reset(message, args)\n return\n \n\nclient.run(os.getenv('DISCORD_TOKEN'))","repo_name":"DiegoSolorzanoO/Botinz","sub_path":"bot.py","file_name":"bot.py","file_ext":"py","file_size_in_byte":1236,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"48"} +{"seq_id":"739377256","text":"import os\nimport os.path\nfrom xml.etree.ElementTree import parse, Element\n#批量修改xml中内容\ndef test():\n path = \"./data/Annotations/\" # xml文件所在的目录\n files = os.listdir(path) # 遍历文件夹下所有文件名称\n for xmlFile in files: # 对所有文件进行循环遍历处理\n path1 = \"./data/Annotations/\"+xmlFile #定位当前处理的文件的路径\n newStr = os.path.join(path, xmlFile)\n\n dom = parse(newStr) # 获取xml文件中的参数\n root = dom.getroot() # 获取数据结构\n\n for obj in root.iter('object'): # 获取object节点中的name子节点(此处如果要换成别的比如bndbox)\n name = obj.find('name').text # 获取相应的文本信息\n # 以下为自定义的修改规则,我这里把文本信息为[1]~[5]的内容改成lack,依次类推\n if name in ['Japanese_spaniel']:\n new_name = 'Jack'\n elif name in ['Leonberg','Eskimo_dog','malamute','Siberian_husky']:\n new_name = 'Danger'\n elif name in ['Chihuahua']:\n new_name = 'huahua'\n else:\n new_name = 'Unknown'\n obj.find('name').text = new_name # 修改\n dom.write(path1, xml_declaration=True) # 保存到指定文件\n pass\nif __name__ == '__main__':\n test()\n","repo_name":"WJQGG/SOUGO-An-intelligent-platform-based-on-YOLO","sub_path":"changelables.py","file_name":"changelables.py","file_ext":"py","file_size_in_byte":1369,"program_lang":"python","lang":"zh","doc_type":"code","stars":0,"dataset":"github-code","pt":"48"} +{"seq_id":"72234795027","text":"\"\"\"\nPrime Time\nHave the function PrimeTime(num) take the num parameter being passed and\nreturn the string true if the parameter is a prime number, otherwise return the string false.\nThe range will be between 1 and 2^16.\n\nExamples\n\nInput: 19\nOutput: true\n\nInput: 110\nOutput: false\n\nAuthor: Eda AYDIN\n\"\"\"\n\n\ndef PrimeTime(num):\n # code goes here\n i = 2\n while i < num:\n if num % i == 0:\n return \"false\"\n else:\n i += 1\n return 'true'\n\n\n# keep this function call here\nprint(PrimeTime(int(input())))\n","repo_name":"edaaydinea/Coderbyte","sub_path":"Medium/Prime Time.py","file_name":"Prime Time.py","file_ext":"py","file_size_in_byte":542,"program_lang":"python","lang":"en","doc_type":"code","stars":6,"dataset":"github-code","pt":"48"} +{"seq_id":"6121480832","text":"def solution(record):\n answer = []\n dic = {}\n\n for i in record:\n com = i.split()\n if len(com) == 3:\n dic[com[1]] = com[2]\n\n for i in record:\n com = i.split()\n if com[0] == 'Enter':\n answer.append(\"%s님이 들어왔습니다.\" % dic[com[1]])\n elif com[0] == 'Leave':\n answer.append(\"%s님이 나갔습니다.\" % dic[com[1]])\n\n return answer","repo_name":"KwonYoungbin/Programmers-Practice","sub_path":"Python/Level2/오픈채팅방.py","file_name":"오픈채팅방.py","file_ext":"py","file_size_in_byte":423,"program_lang":"python","lang":"ko","doc_type":"code","stars":1,"dataset":"github-code","pt":"48"} +{"seq_id":"40999773432","text":"import paddle\nimport numpy as np\nimport paddle.nn.functional as F\n\n# 构建验证集evaluate函数\n@paddle.no_grad()\ndef evaluate(model, criterion, metric, data_loader, label_vocab, if_return_results=True):\n\n model.eval()\n metric.reset()\n losses = []\n results = []\n for batch in data_loader:\n input_ids, token_type_ids, labels = batch['input_ids'], batch['token_type_ids'], batch['labels']\n logits = model(input_ids, token_type_ids)\n loss = criterion(logits, labels)\n probs = F.sigmoid(logits)\n losses.append(loss.numpy())\n metric.update(probs, labels)\n if if_return_results:\n probs = probs.tolist()\n for prob in probs:\n result = []\n for c, pred in enumerate(prob):\n if pred > 0.5:\n result.append(label_vocab[str(c)])\n results.append(','.join(result))\n\n auc, f1_score, precison, recall = metric.accumulate()\n print(\"eval loss: %.5f, auc: %.5f, f1 score: %.5f, precison: %.5f, recall: %.5f\" %\n (np.mean(losses), auc, f1_score, precison, recall))\n model.train()\n metric.reset()\n if if_return_results:\n return results\n else:\n return f1_score","repo_name":"fuyanzhi1234/examtag","sub_path":"eval.py","file_name":"eval.py","file_ext":"py","file_size_in_byte":1252,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"48"} +{"seq_id":"16737665360","text":"from time import sleep\nfrom selenium.webdriver import Chrome\nfrom pytest import fixture\n\n@fixture(scope=\"session\")\ndef setup_tear_down():\n driver=Chrome(\"C:\\\\chrome\\\\chromedriver-win32\\\\chromedriver.exe\")\n driver.maximize_window()\n driver.get(\"https://parabank.parasoft.com/parabank/register.htm;jsessionid=E854E23A39712313A7F6A6D668448727\")\n sleep(2)\n yield driver\n driver.close()\n\n","repo_name":"Sathish-R-Nayak/Automation-Project-1","sub_path":"conftest.py","file_name":"conftest.py","file_ext":"py","file_size_in_byte":401,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"48"} +{"seq_id":"38210673685","text":"from torch import nn\nimport torch, math\nimport matplotlib.pyplot as plt\n\nclass PositionalEncoder(nn.Module):\n\n def __init__(self, d_model, max_seq_len, p=0.1):\n super(PositionalEncoder, self).__init__()\n position = torch.arange(max_seq_len).unsqueeze(1)\n div_term = torch.exp(torch.arange(0, d_model, 2) * (-math.log(10000.0) / d_model))\n pe = torch.zeros(1, max_seq_len, d_model)\n pe[0, :, 0::2] = torch.sin(position * div_term)\n pe[0, :, 1::2] = torch.cos(position * div_term)\n self.register_buffer('pe', pe)\n self.dropout = nn.Dropout(p=p)\n\n # x has shape [batch, seq_len, embed_dim]\n def forward(self, x):\n _, seq_len, _ = x.shape\n out = self.dropout(x + self.pe[:, :seq_len, :])\n return out\n\n\nclass FeedForward(nn.Module):\n\n def __init__(self, input_dim):\n super(FeedForward, self).__init__()\n self.layer = nn.Sequential(\n nn.Linear(input_dim, input_dim * 4),\n nn.ReLU(),\n nn.Linear(input_dim * 4, input_dim)\n )\n\n def forward(self, x):\n return self.layer(x)\n \n\ndef test_positional_encoder():\n pe = PositionalEncoder(512, 2048)\n out = pe(torch.randn(32, 100, 512))\n print(out.shape)\n plt.figure(figsize=(20, 10))\n plt.title(\"Positional encoding\")\n plt.imshow(pe.pe[0].T, cmap=\"Greys\")\n plt.show()\n\n\nif __name__ == \"__main__\":\n test_positional_encoder()","repo_name":"gursi26/seq2seq-transformer","sub_path":"other_modules.py","file_name":"other_modules.py","file_ext":"py","file_size_in_byte":1436,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"48"} +{"seq_id":"41803098748","text":"import generator\n#计算每层输出之后的input_size\ndef parameters_and_flops_calculator(mdef):\n input_size=32\n middle_size=0\n if mdef['type_name']=='conv':\n parameters_amount= pow(mdef['kernel_size'],2)*mdef['in_ch']*mdef['out_ch']\n flops_amount=parameters_amount*pow(input_size,2)\n \n if mdef['type_name']=='resblock':\n kernel_size=3\n strides=[mdef['stride']]+[1]*(mdef['num_blocks']-1)\n in_channels=mdef['in_ch']\n out_channels=mdef['out_ch']\n padding=1\n for i,stride in strides:\n if i==0: \n parameters_count=pow(kernel_size,2)*in_channels*out_channels+kernel_size*out_channels*out_channels\n flops_amount+=parameters_count*pow(input_size,2)\n middle_size=(input_size-kernel_size+2*padding)//stride+1\n parameters_amount+=parameters_count\n else:\n parameters_count=pow(kernel_size,2)*out_channels*out_channels\n flops_amount+=parameters_count*pow(middle_size,2)\n middle_size=(input_size-kernel_size+2*padding)//stride+1\n parameters_amount+=parameters_count\n if stride!=1 or in_channels!=out_channels:\n parameters_count+=in_channels*out_channels\n flops_amount+=parameters_count*pow(middle_size,2)\n middle_size=(input_size-kernel_size+2*padding)//stride+1\n parameters_amount+=parameters_count\n\n \n if mdef['type_name']=='inceptiona':\n input_size=32\n padding=1\n padding_branch5x5=2\n in_channels=mdef['in_ch']\n pool_feature=mdef['po_ft']\n out_channels_branch1x1=64\n out_channels_branch5x5_1=48\n out_channels_branch5x5_2=64\n kernel_size_branch5x5=5\n kernel_size_branch3x3=3\n out_channels_branch3x3dbl_1=64\n out_channels_branch3x3dbl_2=96\n out_channels_branch3x3dbl_3=96\n #1x1卷积分支\n parameters_count_branch1x1=in_channels*out_channels_branch1x1\n flops_amount+=pow(input_size,2)*parameters_count_branch1x1\n\n #5x5卷积\n parameters_count_branch5x5_1=in_channels*out_channels_branch5x5_1\n flops_amount+=pow(input_size,2)*parameters_count_branch5x5_1\n parameters_count_branch5x5_2=in_channels*pow(kernel_size_branch5x5,2)*out_channels_branch5x5_2\n middle_size=(input_size-kernel_size_branch5x5+2*padding_branch5x5)//stride+1\n flops_amount+=pow(middle_size,2)*parameters_count_branch5x5_1\n parameters_count_branch5x5=parameters_count_branch5x5_1+parameters_count_branch5x5_2\n\n #3x3卷积\n parameters_count_branch3x3dbl_1=in_channels*out_channels_branch3x3dbl_1\n flops_amount+=pow(input_size,2)*parameters_count_branch3x3dbl_1\n middle_size=(input_size-kernel_size_branch5x5+2*padding_branch5x5)+1\n parameters_count_branch3x3dbl_2=out_channels_branch3x3dbl_1*out_channels_branch3x3dbl_2*pow(kernel_size_branch3x3,2)\n flops_amount+=pow(middle_size,2)*parameters_count_branch3x3dbl_2\n middle_size=(middle_size-kernel_size_branch3x3+2*padding)+1\n parameters_count_branch3x3dbl_3=out_channels_branch3x3dbl_2*out_channels_branch3x3dbl_3*pow(kernel_size_branch3x3,2)\n flops_amount+=pow(middle_size,2)*parameters_count_branch3x3dbl_3\n middle_size=(middle_size-kernel_size_branch3x3+2*padding)+1\n parameters_count_branch3x3=parameters_count_branch3x3dbl_1+parameters_count_branch3x3dbl_2+parameters_count_branch3x3dbl_3\n\n #pooling分支\n parameters_count_pooling=in_channels*pool_feature\n flops_amount+=pow(input_size,2)*parameters_count_pooling\n\n parameters_amount=parameters_count_branch1x1+parameters_count_branch3x3+parameters_count_branch5x5\n \n if mdef['type_name']=='inceptionb':\n in_channels=mdef['in_ch']\n kernel_size=3\n stride=2\n padding=1\n out_channels_branch3x3=384\n out_channels_branch3x3dbl_1=64\n out_channels_branch3x3dbl_2=96\n out_channels_branch3x3dbl_3=96\n #3x3卷积分支\n parameters_count_branch3x3=pow(kernel_size,2)*in_channels*out_channels_branch3x3\n flops_amount+=pow(input_size,2)*parameters_count_branch3x3\n\n #3x3dbl分支\n parameters_count_branch3x3dbl_1=in_channels*out_channels_branch3x3dbl_1\n flops_amount+=pow(input_size,2)*parameters_count_branch3x3dbl_1\n parameters_count_branch3x3dbl_2=out_channels_branch3x3dbl_1*out_channels_branch3x3dbl_2*pow(kernel_size_branch3x3,2)\n flops_amount+=pow(middle_size,2)*parameters_count_branch3x3dbl_2\n middle_size=(input_size-kernel_size+2*padding)//stride+1\n parameters_count_branch3x3dbl_3=out_channels_branch3x3dbl_2*out_channels_branch3x3dbl_3*pow(kernel_size_branch3x3,2)\n flops_amount+=pow(middle_size,2)*parameters_count_branch3x3dbl_3\n parameters_amount=parameters_count_branch3x3+parameters_count_branch3x3dbl_1+parameters_count_branch3x3dbl_2+parameters_count_branch3x3dbl_3\n \n \n if mdef['type_name']=='bottleneck':\n in_channels=mdef['in_ch']\n out_channels=mdef['out_ch']\n kernel_size=3\n padding=1\n parameters_count_1=in_channels*out_channels\n flops_amount+=pow(input_size,2)*parameters_count_1\n parameters_count_3x3=out_channels*out_channels*pow(kernel_size,2)\n flops_amount+=pow(middle_size,2)*parameters_count_branch3x3\n middle_size=(input_size-kernel_size+2*padding)//stride+1\n parameters_count_1x1_2=out_channels*out_channels\n flops_amount+=pow(middle_size,2)*parameters_count_1x1_2\n parameters_amount=parameters_count_1+parameters_count_3x3+parameters_count_1x1_2\n \n if mdef['type_name']=='fc':\n in_channels=mdef['in_ch']\n out_channels=mdef['out_ch']\n parameters_amount=in_channels*out_channels\n flops_amount=in_channels*out_channels\n \n return parameters_amount,flops_amount\n \n\n\n\n\n\n# def sample_net_tree(branch_node):\n# tree_def_list=[]\n# tree_def_list+=[mdef_dict(0,'conv',{'kernel_size':3,'in_ch':3,'out_ch':64,'stride':1,'batch_normalize':True,'activation':'relu'},1,-1,-1)] \n# tree_def_list+=[mdef_dict(1,'resblock',{'block':BasicBlock,'in_ch':64,'out_ch':64,'num_blocks':3,'stride':1},2,5,0)] #360448 90112 1\n# tree_def_list+=[mdef_dict(2,'resblock',{'block':BasicBlock,'in_ch':64,'out_ch':128,'num_blocks':3,'stride':2},3,-1,1)] #90112 正确 1/4\n# tree_def_list+=[mdef_dict(3,'resblock',{'block':BasicBlock,'in_ch':128,'out_ch':256,'num_blocks':3,'stride':2},4,-1,2)] #22528 90112 1/16\n# tree_def_list+=[mdef_dict(4,'resblock',{'block':BasicBlock,'in_ch':256,'out_ch':512,'num_blocks':3,'stride':2},8,-1,3)]\n# tree_def_list+=[mdef_dict(5,'fc',{'input_nums':8192,'num_class':10},-1,-1,4)]\n# tree_def_list+=[mdef_dict(6,'inceptiona',{'in_ch':tree_def_list[branch_node]['describe']['out_ch'],'po_ft':64},6,-1,branch_node)]\n# tree_def_list+=[mdef_dict(7,'inceptiona',{'in_ch':288,'po_ft':128},7,-1,6)]\n# #tree_def_list+=[mdef_dict(7,'bottleneck',{'in_ch':352,'out_ch':64},8,-1,2)]\n# print(tree_def_list[branch_node]['parent'])\n# tree_def_list+=[mdef_dict(8,'fc',{'input_nums':360448//pow(4,tree_def_list[branch_node]['parent']),'num_class':10},-1,-1,7)]\n# return tree_def_list\n","repo_name":"Shize1997Zhao/early-exit","sub_path":"utils.py","file_name":"utils.py","file_ext":"py","file_size_in_byte":7370,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"48"} +{"seq_id":"504798497","text":"from DD_Analyzer import SpectrumAnalyzer\n\nclass DD_FSWT(SpectrumAnalyzer):\n def __init__(self):\n super().__init__('FSWT')\n self.stepMode = False\n self.editableCommands = ['set_StartFreq',\n 'set_StopFreq',\n 'set_ResBW',\n 'set_VidBW',\n 'set_Attenuator',\n 'set_PreAmplifier',\n 'set_PreSelector',\n 'set_RefLevel',\n 'set_SweepTime',\n 'set_Detector']\n pass\n\n\n\n def setup(self):\n _ret = super().setup()\n if not _ret:\n return False\n #not attenuator protection\n _ret = self.sa.write(\"INP:ATT:PROT 0\")\n #calculate autorange with transducer\n self.sa.write(\"CORR:TRAN:ADJ:RLEV ON\")\n if not _ret:\n return False\n return True\n\n def set_StartFreq(self,*par:'S3'):\n f = float(par[0])\n return super().set_StartFreq(f)\n\n def set_StopFreq(self,*par:'S3'):\n f = float(par[0])\n return super().set_StopFreq(f)\n\n def set_RefLevel(self,*par:'S0'):\n return (super()).set_RefLevel(par[0])\n\n def set_Detector(self,*par:['Max Peak','Min Peak','Average','AC Video']):\n return (super().set_Detector(par[0]))\n\n def set_Attenuator(self,*par:'S0'):\n return(super().set_Attenuator(par[0]))\n\n def set_ResBW(self, *par: ['1', '2', '3', '5',\n '10', '20', '30', '50',\n '100', '200', '300', '500',\n '1k', '2k', '3k', '5k',\n '10k', '20k', '30k', '50k',\n '100k', '200k', '300k', '500k',\n '1M', '2M', '3M', '5M',\n '10M', '20M', '30M', '50M',\n '100M', '200M', '300M', '500M']):\n return (super().set_ResBW(par[0]))\n\n def set_VidBW(self,*par:['auto','1','2','3','5',\n '10','20','30','50',\n '100','200','300','500',\n '1k','2k','3k','5k',\n '10k','20k','30k','50k',\n '100k','200k','300k','500k',\n '1M','2M','3M','5M','10M','30M','50M']):\n _vf = float(par[0])\n if _vf > 50e6:\n return (True)\n return(super().set_VidBW(par[0]))\n\n def set_StepTime(self,*par:'f0'):\n if self.stepMode == False:\n super().set_SweepTime(par[0])\n\n def set_SweepTime(self,*par:'S0'):\n self.stepMode = False\n return super().set_SweepTime(par[0])\n\n def set_PreSelector(self,*par:['WIDE','NARROW']):\n _ret = True\n # to make it compatible to FSET with Preselector 'NORMAL'\n _ps = par[0]\n if _ps != 'WIDE':\n _ps = 'NARROW'\n _ret = super().get_PreselectorState()\n if _ret == False:\n super().set_PreselectorState('1')\n _ret = super().set_Preselector(_ps)\n return _ret\n\n def set_PreAmplifier(self,*par:['0','10','20','30']):\n #if amp == 0:\n # _ret = super().set_AmplifierState('0')\n #else:\n # _ret = super().get_AmplifierState()\n # if _ret == False:\n _ret = super().set_PreselectorState('1')\n if not _ret: return _ret\n _ret = super().set_Amplifier(par[0])\n return _ret\n\n\n def get_PreAmplifier(self):\n _ret = super().get_PreselectorState()\n if _ret == False:\n return 0\n if _ret == True:\n _ret = super().get_Amplifier()\n return _ret\n\n def set_Attenuator(self,*par:'S0'):\n return (super().set_Attenuator(par[0]))\n\n def setAutoLevel(self):\n self.sa.write(\"SENSE:ADJUST:LEVEL\")\n if not self.errorQueueHandler(): return False\n return True\n\n\n def autoRange(self):\n #start position\n _HF_Overload = False\n _IF_Overload = False\n _AMP = 0\n _ATT = 30\n\n self.set_Attenuator(30)\n _ret = super().set_PreselectorState('1')\n if not _ret:\n return False,0,0\n self.set_Attenuator(30)\n self.set_Amplifier(0)\n\n if not (self.setAutoLevel):\n return False,0,0\n\n _Attn = self.get_Attenuator()\n _Amp = self.get_Amplifier()\n# self.take_SweepAuto()\n# _RF_Overload, _IF_Overload = super().get_HFIF_Overload()\n# while not (_RF_Overload or _IF_Overload) and (_Amp < 30):\n# _tAmp = _Amp + 10\n# super().set_Amplifier(_tAmp)\n# self.take_SweepAuto()\n# _RF_Overload, _IF_Overload = super().get_HFIF_Overload()\n# if not(_RF_Overload or _IF_Overload):\n# _Amp = _tAmp\n\n# super().set_Amplifier(_Amp)\n return True,_Amp,_Attn\n\n\n","repo_name":"HenricusRex/TMV3","sub_path":"DeviceDriver/DD_FSWT.py","file_name":"DD_FSWT.py","file_ext":"py","file_size_in_byte":4956,"program_lang":"python","lang":"en","doc_type":"code","stars":2,"dataset":"github-code","pt":"48"} +{"seq_id":"74396813585","text":"import pprint\n\n__author__ = 'Joao'\n\nimport shutil\nfrom os.path import isfile\n\nfrom rdflib import Graph, Namespace, RDF, Literal, BNode, URIRef, XSD\n\nimport json\nfrom pprint import pprint\n\ng = Graph()\n\ng.parse('onto.ttl', format=\"n3\")\n\nprint(\"graph has %s statements.\\n\" % len(g))\n\nns=Namespace('http://www.movierecomendation.pt/ontology/movierecomendation.owl#')\n\nfirstYear = 2004\nlastYear = 2004\nthisYear = firstYear\n\n#\n# STORE PPL IN TREE\n#########################\nLocalNamespace=Namespace('http://www.movierecomendation.pt/Person/')\nthisYear = firstYear\nwhile thisYear <= lastYear:\n\n\tfilename = 'persons_' + str(thisYear) + '.json'\n\tFileData = open(filename)\n\tPersonJSON = json.load(FileData)\n\tFileData.close()\n\n\tfor person in PersonJSON:\n\n\t\t#see if Person is already added\n\t\tsearch = g.value(predicate=ns.hasPersonId, object=Literal(person['id']))\n\t\tif(search!=None):\n\t\t\tpprint(\"Error:Theres already an Instance for the Movie id \" + person['id'])\n\t\t\tcontinue;\n\n\t\tPersonNode = URIRef(LocalNamespace[person['id']]);\n\n\t\tg.add((PersonNode,RDF.type,ns.Person))\n\n\t\tfor attr in person:\n\t\t\tif(attr=='id'):\n\t\t\t\tg.add((PersonNode,ns.hasPersonId,Literal(person[attr])))\n\t\t\tif(attr=='name'):\n\t\t\t\tg.add((PersonNode,ns.hasPersonName,Literal(person[attr])))\n\t\t\tif(attr=='picture'):\n\t\t\t\tg.add((PersonNode,ns.hasPersonPicture,Literal(person[attr])))\n\t\t\tif(attr=='miniBio'):\n\t\t\t\tg.add((PersonNode,ns.hasPersonMiniBio,Literal(person[attr])))\n\t\t\tif(attr=='jobCategories'):\n\t\t\t\tfor prof in person[attr]:\n\t\t\t\t\tg.add((PersonNode,ns.hasProfession,ns[prof.replace(\" \",\"_\")]))\n\t\t\tif(attr=='birthPlace'):\n\t\t\t\tg.add((PersonNode,ns.hasPersonBirthPlace,Literal(person[attr])))\n\t\t\tif(attr=='birthDate'):\n\t\t\t\tif(person[attr] ==\"00-00-00\"):\n\t\t\t\t\tcontinue\n\t\t\t\tg.add((PersonNode,ns.hasPersonBirth,Literal(person[attr], datatype=XSD.dateTime)))\n\t\t\t#if(attr=='actor'):\n\t\t\t#\tpprint(person[attr])\n\t\t\t#if(attr=='director'):\n\t\t\t#\tpprint(person[attr])\n\tthisYear += 1\n#\n# STORE STUDIOS IN TREE\n#########################\nLocalNamespace=Namespace('http://www.movierecomendation.pt/Studio/')\nthisYear = firstYear\nwhile thisYear <= lastYear:\n\n\tfilename = 'studios_' + str(thisYear) + '.json'\n\tFileData = open(filename)\n\tStudioJSON = json.load(FileData)\n\tFileData.close()\n\n\tfor studio in StudioJSON:\n\t\t#see if Studio is already added\n\t\tsearch = g.value(predicate=ns.hasStudioId,object=Literal(studio['id']))\n\t\tif(search!=None):\n\t\t\tpprint(\"Error:Theres already an Instance for the Studio id \"+studio['id'])\n\t\t\tcontinue;\n\n\t\tStudioNode = URIRef(LocalNamespace[studio['id']]);\n\t\tg.add((StudioNode,RDF.type,ns.Studio))\n\t\tfor attr in studio:\n\t\t\tif(attr=='id'):\n\t\t\t\tg.add((StudioNode,ns.hasStudioId,Literal(studio[attr])))\n\t\t\tif(attr=='name'):\n\t\t\t\tg.add((StudioNode,ns.hasStudioName,Literal(studio[attr])))\n\tthisYear += 1\n#\n# STORE MOVIES IN TREE\n#########################\nLocalNamespace=Namespace('http://www.movierecomendation.pt/Movie/')\nthisYear = firstYear\npprint(\"Add Movies\")\nwhile thisYear <= lastYear:\n\n\tfilename = 'movies_' + str(thisYear) + '.json'\n\t#load all json files to store in RDF\n\tFileData = open(filename)\n\tMovieJSON = json.load(FileData)\n\tFileData.close()\n\n\tfor movie in MovieJSON:\n\t\t#see if movie is already added\n\t\tsearch = g.value(predicate=ns.hasMediaId,object=Literal(movie['id']))\n\t\tif(search!=None):\n\t\t\tpprint(\"Error:Theres already an Instance for the Movie id \"+movie['id'])\n\t\t\tcontinue;\n\n\t\tMovieNode = URIRef(LocalNamespace[movie['id']]);\n\t\tg.add((MovieNode,RDF.type,ns.Movie))\n\n\t\tfor attr in movie:\n\t\t\tif(attr=='id'):\n\t\t\t\tg.add((MovieNode,ns.hasMediaId,Literal(movie[attr])))\n\t\t\tif(attr=='directors'):\n\t\t\t\tfor director in movie[attr]['director']:\n\t\t\t\t\tsearch = g.value(predicate=ns.hasPersonId, object=Literal(director))\n\t\t\t\t\tif(search==None):\n\t\t\t\t\t\tpprint(\"Error:Director not found\")\n\t\t\t\t\t\tcontinue;\n\t\t\t\t\tg.add((MovieNode,ns.hasDirector,search))\n\t\t\tif(attr=='studios'):\n\t\t\t\tfor studio in movie[attr]['studio']:\n\t\t\t\t\tsearch = g.value(predicate=ns.hasStudioId, object=Literal(studio))\n\t\t\t\t\tif(search==None):\n\t\t\t\t\t\tpprint(\"Error:Studio not found\")\n\t\t\t\t\t\tcontinue;\n\t\t\t\t\tg.add((MovieNode,ns.hasStudio,search))\n\t\t\tif(attr=='launchDate'):\n\t\t\t\tif(movie[attr] ==\"00-00-00\"):\n\t\t\t\t\tcontinue\n\t\t\t\tg.add((MovieNode,ns.hasMediaLaunchDate,Literal(movie[attr], datatype=XSD.dateTime)))\n\t\t\tif(attr=='genres'):\n\t\t\t\tfor genre in movie[attr]['genre']:\n\t\t\t\t\tg.add((MovieNode,ns.hasGenre,ns[genre]))\n\t\t\tif(attr=='description'):\n\t\t\t\tg.add((MovieNode,ns.hasMediaDescription,Literal(movie[attr])))\n\t\t\tif(attr=='score'):\n\t\t\t\tg.add((MovieNode,ns.hasMediaClassification,Literal(movie[attr], datatype=XSD.float)))\n\t\t\tif(attr=='duration'):\n\t\t\t\tg.add((MovieNode,ns.hasMediaDuration,Literal(movie[attr], datatype=XSD.integer)))\n\t\t\tif(attr=='stars'):\n\t\t\t\tfor star in movie[attr]['star']:\n\t\t\t\t\tsearch = g.value(predicate=ns.hasPersonId,object=Literal(star))\n\t\t\t\t\tif(search==None):\n\t\t\t\t\t\tpprint(\"Error:Star not found\")\n\t\t\t\t\t\tcontinue;\n\t\t\t\t\tg.add((MovieNode,ns.hasActor,search))\n\t\t\tif(attr=='name'):\n\t\t\t\tg.add((MovieNode,ns.hasMediaName,Literal(movie[attr])))\n\t\t\tif(attr=='image'):\n\t\t\t\tg.add((MovieNode,ns.hasMediaPoster,Literal(movie[attr])))\n\tthisYear += 1\n\n#\n# STORE SERIES IN TREE\n#########################\npprint(\"Add Series\")\nLocalNamespace=Namespace('http://www.movierecomendation.pt/Serie/')\nthisYear = firstYear\nwhile thisYear <= lastYear:\n\n\tfilename = 'series_' + str(thisYear) + '.json'\n\t#load all json files to store in RDF\n\tFileData = open(filename)\n\tSeriesJSON = json.load(FileData)\n\tFileData.close()\n\n\tfor serie in SeriesJSON:\n\t\tif(serie ==None):\n\t\t\tcontinue\n\t\t#see if movie is already added\n\t\tsearch = g.value(predicate=ns.hasMediaId,object=Literal(serie['id']))\n\t\tif(search!=None):\n\t\t\tpprint(\"Error:Theres already an Instance for the Serie id \"+serie['id'])\n\t\t\tcontinue;\n\n\t\tSerieNode = URIRef(LocalNamespace[serie['id']]);\n\t\tg.add((SerieNode,RDF.type,ns.Serie))\n\n\t\tfor attr in serie:\n\t\t\tif(attr=='id'):\n\t\t\t\tg.add((SerieNode,ns.hasMediaId,Literal(serie[attr])))\n\t\t\tif(attr=='studios'):\n\t\t\t\tfor studio in serie[attr]['studio']:\n\t\t\t\t\tsearch = g.value(predicate=ns.hasStudioId, object=Literal(studio))\n\t\t\t\t\tif(search==None):\n\t\t\t\t\t\tpprint(\"Error:Studio not found\")\n\t\t\t\t\t\tcontinue;\n\t\t\t\t\tg.add((SerieNode,ns.hasStudio,search))\n\t\t\tif(attr=='start'):\n\t\t\t\tg.add((SerieNode,ns.hasSerieStart,Literal(serie[attr], datatype=XSD.integer)))\n\t\t\tif(attr=='end'):\n\t\t\t\tif(serie[attr] != 0):\n\t\t\t\t\tg.add((SerieNode,ns.hasSerieEnd,Literal(serie[attr], datatype=XSD.integer)))\n\t\t\tif(attr=='genres'):\n\t\t\t\tfor genre in serie[attr]['genre']:\n\t\t\t\t\tg.add((SerieNode,ns.hasGenre,ns[genre]))\n\t\t\tif(attr=='description'):\n\t\t\t\tg.add((SerieNode,ns.hasMediaDescription,Literal(serie[attr])))\n\t\t\tif(attr=='score'):\n\t\t\t\tg.add((SerieNode,ns.hasMediaClassification,Literal(serie[attr], datatype=XSD.float)))\n\t\t\tif(attr=='duration'):\n\t\t\t\tg.add((SerieNode,ns.hasMediaDuration,Literal(serie[attr], datatype=XSD.integer)))\n\t\t\tif(attr=='stars'):\n\t\t\t\tfor star in serie[attr]['star']:\n\t\t\t\t\tsearch = g.value(predicate=ns.hasPersonId,object=Literal(star))\n\t\t\t\t\tif(search==None):\n\t\t\t\t\t\tpprint(\"Error:Star not found\")\n\t\t\t\t\t\tcontinue;\n\t\t\t\t\tg.add((SerieNode,ns.hasActor,search))\n\t\t\tif(attr=='name'):\n\t\t\t\tg.add((SerieNode,ns.hasMediaName,Literal(serie[attr])))\n\t\t\tif(attr=='image'):\n\t\t\t\tg.add((SerieNode,ns.hasMediaPoster,Literal(serie[attr])))\n\t\t\tif(attr=='seasons'):\n\t\t\t\tg.add((SerieNode,ns.hasSerieSeason,Literal(serie[attr], datatype=XSD.integer)))\n\tthisYear += 1\n\n\n\n\nthisYear = firstYear\nwhile thisYear <= lastYear:\n\n\tfilename = 'persons_' + str(thisYear) + '.json'\n\tFileData = open(filename)\n\tPersonJSON = json.load(FileData)\n\tFileData.close()\n\n\tLocalNamespace=Namespace('http://www.movierecomendation.pt/Person/')\n\tfor person in PersonJSON:\n\t\tPersonNode = URIRef(LocalNamespace[person['id']]);\n\t\tsearch = g.value(predicate=ns.hasPersonId, object=Literal(person['id']))\n\t\tif(search == None):\n\t\t\tpprint(\"Error: Person not found! \" + person['id'])\n\t\t\tcontinue;\n\t\ttry:\n\t\t\tif((search, ns.isKnownFor, None) not in g):\n\t\t\t\tfor relevant in person['knownFor']:\n\t\t\t\t\tsearch = g.value(predicate=ns.hasMediaId, object=Literal(relevant))\n\t\t\t\t\tif search == None:\n\t\t\t\t\t\tpprint(\"Error: NOT FOUND: \" + relevant)\n\t\t\t\t\t\tcontinue\n\t\t\t\t\tg.add((PersonNode,ns.isKnownFor,search))\n\t\texcept (Exception ):\n\t\t\tpprint(\"Error: attribute not found on \" + person['id'])\t\n\n\tthisYear += 1\n\ng.serialize(destination='output1.ttl', format='n3')","repo_name":"jpbat/ws","sub_path":"RDF_Populate/main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":8320,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"48"} +{"seq_id":"41008951711","text":"import lib\r\n\r\n\r\nwhile 1:\r\n\r\n choice=int(input('''**********Welcome to Yomna's hospital*********\r\n\r\n1)Admin mode.\r\n2)User mode.\r\n\r\nYour choice:'''))\r\n if choice==1:\r\n psw=str(input(\"Enter the password: \"))\r\n i=1\r\n while (i<3):\r\n if psw!='1234':\r\n psw=str(input(\"Please enter the correct password: \"))\r\n i+=1\r\n else:\r\n break\r\n if(i==3):\r\n print(\"\\n****Blocked for now*****\\nPlease try again later\")\r\n break\r\n else:\r\n while(1):\r\n choice=int(input(\r\n'''\r\n**Hello admin**\r\n1)Manage patients.\r\n2)Manage doctors.\r\n3)Book an appointment.\r\n4)Exit.\r\nYour choice: '''))\r\n if (choice==1):\r\n lib.manage_patients()\r\n elif (choice==2):\r\n lib.manage_doctors()\r\n elif (choice==3):\r\n lib.book_app()\r\n elif (choice==4):\r\n break\r\n else:\r\n print(\"Wrong choice\")\r\n elif (choice==2):\r\n print(\r\n'''1- View all departments.\r\n2- View all doctors.\r\n3- View all patients Residents in a hospital.\r\n4- Enter the patient's ID to view the patient details\r\n5- Enter the doctor's ID to view an appointments'''\r\n )\r\n viewer_option=int(input(\"\\nYour choice: \"))\r\n if (viewer_option==1) or (viewer_option==2):\r\n lib.user_display(viewer_option)\r\n elif (viewer_option==3)or(viewer_option==4):\r\n lib.patient_display_user(viewer_option)\r\n elif (viewer_option==5):\r\n lib.dr_appointments()\r\n else :\r\n print(\"Error choice!\")\r\n","repo_name":"YomnaRagab/Hospital-system","sub_path":"main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":1718,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"48"} +{"seq_id":"57091030","text":"\nimport os\nimport numpy as np\nfrom subprocess import Popen, PIPE\n\nfrom algs.cnn_ga.genetic.statusupdatetool import StatusUpdateTool\nfrom compute import Config_ini\nfrom compute.file import get_algo_local_dir, get_local_path, get_transfer_local_path\nfrom comm.log import Log\nfrom algs.cnn_ga.genetic.population import Population, Individual, ResUnit, PoolUnit\nimport multiprocessing\nimport time\nimport platform\n\n\nclass Utils(object):\n _lock = multiprocessing.Lock()\n\n @classmethod\n def get_lock_for_write_fitness(cls):\n return cls._lock\n\n @classmethod\n def path_replace(cls, input_str):\n new_str = input_str.replace('\\\\', '/')\n return new_str\n\n @classmethod\n def load_cache_data(cls):\n file_name = '%s/cache.txt' % (os.path.join(get_algo_local_dir(), 'populations'))\n file_name = cls.path_replace(file_name)\n _map = {}\n if os.path.exists(file_name):\n f = open(file_name, 'r')\n for each_line in f:\n rs_ = each_line.strip().split(';')\n _map[rs_[0]] = '%.5f' % (float(rs_[1]))\n f.close()\n return _map\n\n @classmethod\n def save_fitness_to_cache(cls, individuals):\n _map = cls.load_cache_data()\n for indi in individuals:\n _key, _str = indi.uuid()\n _acc = indi.acc\n if _key not in _map:\n Log.debug('Add record into cache, id:%s, acc:%.5f' % (_key, _acc))\n file_name = '%s/cache.txt' % (os.path.join(get_algo_local_dir(), 'populations'))\n file_name = cls.path_replace(file_name)\n f = open(file_name, 'a+')\n _str = '%s;%.5f;%s\\n' % (_key, _acc, _str)\n f.write(_str)\n f.close()\n _map[_key] = _acc\n\n @classmethod\n def save_population_at_begin(cls, _str, gen_no):\n file_name = '%s/begin_%05d.txt' % (os.path.join(get_algo_local_dir(), 'populations'), gen_no)\n file_name = cls.path_replace(file_name)\n with open(file_name, 'w') as f:\n f.write(_str)\n\n @classmethod\n def save_population_after_crossover(cls, _str, gen_no):\n file_name = '%s/crossover_%05d.txt' % (os.path.join(get_algo_local_dir(), 'populations'), gen_no)\n file_name = cls.path_replace(file_name)\n with open(file_name, 'w') as f:\n f.write(_str)\n\n @classmethod\n def save_population_after_mutation(cls, _str, gen_no):\n file_name = '%s/mutation_%05d.txt' % (os.path.join(get_algo_local_dir(), 'populations'), gen_no)\n file_name = cls.path_replace(file_name)\n with open(file_name, 'w') as f:\n f.write(_str)\n\n @classmethod\n def get_newest_file_based_on_prefix(cls, prefix):\n id_list = []\n for _, _, file_names in os.walk(os.path.join(get_algo_local_dir(), 'populations')):\n for file_name in file_names:\n if file_name.startswith(prefix):\n number_index = len(prefix) + 1\n id_list.append(int(file_name[number_index:number_index + 5]))\n if len(id_list) == 0:\n return None\n else:\n return np.max(id_list)\n\n @classmethod\n def load_population(cls, prefix, gen_no):\n file_name = '%s/%s_%05d.txt' % (os.path.join(get_algo_local_dir(), 'populations'), prefix, np.min(gen_no))\n file_name = cls.path_replace(file_name)\n params = StatusUpdateTool.get_init_params()\n pop = Population(params, gen_no)\n f = open(file_name)\n indi_start_line = f.readline().strip()\n while indi_start_line.startswith('indi'):\n indi_no = indi_start_line[5:]\n indi = Individual(params, indi_no)\n for line in f:\n line = line.strip()\n if line.startswith('--'):\n indi_start_line = f.readline().strip()\n break\n else:\n if line.startswith('Acc'):\n indi.acc = float(line[4:])\n elif line.startswith('[conv'):\n data_maps = line[6:-1].split(',', 5)\n conv_params = {}\n for data_item in data_maps:\n _key, _value = data_item.split(\":\")\n if _key == 'number':\n indi.number_id = int(_value)\n conv_params['number'] = int(_value)\n elif _key == 'in':\n conv_params['in_channel'] = int(_value)\n elif _key == 'out':\n conv_params['out_channel'] = int(_value)\n else:\n raise ValueError('Unknown key for load conv unit, key_name:%s' % (_key))\n conv = ResUnit(conv_params['number'], conv_params['in_channel'], conv_params['out_channel'])\n indi.units.append(conv)\n elif line.startswith('[pool'):\n pool_params = {}\n for data_item in line[6:-1].split(','):\n _key, _value = data_item.split(':')\n if _key == 'number':\n indi.number_id = int(_value)\n pool_params['number'] = int(_value)\n elif _key == 'type':\n pool_params['max_or_avg'] = float(_value)\n else:\n raise ValueError('Unknown key for load pool unit, key_name:%s' % (_key))\n pool = PoolUnit(pool_params['number'], pool_params['max_or_avg'])\n indi.units.append(pool)\n else:\n print('Unknown key for load unit type, line content:%s' % (line))\n pop.individuals.append(indi)\n f.close()\n\n # load the fitness to the individuals who have been evaluated, only suitable for the first generation\n if gen_no == 0:\n after_file_path = '%s/after_%05d.txt' % (os.path.join(get_algo_local_dir(), 'populations'), gen_no)\n if os.path.exists(after_file_path):\n fitness_map = {}\n f = open(after_file_path)\n for line in f:\n if len(line.strip()) > 0:\n line = line.strip().split('=')\n fitness_map[line[0]] = float(line[1])\n f.close()\n\n for indi in pop.individuals:\n if indi.id in fitness_map:\n indi.acc = fitness_map[indi.id]\n\n return pop\n\n @classmethod\n def read_template(cls):\n _path = os.path.join(os.path.dirname(__file__), 'template', 'model_template.py')\n part1 = []\n part2 = []\n part3 = []\n\n f = open(_path)\n f.readline()\n line = f.readline().rstrip()\n while line.strip() != '#generate_init':\n part1.append(line)\n line = f.readline().rstrip()\n\n line = f.readline().rstrip()\n while line.strip() != '#generate_forward':\n part2.append(line)\n line = f.readline().rstrip()\n\n line = f.readline().rstrip()\n while line.strip() != '\"\"\"':\n part3.append(line)\n line = f.readline().rstrip()\n return part1, part2, part3\n\n @classmethod\n def generate_pytorch_file(cls, indi, test=False):\n # query convolution unit\n conv_name_list = []\n conv_list = []\n for u in indi.units:\n if u.type == 1:\n conv_name = 'self.conv_%d_%d' % (u.in_channel, u.out_channel)\n if conv_name not in conv_name_list:\n conv_name_list.append(conv_name)\n conv = '%s = BasicBlock(in_planes=%d, planes=%d)' % (conv_name, u.in_channel, u.out_channel)\n conv_list.append(conv)\n\n # query fully-connect layer\n out_channel_list = []\n image_output_size = StatusUpdateTool.get_input_size()\n for u in indi.units:\n if u.type == 1:\n out_channel_list.append(u.out_channel)\n else:\n out_channel_list.append(out_channel_list[-1])\n image_output_size = int(image_output_size / 2)\n fully_layer_name = 'self.linear = nn.Linear(%d,%d)' % (\n image_output_size * image_output_size * out_channel_list[-1], StatusUpdateTool.get_num_class())\n # generate the forward part\n forward_list = []\n for i, u in enumerate(indi.units):\n if i == 0:\n last_out_put = 'x'\n else:\n last_out_put = 'out_%d' % (i - 1)\n if u.type == 1:\n _str = 'out_%d = self.conv_%d_%d(%s)' % (i, u.in_channel, u.out_channel, last_out_put)\n forward_list.append(_str)\n\n else:\n if u.max_or_avg < 0.5:\n _str = 'out_%d = F.max_pool2d(%s, 2)' % (i, last_out_put)\n else:\n _str = 'out_%d = F.avg_pool2d(%s, 2)' % (i, last_out_put)\n forward_list.append(_str)\n forward_list.append('out = out_%d' % (len(indi.units) - 1))\n\n part1, part2, part3 = cls.read_template()\n _str = []\n current_time = time.strftime(\"%Y-%m-%d %H:%M:%S\")\n _str.append('\"\"\"')\n _str.append(current_time)\n _str.append('\"\"\"')\n _str.extend(part1)\n _str.append('\\n %s' % ('#conv unit'))\n for s in conv_list:\n _str.append(' %s' % (s))\n _str.append('\\n %s' % ('#linear unit'))\n _str.append(' %s' % (fully_layer_name))\n\n _str.extend(part2)\n for s in forward_list:\n _str.append(' %s' % (s))\n _str.extend(part3)\n if not test:\n file_name = '%s/%s.py' % (os.path.join(get_algo_local_dir(), 'scripts'), indi.id)\n else:\n file_name = '%s/cnn_ga_%s.py' % (os.path.join(get_transfer_local_path(), 'example'), indi.id)\n file_name = cls.path_replace(file_name)\n script_file_handler = open(file_name, 'w')\n script_file_handler.write('\\n'.join(_str))\n script_file_handler.flush()\n script_file_handler.close()\n\n @classmethod\n def write_to_file(cls, _str, _file):\n f = open(_file, 'w')\n f.write(_str)\n f.flush()\n f.close()\n","repo_name":"benchenas/BenchENAS","sub_path":"BenchENAS_python_package/algs/cnn_ga/utils.py","file_name":"utils.py","file_ext":"py","file_size_in_byte":10528,"program_lang":"python","lang":"en","doc_type":"code","stars":11,"dataset":"github-code","pt":"48"} +{"seq_id":"10933944715","text":"import json\nimport sys\n\nid2captions = {}\n\nfor line in sys.stdin:\n image_id, caption, score = line.strip().split(\"\\t\")\n score = float(score)\n if image_id in id2captions:\n if id2captions[image_id][1] < score:\n id2captions[image_id] = (caption, score)\n else:\n id2captions[image_id] = (caption, score)\n \nresults = []\nfor image_id in id2captions:\n caption, score = id2captions[image_id]\n caption = caption.replace(\"\", \"\")\n result = {}\n result['image_id'] = image_id\n result['caption'] = caption\n results.append(result)\n\njson.dump(results, sys.stdout, ensure_ascii=False, indent=4)\n","repo_name":"wangheda/ImageCaption-UnderFitting","sub_path":"scripts/ranker_convert_csv_to_oracle_prediction.py","file_name":"ranker_convert_csv_to_oracle_prediction.py","file_ext":"py","file_size_in_byte":603,"program_lang":"python","lang":"en","doc_type":"code","stars":9,"dataset":"github-code","pt":"48"} +{"seq_id":"33143432062","text":"# coding: utf-8\n\n\nfrom .page_base import (\n TaskHandlerBase, TextProcessMixin, \n SCRIPT_BASE_HEAD, SCRIPT_BASE_TAIL, STYLE_BASE\n)\n\n\nclass TTextClassification(TaskHandlerBase, TextProcessMixin):\n \n DEFAULT_INSTRUCTION = 'Natural Language Inference Task\\n' + \\\n 'Read the following sentences and ' + \\\n 'click the button of the most appliable class.'\n DEFAULT_GOLD_ACTIONS = 'move_to+#correct_button click'\n \n def get_html_text(self, _id):\n \n fields = self.compile_fields(_id)\n text = self.render_text(**fields)\n return text\n \n def compile_fields(self, _id):\n \n data = self.data[_id]\n metadata = self.metadata\n fields = {}\n \n fields['gold_actions'] = self.DEFAULT_GOLD_ACTIONS\n \n try:\n fields['instruction'] = metadata['instructions'][0]\n except:\n fields['instruction'] = self.DEFAULT_INSTRUCTION\n \n feature_name_rule = metadata['feature_name_rules'][0]\n fields['sentences'] = sentences = []\n # tuple (name, sentence)\n for f in metadata['sentence_features']:\n name = feature_name_rule.get(f, f)\n sentence = data[f]\n sentences.append((name, sentence))\n \n label_rule = metadata['label_rules'][0]\n # answer is id (int) for classification\n fields['answer'] = int(data['label'])\n # id and name\n fields['candidates'] = [(_, label_rule.get(_, str(_))) for _ in metadata['labels']]\n \n return fields\n \n def render_text(self, instruction, sentences, candidates, answer, gold_actions):\n \n # Font settings for this tasks\n font_size_head, font_size_main, font_size_tail, line_height = ('16px', '16px', '16px', 1.4)\n \n # Escaping\n # we do not need escape except for newline for target sentences of emulated ocr.\n candidates_name = [(_id, self.escape_new_line(n)) for _id, n in candidates]\n instruction = self.escape_new_line(instruction)\n sentences = [(self.escape_new_line(n), self.escape_new_line(s)) for n, s in sentences]\n \n # Sentences\n context = '
'\n for name, sentence in sentences:\n if name:\n sentence = f'{name}: {sentence}'\n context += sentence + '
'\n context += '
'\n \n # Buttons for candidates\n buttons = []\n for candidate_id, condidate_name in candidates:\n if candidate_id == answer:\n _id = 'id=\"correct_button\" '\n else:\n _id = ''\n buttons.append(f'')\n \n footer = '
Classes:
%s'%(''.join(buttons))\n \n # Start HTML\n src = ''\n src += ''\n \n src += ''\n src += ''\n src += f''\n src += f''\n src += ''\n src += ''\n src += ''\n \n src += ''\n \n style = f'display:inline-block; float:left; clear:both; margin-bottom:10px; font-size:{font_size_head}; line-height:{line_height};'\n src += f'
{instruction}
'\n \n style = f'display:inline-block; float:left; clear:both; margin-bottom:10px; font-size:{font_size_main}; line-height:{line_height};'\n src += f'
{context}
'\n \n style = f'display:inline-block; float:left; clear:both; margin-bottom:10px; font-size:{font_size_tail}; line-height:{line_height};'\n src += f'
{footer}
'\n \n src += ''\n src += ''\n \n src = self.emulated_ocr(src, self.is_debugging)\n return src\n","repo_name":"Alab-NII/bertbui_pub","sub_path":"tasksvr/src/tasksvr/pages/page_glue.py","file_name":"page_glue.py","file_ext":"py","file_size_in_byte":4404,"program_lang":"python","lang":"en","doc_type":"code","stars":9,"dataset":"github-code","pt":"48"} +{"seq_id":"42845253313","text":"from odoo import api, fields, models, _\nfrom odoo.exceptions import RedirectWarning, UserError, ValidationError, AccessError\nfrom odoo.tools import float_is_zero, float_compare, safe_eval, date_utils, email_split, email_escape_char, email_re\nfrom odoo.tools.misc import formatLang, format_date, get_lang\n\nfrom collections import defaultdict\nfrom datetime import date, timedelta\nfrom itertools import groupby\nfrom itertools import zip_longest\nfrom hashlib import sha256\nfrom json import dumps\n\nimport json\nimport re\n\nclass AccountMove(models.Model):\n _inherit = \"account.move\"\n\n creation_rate = fields.Float(string=\"Tasa en ultima modificacion\")\n\n @api.onchange('date')\n def _creation_rate_onchange(self):\n tasa = self.company_id.currency_id._get_rates(self.company_id, self.date).get(self.company_id.currency_id.id)\n if tasa:\n self.creation_rate = tasa\n else:\n raise ValidationError(_('No existen tasas para la fecha contable de la factura'))\n\n #############################################################################################################\n # Se extiende esta funcion para agregar en el onchange el campo por el cual ahora deben\n # cambiar las conversiones \n #############################################################################################################\n\n @api.onchange('date', 'currency_id', 'x_studio_field_TJfMu')\n def _onchange_currency(self):\n if not self.currency_id:\n return\n if self.is_invoice(include_receipts=True):\n company_currency = self.company_id.currency_id\n has_foreign_currency = self.currency_id and self.currency_id != company_currency\n\n for line in self._get_lines_onchange_currency():\n new_currency = has_foreign_currency and self.currency_id\n line.currency_id = new_currency\n line._onchange_currency()\n else:\n self.line_ids._onchange_currency()\n\n self._recompute_dynamic_lines(recompute_tax_base_amount=True)\n\n\nclass AccountMoveLine(models.Model):\n _inherit = \"account.move.line\"\n\n #############################################################################################################\n # Se extiende esta funcion para el calculo de los asientos contables con la tasa reflejada\n # en la factura\n #############################################################################################################\n @api.model\n def _get_fields_onchange_subtotal_model(self, price_subtotal, move_type, currency, company, date):\n ''' This method is used to recompute the values of 'amount_currency', 'debit', 'credit' due to a change made\n in some business fields (affecting the 'price_subtotal' field).\n\n :param price_subtotal: The untaxed amount.\n :param move_type: The type of the move.\n :param currency: The line's currency.\n :param company: The move's company.\n :param date: The move's date.\n :return: A dictionary containing 'debit', 'credit', 'amount_currency'.\n '''\n if move_type in self.move_id.get_outbound_types():\n sign = 1\n elif move_type in self.move_id.get_inbound_types():\n sign = -1\n else:\n sign = 1\n price_subtotal *= sign\n\n if currency and currency != company.currency_id:\n # Multi-currencies.\n ###################################################################################\n if self.move_id and (self.move_id.partner_id.people_type_company == 'pjnd' or self.move_id.partner_id.people_type_individual == 'pnnr') and self.move_id.x_studio_field_TJfMu:\n balance = price_subtotal * self.move_id.x_studio_field_l5IHS\n else:\n balance = currency._convert(price_subtotal, company.currency_id, company, date)\n ####################################################################################\n return {\n 'amount_currency': price_subtotal,\n 'debit': balance > 0.0 and balance or 0.0,\n 'credit': balance < 0.0 and -balance or 0.0,\n }\n else:\n # Single-currency.\n return {\n 'amount_currency': 0.0,\n 'debit': price_subtotal > 0.0 and price_subtotal or 0.0,\n 'credit': price_subtotal < 0.0 and -price_subtotal or 0.0,\n }","repo_name":"AngelicaMeza/demostracion","sub_path":"catesco_locv_fixes/models/account_move.py","file_name":"account_move.py","file_ext":"py","file_size_in_byte":4517,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"48"} +{"seq_id":"73193392785","text":"from datetime import datetime, timedelta\nfrom pprint import pprint\n\nfrom data_manager import DataManager\nfrom flight_search import FlightSearch\n# from notification_manager import NotificationManager\nimport sheety\n\ndata_manager = DataManager()\nsheet_data = data_manager.get_destination_data()\nflight_search = FlightSearch()\n# notification_manager = NotificationManager()\n\nprint(\"Welcome to Yossi's Flight Club\")\nprint(\"We find the best deals and email you\")\nadd_user = input(\"Do you want to add a user? : (Y) or (N) : \").lower()\n\nif add_user == 'y' or add_user == 'yess':\n firstname = input(\"What is your first name?\").title()\n lastname = input(\"What is your last name?\").title()\n\n success = False\n\n while not success:\n email = input(\"What is your email? : \").lower()\n email_check = input(\"type your email again : \").lower()\n\n if email_check == email:\n sheety.post_new_row(firstname, lastname, email)\n success = True\n else:\n print(\"Emails did not match, please try again.\")\n\nORIGIN_CITY_IATA = \"LON\"\n\nif sheet_data[0][\"iataCode\"] == \"\":\n for row in sheet_data:\n row[\"iataCode\"] = flight_search.get_destination_code(row[\"city\"])\n data_manager.destination_data = sheet_data\n data_manager.update_destination_codes()\n\ntomorrow = datetime.now() + timedelta(days=1)\nsix_month_from_today = datetime.now() + timedelta(days=(6 * 30))\n\nfor destination in sheet_data:\n flight = flight_search.check_flights(\n ORIGIN_CITY_IATA,\n destination[\"iataCode\"],\n from_time=tomorrow,\n to_time=six_month_from_today\n )\n\n if flight is None:\n continue\n\n print(f\"{flight.destination_city} for £{flight.price}\")\n\n if flight.price < destination[\"lowestPrice\"]:\n message = f\"\"\" Low price alert! Only £{flight.price} to fly from {flight.origin_city}-{flight.origin_airport}\n to {flight.destination_city}-{flight.destination_airport},\n from {flight.out_date} to {flight.return_date}. \"\"\"\n\n if flight.stop_overs > 0:\n message += f\"\\nFlight has {flight.stop_overs} stop over, via {flight.via_city}.\"\n print(message)\n","repo_name":"yossiyanouhartman/python-100-day-coding-challenge","sub_path":"Day40_CheapFlightCompany/main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":2206,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"48"} +{"seq_id":"28766094451","text":"from typing import Any\n\nclass CompositeOp:\n ALPHA: int\n ATOP: int\n BLEND: int\n BLUR: int\n BUMPMAP: int\n CHANGE_MASK: int\n CLEAR: int\n COLORIZE: int\n COLOR_BURN: int\n COLOR_DODGE: int\n COPY: int\n COPY_ALPHA: int\n COPY_BLACK: int\n COPY_BLUE: int\n COPY_CYAN: int\n COPY_GREEN: int\n COPY_MAGENTA: int\n COPY_RED: int\n COPY_YELLOW: int\n DARKEN: int\n DARKEN_INTENSITY: int\n DIFFERENCE: int\n DISPLACE: int\n DISSOLVE: int\n DISTORT: int\n DIVIDE_DST: int\n DIVIDE_SRC: int\n DST: int\n DST_ATOP: int\n DST_IN: int\n DST_OUT: int\n DST_OVER: int\n EXCLUSION: int\n HARD_LIGHT: int\n HARD_MIX: int\n HUE: int\n IN: int\n INTENSITY: int\n LIGHTEN: int\n LIGHTEN_INTENSITY: int\n LINEAR_BURN: int\n LINEAR_DODGE: int\n LINEAR_LIGHT: int\n LUMINIZE: int\n MATHEMATICS: int\n MINUS_DST: int\n MINUS_SRC: int\n MODULATE: int\n MODULUS_ADD: int\n MODULUS_SUBTRACT: int\n MULTIPLY: int\n NO: int\n OUT: int\n OVER: int\n OVERLAY: int\n PEGTOP_LIGHT: int\n PINLIGHT: int\n PLUS: int\n REPLACE: int\n SATURATE: int\n SCREEN: int\n SOFT_LIGHT: int\n SRC: int\n SRC_ATOP: int\n SRC_IN: int\n SRC_OUT: int\n SRC_OVER: int\n THRESHOLD: int\n UNDEFINED: int\n VIVID_LIGHT: int\n XOR: int\n\nclass Gravity:\n CENTER: int\n EAST: int\n FORGET: int\n NORTH: int\n NORTH_EAST: int\n NORTH_WEST: int\n SOUTH: int\n SOUTH_EAST: int\n SOUTH_WEST: int\n UNDEFINED: int\n WEST: int\n\nclass MagickWand:\n def _raise_error(self, *argv) -> Any: ...\n def _set_image_depth(self, *argv) -> Any: ...\n def _set_image_format(self, *argv) -> Any: ...\n def _set_image_gravity(self, *argv) -> Any: ...\n def border_image(self, *argv) -> Any: ...\n def export_image_pixels(self, *argv) -> Any: ...\n def extent_image(self, *argv) -> Any: ...\n image_blob: Any\n image_depth: Any\n image_format: Any\n image_gravity: Any\n image_height: Any\n image_width: Any\n def read_image(self, *argv) -> Any: ...\n def write_image(self, *argv) -> Any: ...\n\nclass MagickWandError(Exception): ...\nclass PixelError(Exception): ...\n\nclass PixelWand:\n def _raise_error(self, *argv) -> Any: ...\n def _set_color(self, *argv) -> Any: ...\n def color(self, *argv) -> Any: ...\n\nclass StorageType:\n CHAR: int\n DOUBLE: int\n FLOAT: int\n LONG: int\n LONG_LONG: int\n QUANTUM: int\n SHORT: int\n UNDEFINED: int\n\n_border_image: Any\n_clear_exception: Any\n_destroy: Any\n_destroy_pixel_wand: Any\n_export_image_pixels: Any\n_extent_image: Any\n_genisis: Any\n_get_exception: Any\n_get_image_blob: Any\n_get_image_depth: Any\n_get_image_format: Any\n_get_image_gravity: Any\n_get_image_height: Any\n_get_image_width: Any\n_new: Any\n_new_pixel_wand: Any\n_pixel_clear_exception: Any\n_pixel_get_color: Any\n_pixel_get_exception: Any\n_pixel_set_color: Any\n_read_image: Any\n_relinquish_memory: Any\n_reset_iterator: Any\n_set_image_depth: Any\n_set_image_format: Any\n_set_image_gravity: Any\n_terminus: Any\n_wand: Any\n_write_image: Any\n\ndef bytearray_at() -> None: ...\ndef calcsize() -> None: ...\n\nffilib: Any\n\ndef unpack() -> None: ...\n","repo_name":"Josverl/micropython-stubs","sub_path":"stubs/ev3_pybricks_v1_0_0/pybricks/uev3dev/_wand.pyi","file_name":"_wand.pyi","file_ext":"pyi","file_size_in_byte":3182,"program_lang":"python","lang":"en","doc_type":"code","stars":90,"dataset":"github-code","pt":"48"} +{"seq_id":"26673478949","text":"# -*- coding: utf-8 -*-\n# @Time : 2018/3/15 23:12\n# @Author : play4fun\n# @File : tornado-async-spider.py\n# @Software: PyCharm\n\n\"\"\"\ntornado-async-spider.py:\n\"\"\"\n\n# coding=utf-8\n\"\"\"\ntornado异步爬虫示例\n\n\"\"\"\nimport time\nfrom datetime import timedelta\nfrom bs4 import BeautifulSoup\nfrom tornado.httpclient import AsyncHTTPClient\nfrom tornado import ioloop, gen, queues\n\n_q = queues.Queue()\n\n\n@gen.coroutine\ndef fetch(url):\n print('fetcing', url)\n response = yield AsyncHTTPClient().fetch(url, raise_error=False)\n\n #POST\n\n raise gen.Return(response)\n\n\n@gen.coroutine\ndef run():\n try:\n url = yield _q.get()\n res = yield fetch(url)\n html = res.body\n soup = BeautifulSoup(html, \"html.parser\")\n print(str(soup.find('title')))\n finally:\n _q.task_done()\n\n\n@gen.coroutine\ndef worker():\n while not _q.empty():\n yield run()\n\n\n@gen.coroutine\ndef main():\n for i in range(73000, 73100): # 放100个链接进去\n url = \"http://www.jb51.net/article/%d.htm\" % i\n yield _q.put(url)\n\n for _ in range(100): # 模拟100个线程\n worker()\n\n yield _q.join(timeout=timedelta(seconds=30))\n\n\nif __name__ == '__main__':\n s = time.time()\n ioloop.IOLoop.current().run_sync(main)\n print('use time:', time.time() - s)\n","repo_name":"19760909/Python_Master_Courses","sub_path":"网站开发/tornado/tornado-async-spider.py","file_name":"tornado-async-spider.py","file_ext":"py","file_size_in_byte":1309,"program_lang":"python","lang":"en","doc_type":"code","dataset":"github-code","pt":"48"} +{"seq_id":"41291797058","text":"import pygame\nimport numpy as np\nimport sys\nimport os\nimport math\nfrom pygame.locals import *\n\n#COLORES\nNEGRO = (0, 0, 0)\nBLANCO = (255, 255, 255)\nVERDE = ( 0, 255, 0)\nestado = None\nconector = None\nmodo = [1, 0] #0 Manual, 1. Automatico\nmodo_temp = [1, 0, 0] #0 No temp, 1 T-Temp, 2 P-Temp \nKEY_REPEAT_SETTING = (200,70)\n\nclass Propiedades(pygame.sprite.Sprite):\n\t\"\"\" La idea de esta clase es que recopile todo lo \n\trelacionado a las propiedades del software\"\"\"\n\tdef __init__(self, superficie):\n\t\tpygame.sprite.Sprite.__init__(self)\t\t\n\t\t#self.s_t = superficie_total # Define la superficie total de la interfaz\n\t\tself.rectangulo_trabajo = pygame.Rect(203, 76, 655, 530) # Rectangulo de trabajo\n\t\tself.area_trabajo = pygame.Surface((700, 580)); self.area_trabajo.fill(VERDE) # Superficie que contendra el area de trabajo\n\t\tself.fondo_dibujo = pygame.Surface((1250, 1110)); self.fondo_dibujo.fill(BLANCO)\n\t\tself.logo = pygame.image.load(os.path.join('Pictures', 'logo_u.png')) # Carga logo utp\n\t\tself.lista_barra = self.init_barra()\n\n\tdef init_barra(self): \n\t\t\"\"\"Inicializar propiedades para scroll pantalla principal\"\"\"\n\t\tlista_barra = list()\n\t\tdown = pygame.image.load(os.path.join('Pictures', 'down.png')) # elemento 0 de la lista\n\t\tdown_rect = down.get_rect() # elemento 5 de la lista\n\t\tdown_rect.center = (867.5, 592.5)\n\t\tup = pygame.image.load(os.path.join('Pictures', 'up.png')) # elemento 1 de la lista\n\t\tup_rect = up.get_rect() # elemento 6 de la lista\n\t\tup_rect.center = (867.5, 62.5)\n\t\tleft = pygame.image.load(os.path.join('Pictures', 'left.png')) # elemento 2 de la lista\n\t\tleft_rect = left.get_rect() # elemento 7 de la lista\n\t\tleft_rect.center = (192.5, 617.5)\n\t\tright = pygame.image.load(os.path.join('Pictures', 'right.png')) # elemento 3 de la lista\n\t\tright_rect = right.get_rect() # elemento 8 de la lista\n\t\tright_rect.center = (842.5, 617.5)\n\t\tplus = pygame.image.load(os.path.join('Pictures', 'plus.png')) # elemento 4 de la lista\n\t\tplus_rect = plus.get_rect() # elemento 9 de la lista\n\t\tplus_rect.center = (867.5, 617.5)\n\t\tlista_barra.append(down); lista_barra.append(up); lista_barra.append(left);lista_barra.append(right)\t\t\n\t\tlista_barra.append(plus)\n\t\tlista_barra.append(down_rect); lista_barra.append(up_rect); lista_barra.append(left_rect);lista_barra.append(right_rect)\t\t\n\t\tlista_barra.append(plus_rect)\n\n\t\tbarra_v = barra_v_1 = pygame.Surface((17, 505)) # elemento 10 y 11 de la lista\n\t\tbarra_v_rect = barra_v.get_rect() # elemento 12 de la lista\n\t\tbarra_v_rect.center = (867.5, 327.5)\n\t\tbarra_v.fill((0, 0, 0))\n\t\tfondo_barra_v = pygame.Surface((25, 505))\n\t\tfondo_barra_v.fill((118, 118, 118))\n\t\tlista_barra.append(barra_v); lista_barra.append(barra_v_1); lista_barra.append(barra_v_rect)\t\t\n\n\t\tbarra_h = barra_h_1 = pygame.Surface((625, 17)) # elemento 13 y 14 de la lista\n\t\tbarra_h_rect = barra_h.get_rect() # elemento 15 de la lista\n\t\tbarra_h_rect.center = (517.5, 617.5)\n\t\tbarra_h.fill((0, 0, 0))\n\t\tfondo_barra_h = pygame.Surface((625, 25))\n\t\tfondo_barra_h.fill((118, 118, 118))\n\t\tlista_barra.append(barra_h); lista_barra.append(barra_h_1); lista_barra.append(barra_h_rect)\n\t\tlista_barra.append(fondo_barra_v); lista_barra.append(fondo_barra_h) # elemento 16 y 17\t de la lista\n\n\t\treturn lista_barra\n\n\tdef dibujar_supercicies(self, superficie):\n\t\tfont = pygame.font.SysFont('Arial', 15)\t\n\t\tfont_2 = pygame.font.SysFont('Arial', 26)\n\t\tsuperficie.blit(self.logo, (30, 10))\n\t\tself.area_trabajo.blit(self.fondo_dibujo, (0, 0))\n\t\tsuperficie.blit(self.area_trabajo, (180, 50))\n\t\trectangulo_usuario = pygame.Rect(20, 120, 140, 370) # Rectangulo de panel\n\t\tpygame.draw.rect(superficie, NEGRO, rectangulo_usuario, 3)\n\t\trectangulo_acciones = pygame.Rect(20, 510, 140, 120) # Rectangulo de acciones\n\t\tpygame.draw.rect(superficie, NEGRO, rectangulo_acciones, 3)\n\t\t#Añadir etiqueas de elementos\n\t\tsuperficie.blit(font.render('Lugar', True, (0, 0, 0)), (75, 130))\n\t\tsuperficie.blit(font.render('Transición', True, (0, 0, 0)), (62, 230))\n\t\tsuperficie.blit(font.render('Arco', True, (0, 0, 0)), (78, 310))\n\t\tsuperficie.blit(font.render('Marca', True, (0, 0, 0)), (75, 415))\n\t\tsuperficie.blit(font_2.render('PiNet', True, (0, 0, 0)), (510, 16))\n\n\tdef dibujar_barra(self, superficie, desp):\n\t\tself.area_trabajo.blit(self.fondo_dibujo, (-desp[0], -desp[1])) # Area de trabajo\n\t\tself.area_trabajo.blit(self.lista_barra[4], (675, 555))\n\t\tself.area_trabajo.blit(self.lista_barra[2], (0, 555))\n\t\tself.area_trabajo.blit(self.lista_barra[3], (650, 555))\n\t\tself.area_trabajo.blit(self.lista_barra[1], (675, 0))\n\t\tself.area_trabajo.blit(self.lista_barra[0], (675, 530))\n\t\tself.area_trabajo.blit(self.lista_barra[16], (675, 25))\n\t\tself.area_trabajo.blit(self.lista_barra[10], (679, 25+desp[1]))\n\t\tself.area_trabajo.blit(self.lista_barra[17], (25, 555))\n\t\tself.area_trabajo.blit(self.lista_barra[13], (25+desp[0], 559))\n\t\tsuperficie.blit(self.area_trabajo, (180, 50))\n\t\tpygame.draw.rect(superficie, NEGRO, (180, 50, 700, 580), 3) # Rectangulo área de trabajo (fisico)\n\n\tdef acciones_barra(self, pos, desp, pasos, size_sheet, barra_actual, center_bar):\n\t\tif self.lista_barra[7].collidepoint(pos): # Presiona boton izquierda\n\t\t\tprint('left')\n\t\t\tif size_sheet >= 1 and pasos[0] > 0:\n\t\t\t\tdesp[0] -= 30\n\t\t\t\tpasos[0] -= 1\n\t\tif self.lista_barra[8].collidepoint(pos): # Presiona boton derecha\n\t\t\tprint('right')\n\t\t\tif size_sheet >= 1 and pasos[0] < size_sheet:\t\t\t\t\t\t\n\t\t\t\tdesp[0] += 30\n\t\t\t\tpasos[0] += 1\n\t\tif self.lista_barra[5].collidepoint(pos): # Presiona boton abajo\n\t\t\tprint('down')\n\t\t\tif size_sheet >= 1 and pasos[1] < size_sheet:\n\t\t\t\tdesp[1] += 24\n\t\t\t\tpasos[1] += 1\n\t\tif self.lista_barra[6].collidepoint(pos): # Presiona boton arriba\n\t\t\tprint('up')\n\t\t\tif size_sheet >= 1 and pasos[1] > 0:\n\t\t\t\tdesp[1] -= 24\n\t\t\t\tpasos[1] -= 1\n\t\tif self.lista_barra[9].collidepoint(pos):\n\t\t\tprint('plus')\n\t\t\tif size_sheet < 10: # Seaumenta máximo 10, osea el doble del área original\n\t\t\t\tbarra_actual[1] -= 24 # Aumento en vertical, se disminuye tamaño barra V\n\t\t\t\tbarra_actual[0] -= 30 # Aumento en horizontal, se disminuye tamaño barra H\n\t\t\t\tsize_sheet += 1 # Aumento de tamaño del área de trabajo\n\t\t\t\tcenter_bar[0] -= 5 \n\t\t\t\tcenter_bar[1] -= 5\n\t\t\tself.lista_barra[13] = pygame.transform.scale(self.lista_barra[14], (barra_actual[0], 17))\n\t\t\t#self.lista_barra[15] = self.lista_barra[13].get_rect()\n\t\t\t#self.lista_barra[15].center = (center_bar[0] , 385) # Barra H Rect\n\n\t\t\tself.lista_barra[10] = pygame.transform.scale(self.lista_barra[11], (17, barra_actual[1]))\n\t\t\t#self.lista_barra[12] = self.lista_barra[10].get_rect()\n\t\t\t#self.lista_barra[12].center = (385, center_bar[1]) # Barra V Rect\n\n\t\treturn barra_actual, size_sheet, desp, pasos\n\n\tdef cargar_play(self, pantalla): # Carga propiedades de la opcion play\n\t\tplay_e = pygame.image.load(os.path.join('Pictures', 'play_empty.png'))\n\t\tplay_f = pygame.image.load(os.path.join('Pictures', 'play_filled.png'))\n\t\tpause_e = pygame.image.load(os.path.join('Pictures', 'pause_empty.png'))\n\t\tpause_f = pygame.image.load(os.path.join('Pictures', 'pause_filled.png'))\n\t\tplay_rect = play_e.get_rect(center = (50, 545))\n\t\tplay_pos = pantalla.blit(play_e, play_rect)\n\t\treturn play_e, play_f, pause_e, pause_f, play_pos\n\n\tdef cargar_erase(self, pantalla): # Carga propiedades de la opcion erase\n\t\terase_e = pygame.image.load(os.path.join('Pictures', 'erase_empty.png'))\n\t\terase_f = pygame.image.load(os.path.join('Pictures', 'erase_filled.png'))\n\t\terase_rect = erase_e.get_rect(center = (115, 545))\n\t\terase_pos = pantalla.blit(erase_e, erase_rect)\n\t\treturn erase_e, erase_f, erase_pos\n\n\tdef cargar_set(self, pantalla): # Carga propiedades de la opcion set\n\t\tset_e = pygame.image.load(os.path.join('Pictures', 'set_empty.png'))\n\t\tset_f = pygame.image.load(os.path.join('Pictures', 'set_filled.png'))\n\t\tset_rect = set_e.get_rect(center = (50, 600))\n\t\tset_pos = pantalla.blit(set_e, set_rect)\n\t\treturn set_e, set_f, set_pos\n\n\tdef cargar_help(self, pantalla): # Carga propiedades de la opcion help\n\t\thelp_e = pygame.image.load(os.path.join('Pictures', 'help_empty.png'))\n\t\thelp_f = pygame.image.load(os.path.join('Pictures', 'help_filled.png'))\n\t\thelp_rect = help_e.get_rect(center = (115, 600))\n\t\thelp_pos = pantalla.blit(help_e, help_rect)\n\t\treturn help_e, help_f, help_pos\n\n\tdef propiedad_estado(self, pantalla, font, estado, modo_temp):\t# Sub ventana para las propiedades de los estados\n\t\tclose = pygame.image.load(os.path.join('Pictures', 'close.png'))\n\t\tif modo_temp == [0, 0, 1]:\n\t\t\tpanel = pygame.Surface((220, 200))\n\t\t\tpanel_personal = pygame.image.load(os.path.join('Pictures', 'panel_config.png'))\n\t\t\t#panel.blit(font.render('Tiempo: '+str(estado.time) + 'ms', True, (0, 0 , 0)), (20, 55))\t\n\t\telse:\n\t\t\tpanel = pygame.Surface((220, 130))\n\t\t\tpanel_personal = pygame.image.load(os.path.join('Pictures', 'panel_config2.png'))\n\t\tpanel.fill(BLANCO)\n\t\tpanel.blit(panel_personal, (0, 0))\n\t\tif estado.limite >= 100:\n\t\t\tlimite = 'infinito'\n\t\telse:\n\t\t\tlimite = estado.limite\n\t\tpanel.blit(font.render('Propiedades Lugar '+str(estado.tag), True, (255, 0 , 0)), (15, 10))\n\t\tpanel.blit(font.render('Limite de Tokens: '+str(limite), True, (0, 0 , 0)), (20, 35))\n\t\tpanel.blit(font.render('Tiempo: '+str(estado.time) + 'ms', True, (0, 0 , 0)), (20, 55))\t\n\t\tpanel.blit(font.render('Limite:', True, (0, 0 , 0)), (55, 100))\n\t\tif modo_temp == [0, 0, 1]:\n\t\t\tpanel.blit(font.render('Tiempo:', True, (0, 0 , 0)), (47, 140))\n\t\tpanel.blit(close, (180, 5))\n\t\tpantalla.blit(panel, (375, 190))\n\n\tdef propiedad_trans(self, pantalla, font, trans): # Sub ventana para las propiedades de las transiciones\n\t\t#close = pygame.image.load(os.path.join('Pictures', 'close.png'))\n\t\tpanel = pygame.Surface((300, 200))\n\t\tpanel_personal = pygame.image.load(os.path.join('Pictures', 'panel_config2.png'))\n\t\tpanel.fill(BLANCO)\n\t\tpanel.blit(panel_personal, (0, 0))\n\t\tpanel.blit(font.render('Propiedades Transición '+ str(trans.tag), True, (255, 0 , 0)), (15, 10))\n\t\tpanel.blit(font.render('Tiempo: '+str(trans.time) + \"ms\", True, (0, 0 , 0)), (20, 35))\n\t\tpanel.blit(font.render('Tiempo:', True, (0, 0 , 0)), (45, 80))\n\t\t#panel.blit(close, (100, 10))\n\t\tpantalla.blit(panel, (375, 210))\n\n\tdef propiedad_conexion(self, pantalla, font, conexion): # Sub ventana para las propiedades de las conexiones\n\t\t#close = pygame.image.load(os.path.join('Pictures', 'os.path.join(close.png'))\n\t\tpanel = pygame.Surface((220, 130))\n\t\tpanel_personal = pygame.image.load(os.path.join('Pictures', 'panel_config2.png'))\n\t\tpanel.fill(BLANCO)\n\t\tpanel.blit(panel_personal, (0, 0))\n\t\tpanel.blit(font.render('Propiedades Conexión entre lugar '+ str(conexion.interconectados[1]), True, (255, 0 , 0)), (6, 10))\n\t\tpanel.blit(font.render('y transición '+ str(conexion.interconectados[0]), True, (255, 0 , 0)), (6, 28))\n\t\tpanel.blit(font.render('Tokens actuales: '+str(conexion.token) , True, (0, 0 , 0)), (20, 45))\n\t\tpanel.blit(font.render('Tokens:', True, (0, 0 , 0)), (45, 80))\n\t\t#panel.blit(close, (100, 10))\n\t\tpantalla.blit(panel, (375, 210))\n\n\tdef configurar(self, pantalla, posi, modo, vel, delay_evo, modo_temp): # Sub ventana para configurar propiedades del sistema\n\t\t#Crear ventana de configuración\n\t\t#global modo\n\t\tfont = pygame.font.SysFont('Arial', 15)\t\n\t\tconfig = pygame.Surface((300, 300))\n\t\t#close = pygame.image.load(os.path.join('Pictures', 'close.png'))\n\t\tconfig_panel = pygame.image.load(os.path.join('Pictures', 'panel_config_1.png'))\n\t\tconfig_check_off = pygame.image.load(os.path.join('Pictures', 'check_off.png'))\n\t\tconfig_check_on = pygame.image.load(os.path.join('Pictures', 'check_on.png'))\n\t\trect_manual = config_check_off.get_rect()\n\t\trect_manual.center = (505, 270) # Checkbox manual\n\t\trect_auto = config_check_off.get_rect()\n\t\trect_auto.center = (505, 240) # Check automatico\n\t\trect_vel_1 = config_check_off.get_rect()\n\t\trect_vel_1.center = (585, 300) # Check 200ms\n\t\trect_vel_2 = config_check_off.get_rect()\n\t\trect_vel_2.center = (585, 320) # Check 500ms\n\t\trect_vel_3 = config_check_off.get_rect()\n\t\trect_vel_3.center = (585, 340) # Check 1s\n\t\trect_vel_4 = config_check_off.get_rect()\n\t\trect_vel_4.center = (585, 360) # Check 2s\n\t\trect_temp_no = config_check_off.get_rect()\n\t\trect_temp_no.center = (480, 410) # No_temp\n\t\trect_temp_t = config_check_off.get_rect()\n\t\trect_temp_t.center = (480, 430) # P_temp\n\t\trect_temp_p = config_check_off.get_rect()\n\t\trect_temp_p.center = (480, 450) # T_temp\n\t\tconfig_auto = pygame.image.load(os.path.join('Pictures', 'check_off.png'))\n\t\tconfig.fill(BLANCO)\n\t\tconfig.blit(config_panel, (0, 0))\n\t\tconfig.blit(font.render('Configuración', True, (255, 0 , 0)), (15, 10))\n\t\tconfig.blit(font.render('Automático', True, (0, 0 , 0)), (40,40))\n\t\tconfig.blit(font.render('Manual', True, (0, 0, 0)), (40, 70))\n\t\tconfig.blit(font.render('200ms', True, (0, 0, 0)), (160, 100))\n\t\tconfig.blit(font.render('500ms', True, (0, 0, 0)), (160, 120))\n\t\tconfig.blit(font.render('1s', True, (0, 0, 0)), (160, 140))\n\t\tconfig.blit(font.render('2s', True, (0, 0, 0)), (160, 160))\n\t\tconfig.blit(font.render('No-Temp', True, (0, 0 , 0)), (40, 210))\n\t\tconfig.blit(font.render('T-Temp', True, (0, 0 , 0)), (46,230))\n\t\tconfig.blit(font.render('P-Temp', True, (0, 0, 0)), (47, 250))\n\t\t#config.blit(close, (260, 8))\n\n\t\tif rect_auto.collidepoint(posi) or modo == [1, 0]: # Elegir modo automatico\n\t\t\tmodo = [1, 0]\t\t\n\t\t\tconfig.blit(config_check_on, (120, 40)) #Auto\n\t\t\tconfig.blit(config_check_off, (120, 70)) #Manual\n\t\t\tif rect_vel_1.collidepoint(posi) or vel == 1:\n\t\t\t\tconfig.blit(config_check_on, (200, 100)) #200ms\n\t\t\t\tconfig.blit(config_check_off, (200, 120)) #500ms\n\t\t\t\tconfig.blit(config_check_off, (200, 140)) #1s\n\t\t\t\tconfig.blit(config_check_off, (200, 160)) #2s\n\t\t\t\tvel = 1\n\t\t\t\tdelay_evo = 200\n\t\t\tif rect_vel_2.collidepoint(posi) or vel == 2:\n\t\t\t\tconfig.blit(config_check_off, (200, 100)) #200ms\n\t\t\t\tconfig.blit(config_check_on, (200, 120)) #500ms\n\t\t\t\tconfig.blit(config_check_off, (200, 140)) #1s\n\t\t\t\tconfig.blit(config_check_off, (200, 160)) #2s\n\t\t\t\tvel = 2\n\t\t\t\tdelay_evo = 500\n\t\t\tif rect_vel_3.collidepoint(posi) or vel == 3:\n\t\t\t\tconfig.blit(config_check_off, (200, 100)) #200ms\n\t\t\t\tconfig.blit(config_check_off, (200, 120)) #500ms\n\t\t\t\tconfig.blit(config_check_on, (200, 140)) #1s\n\t\t\t\tconfig.blit(config_check_off, (200, 160)) #2s\n\t\t\t\tvel = 3\n\t\t\t\tdelay_evo = 1000\n\t\t\tif rect_vel_4.collidepoint(posi) or vel == 4:\n\t\t\t\tconfig.blit(config_check_off, (200, 100)) #200ms\n\t\t\t\tconfig.blit(config_check_off, (200, 120)) #500ms\n\t\t\t\tconfig.blit(config_check_off, (200, 140)) #1s\n\t\t\t\tconfig.blit(config_check_on, (200, 160)) #2s\n\t\t\t\tvel = 4\n\t\t\t\tdelay_evo = 2000\n\n\t\t\tconfig.blit(font.render('Velocidad ejecución:', True, (0, 0, 0)), (40, 100))\n\n\t\t\tif rect_temp_no.collidepoint(posi)\tor modo_temp == [1, 0, 0]:\n\t\t\t\tconfig.blit(config_check_on, (95, 210)) #Manual\n\t\t\t\tconfig.blit(config_check_off, (95, 230)) #Auto\n\t\t\t\tconfig.blit(config_check_off, (95, 250)) #200ms\n\t\t\t\tmodo_temp = [1, 0, 0]\n\t\t\tif rect_temp_t.collidepoint(posi)\tor modo_temp == [0, 1, 0]:\n\t\t\t\tconfig.blit(config_check_off, (95, 210)) #Manual\n\t\t\t\tconfig.blit(config_check_on, (95, 230)) #Auto\n\t\t\t\tconfig.blit(config_check_off, (95, 250)) #200ms\n\t\t\t\tmodo_temp = [0, 1, 0]\n\t\t\tif rect_temp_p.collidepoint(posi)\tor modo_temp == [0, 0, 1]:\n\t\t\t\tconfig.blit(config_check_off, (95, 210)) #Manual\n\t\t\t\tconfig.blit(config_check_off, (95, 230)) #Auto\n\t\t\t\tconfig.blit(config_check_on, (95, 250)) #200ms\n\t\t\t\tmodo_temp = [0, 0, 1]\n\n\t\tif rect_manual.collidepoint(posi) or modo == [0, 1]:\t# Elegir modo automatico\n\t\t\tmodo = [0, 1]\n\t\t\tconfig.blit(config_check_on, (120, 70)) #Manual\n\t\t\tconfig.blit(config_check_off, (120, 40)) #Auto\n\t\t\tconfig.blit(config_check_off, (200, 100)) #200ms\n\t\t\tconfig.blit(config_check_off, (200, 120)) #500ms\n\t\t\tconfig.blit(config_check_off, (200, 140)) #1s\n\t\t\tconfig.blit(config_check_off, (200, 160)) #2s\n\t\t\tconfig.blit(config_check_off, (95, 210)) #Manual\n\t\t\tconfig.blit(config_check_off, (95, 230)) #Auto\n\t\t\tconfig.blit(config_check_off, (95, 250)) #200ms\n\t\t\tconfig.blit(font.render('Velocidad ejecución:', True, (128,128,128)), (40, 100))\t\n\n\t\tpantalla.blit(config, (375, 190))\n\t\treturn modo, vel, delay_evo, modo_temp\n\n\tdef show_structure(self, pantalla):\n\t\tmatrix_e = pygame.image.load(os.path.join('Pictures', 'matrix_empty.png'))\n\t\tmatrix_f = pygame.image.load(os.path.join('Pictures', 'matrix_filled.png'))\n\t\tchange_rect = matrix_e.get_rect(center = (530, 665))\n\t\tchange_pos = pantalla.blit(matrix_e, change_rect)\n\t\treturn matrix_e, matrix_f, change_pos\n\n\tdef show_proper(self, pantalla):\n\t\tproper_e = pygame.image.load(os.path.join('Pictures', 'proper_empty.png'))\n\t\tproper_f = pygame.image.load(os.path.join('Pictures', 'proper_filled.png'))\n\t\tproper_rect = proper_e.get_rect(center = (460, 665))\n\t\tproper_pos = pantalla.blit(proper_e, proper_rect)\n\t\treturn proper_e, proper_f, proper_pos\n\n\tdef show_trans(self, pantalla):\n\t\ttrans_e = pygame.image.load(os.path.join('Pictures', 'tree_empty.png'))\n\t\ttrans_f = pygame.image.load(os.path.join('Pictures', 'tree_filled.png'))\n\t\ttrans_rect = trans_e.get_rect(center = (590, 665))\n\t\ttrans_pos = pantalla.blit(trans_e, trans_rect)\n\t\treturn trans_e, trans_f, trans_pos\n\n\tdef save_load(self, pantalla):\n\t\tload_f = pygame.image.load(os.path.join('Pictures', 'load_filled.png'))\n\t\tload_e = pygame.image.load(os.path.join('Pictures', 'load_empty.png'))\n\t\tsave_f = pygame.image.load(os.path.join('Pictures', 'save_filled.png'))\n\t\tsave_e = pygame.image.load(os.path.join('Pictures', 'save_empty.png'))\n\t\tsave_rect = save_f.get_rect(center = (795, 30))\n\t\tsave_pos = pantalla.blit(save_f, save_rect)\n\t\tload_rect = load_f.get_rect(center = (840, 30))\n\t\tload_pos = pantalla.blit(load_f, load_rect)\n\t\treturn load_f, load_e, save_f, save_e, load_pos, save_pos\n\n\n","repo_name":"preacher6/PiNet","sub_path":"propiedades.py","file_name":"propiedades.py","file_ext":"py","file_size_in_byte":17587,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"48"} +{"seq_id":"24123474707","text":"import os\n\ndef busca_arquivo_rec(nome, dir):\n lista_dir = []\n lista_resp = []\n lista_dir.append(dir)\n \n while lista_dir:\n dir_atual = lista_dir[0]\n l = []\n try:\n l = os.listdir(dir_atual)\n except:\n pass\n for i in l:\n arq = os.path.join(dir_atual, i)\n if os.path.isfile(arq) and i == nome:\n lista_resp.append(arq)\n elif os.path.isdir(arq):\n lista_dir.append(arq)\n lista_dir.remove(dir_atual)\n return(lista_resp)\n\n\nnome_arq = input(\"Entre com o nome do arquivo: \")\nnome_dir = input(\"Entre com o nome do diretório: \")\n\nl = busca_arquivo_rec(nome_arq, nome_dir)\nprint(\"Diretório(s) onde\", nome_arq, \"foi(ram) encontrados(s):\")\nfor i in l:\n print(i)","repo_name":"marisoarsan/Fundamentos-Python","sub_path":"busca_arquivo_recursivo.py","file_name":"busca_arquivo_recursivo.py","file_ext":"py","file_size_in_byte":794,"program_lang":"python","lang":"pt","doc_type":"code","stars":0,"dataset":"github-code","pt":"48"} +{"seq_id":"23572683750","text":"from pathlib import Path\n\nimport click\nimport omegaconf\nimport torch\nimport torchvision.datasets\nimport tqdm\nfrom torch.utils.tensorboard import SummaryWriter\nfrom torchvision.transforms import ToTensor\n\nfrom utils.config import get_class_from_str\n\ndevice = \"cuda\"\n\n\nclass DatasetWrapper(torch.utils.data.Dataset):\n def __init__(self, dataset):\n self.dataset = dataset\n\n def __len__(self):\n return len(self.dataset)\n\n def __getitem__(self, index):\n x = self.dataset[index]\n image = x[0]\n if not isinstance(image, torch.Tensor):\n image = ToTensor()(image)\n return image, x[1]\n\n\ndef train(config_path, name, epochs, resume_from):\n run_path = f\"runs/{name}\"\n config = omegaconf.OmegaConf.load(config_path)\n\n tb_writer = SummaryWriter(run_path)\n model = get_class_from_str(config.model.target)(**config.model.params).to(device)\n diffusion = get_class_from_str(config.diffusion.target)(\n model, **config.diffusion.params\n ).to(device)\n\n opt = torch.optim.AdamW(diffusion.parameters(), lr=config.training.learning_rate)\n step = 0\n if resume_from is not None:\n print(f\"Resuming from {resume_from}\")\n checkpoint = torch.load(resume_from)\n diffusion.load_state_dict(checkpoint[\"model_state_dict\"], strict=False)\n opt.load_state_dict(checkpoint[\"optimizer_state_dict\"])\n step = checkpoint[\"step\"]\n\n for g in opt.param_groups:\n g[\"lr\"] = config.training.learning_rate\n\n print(\"creating dataset\")\n dataset = DatasetWrapper(\n get_class_from_str(config.data.target)(**config.data.params)\n )\n\n dataloader = torch.utils.data.DataLoader(\n dataset, batch_size=config.training.batch_size, shuffle=True, num_workers=4\n )\n print(\"training\")\n for epoch in range(epochs):\n tb_writer.add_scalar(\"epoch\", epoch, step)\n step = do_epoch(\n dataloader,\n diffusion,\n epoch,\n model,\n opt,\n run_path,\n step,\n config.training,\n tb_writer,\n )\n\n torch.save(\n {\n \"model_state_dict\": diffusion.state_dict(),\n \"optimizer_state_dict\": opt.state_dict(),\n \"step\": step,\n \"epoch\": epoch,\n },\n Path(run_path) / f\"diffusion_{step}.pt\",\n )\n\n\ndef do_epoch(\n dataloader, diffusion, epoch, model, opt, run_path, step, training_config, tb_writer\n):\n pbar = tqdm.tqdm(dataloader)\n for image, class_id in pbar:\n image = image.to(device)\n class_id = class_id.to(device)\n opt.zero_grad()\n if training_config.conditional:\n loss = diffusion(image, class_id)\n else:\n loss = diffusion(image)\n tb_writer.add_scalar(\"loss\", loss.item(), step)\n loss.backward()\n opt.step()\n pbar.set_description(f\"{step}: {loss.item():.4f}\")\n if step % 1000 == 0:\n sample(\n diffusion,\n model,\n step,\n training_config.conditional,\n class_id[0],\n tb_writer,\n )\n tb_writer.add_image(\"real_image\", (image[0] + 1) / 2, step)\n torch.save(\n {\n \"model_state_dict\": diffusion.state_dict(),\n \"optimizer_state_dict\": opt.state_dict(),\n \"step\": step,\n \"epoch\": epoch,\n },\n Path(run_path) / f\"diffusion_{step}.pt\",\n )\n step = step + 1\n return step\n\n\ndef sample(diffusion, model, step, conditional, class_id, tb_writer):\n\n model.eval()\n if conditional:\n generated = diffusion.p_sample_loop(\n (1, model.in_channels, *model.size), class_id=class_id[None]\n )\n else:\n generated = diffusion.p_sample_loop((1, model.in_channels, *model.size))\n generated = (generated + 1) / 2\n model.train()\n tb_writer.add_image(\"image\", torchvision.utils.make_grid(generated, nrow=3), step)\n\n\n@click.command()\n@click.option(\"--config\", \"-c\")\n@click.option(\"--name\", \"-n\")\n@click.option(\"--epochs\", \"-e\", default=500)\n@click.option(\"--resume-from\", \"-r\", default=None)\ndef main(config: str, name: str, resume_from: str, epochs: int):\n train(config, name, epochs, resume_from)\n\n\nif __name__ == \"__main__\":\n main()\n","repo_name":"luc-leonard/pytorch-diffusion-autoencoder","sub_path":"scripts/train.py","file_name":"train.py","file_ext":"py","file_size_in_byte":4435,"program_lang":"python","lang":"en","doc_type":"code","stars":9,"dataset":"github-code","pt":"48"} +{"seq_id":"29114567956","text":"import pandas as pd\nimport xlwings as xw\n\nxlapp = xw.apps.active\nrng = xlapp.selection\ndp = pd.DataFrame(rng.options(pd.DataFrame, header=1, index=False).value)\n\ndf = dp.fillna(0)\n\n\nprint(df.shape)\nprint(df.dtypes)\n","repo_name":"dbmats/TestPr","sub_path":"1сбор2.py","file_name":"1сбор2.py","file_ext":"py","file_size_in_byte":215,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"48"} +{"seq_id":"19029714829","text":"# За день машина проезжает n километров. Сколько дней нужно,\n# чтобы проехать маршрут длиной m километров?\n# При решении этой задачи нельзя пользоваться условной инструкцией if и циклами.\n\n# Input:\n# n = 700\n# m = 750\n# Output:\n# 2\n# ------------------------------------------------------------------------------\n\nn = int(input(\"Введите расстояние за день (км): \"))\nm = int(input(\"Введите длину маршрута (км): \"))\n\n# import math\n# result = math.ceil(m / n)\n\n# result = m // n + (m % n != 0) # Булево выражение добавляет к результату единицу, если True.\n\nresult = (m + n - 1) // n\n\nprint(f\"-> Количество дней, требуемое для прохождения маршрута: {result}\")\n","repo_name":"kask1n/Py_Introduction","sub_path":"Py_Seminar1_Classwork/Py_Task1/main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":943,"program_lang":"python","lang":"ru","doc_type":"code","stars":0,"dataset":"github-code","pt":"48"} +{"seq_id":"32400389356","text":"#!/usr/bin/env python\n# Requires the pigpio daemon to be running:\n# sudo pigpiod\n\nfrom evdev import InputDevice, categorize, ecodes\nimport time\nimport pigpio\n\nSERVO = 13\npi = pigpio.pi()\n\nprint('calibrating at 1500 PWM ..')\npi.set_servo_pulsewidth(SERVO, 1500)\ntime.sleep(3)\n\nprint('calibration done.')\n\ngamepad = InputDevice('/dev/input/event7')\nprint(gamepad)\n\nfor event in gamepad.read_loop():\n if event.type == ecodes.EV_KEY:\n catEvent = categorize(event)\n #print(event)\n #print('======')\n #print(categorize(event))\n #print('>>>>>>>>>>>>>')\n if event.code == ecodes.ecodes['BTN_SOUTH']:\n if catEvent.keystate == catEvent.key_down:\n print('X pressed!')\n pi.set_servo_pulsewidth(SERVO, 1300)\n else:\n print('X released')\n pi.set_servo_pulsewidth(SERVO, 1500)\n elif event.code == ecodes.ecodes['BTN_NORTH']:\n if catEvent.keystate == catEvent.key_down:\n print('TRIANGLE pressed!')\n pi.set_servo_pulsewidth(SERVO, 1700)\n else:\n print('TRIANGLE released')\n pi.set_servo_pulsewidth(SERVO, 1500)\n elif event.code == ecodes.ecodes['BTN_TR2']:\n print('R2 pressed, escaping ..')\n break\n\n\nprint('stopping pulses ..')\npi.set_servo_pulsewidth(SERVO, 0)\npi.stop()\ntime.sleep(1)\n","repo_name":"sbkn/psControlledTank","sub_path":"digital_test.py","file_name":"digital_test.py","file_ext":"py","file_size_in_byte":1411,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"48"} +{"seq_id":"38732310413","text":"user = input(\"Write numbers (example : 1,2,2,5): \")\nnumbers = user.split(\",\")\n\ntry:\n for number in numbers:\n numbers[numbers.index(number)] = int(number)\n\n my_set = set(numbers)\n print(my_set)\n \nexcept:\n print(\"bad data\")","repo_name":"emnakdg/lab3","sub_path":"lab3-3.py","file_name":"lab3-3.py","file_ext":"py","file_size_in_byte":243,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"48"} +{"seq_id":"73411987987","text":"import logging\nimport collections\nimport os\nimport sys\n\nclass Plugin(object):\n '''Base class for all plugins\n to create a plugin, subclass this and place in the plugins\n directory.'''\n\n enabled = True # Set to false in subclasses to disable that plugin\n\n def activate(self):\n '''Called after plugin is loaded but before added to event\n loop'''\n pass\n\n def deactivate(self):\n '''Called before plugin is unloaded'''\n pass\n\nclass PluginLoader(object):\n def __init__(self, plugins_dir, parent_class=Plugin,\n init_args=(), init_kwargs={}):\n self.plugins_dir = plugins_dir\n self.parent_class = parent_class\n if self.plugins_dir[-1:] != '/':\n self.plugins_dir += '/'\n self.plugins = collections.deque()\n self.modules = collections.deque()\n self.init_args = init_args\n self.init_kwargs = init_kwargs\n\n def load_all(self):\n logging.debug('Starting plugin loading')\n plugins_dir = os.listdir(self.plugins_dir)\n found_driver = False\n if self.plugins_dir not in sys.path:\n sys.path.insert(0, self.plugins_dir)\n for poss_plugin in plugins_dir:\n full_path = self.plugins_dir + poss_plugin\n if poss_plugin[-3:] == '.py':\n logging.debug('loading %s' % full_path)\n module=__import__(poss_plugin[:-3])\n mod_dict = module\n elif os.path.isdir(full_path) and os.path.isfile(full_path+'/__init__.py'):\n module=__import__(poss_plugin)\n mod_dict = module\n else:\n logging.debug('skipping %s due to invalid path (No __init__.py or not .py)' % full_path)\n continue\n mod_dict = mod_dict.__dict__\n for key, value in mod_dict.items():\n try:\n is_subclass = issubclass(value, self.parent_class)\n except TypeError:\n continue\n if is_subclass:\n try:\n enabled = value.enabled\n except AttributeError:\n enabled = True\n\n if enabled:\n logging.debug('Initializing %s' % value.__name__)\n instance = value(*self.init_args, **self.init_kwargs)\n instance.activate()\n self.modules.append(module)\n self.plugins.append(instance)\n else:\n logging.debug('Skipping %s, not enabled' % value.__name__)\n\n logging.debug('Finished plugin loading')\n\n","repo_name":"greghaynes/SSPPS","sub_path":"sspps/__init__.py","file_name":"__init__.py","file_ext":"py","file_size_in_byte":2703,"program_lang":"python","lang":"en","doc_type":"code","stars":7,"dataset":"github-code","pt":"48"} +{"seq_id":"30303469859","text":"import wx, itertools, math\r\n\r\nphi = (math.sqrt(5) - 1) / 2\r\n\r\nclass paintPanel(wx.Panel):\r\n\tdef disectRect(self, weight, l, t, r, b, weightacc=None):\r\n\t\tw, h = r - l, b - t\r\n\t\tif len(weight) == 1:\r\n\t\t\treturn [(l, t, w, h)], w + h\r\n\t\telse:\r\n\t\t\tweightAcc = list(itertools.accumulate(weight)) if weightacc is None else weightacc\r\n\t\t\twtSum = weightAcc[-1]\r\n\t\t\ttarSplit = min(w, h) / max(w, h) * phi * wtSum\r\n\t\t\tidxSplit = min(min(enumerate(weightAcc), key=lambda x: abs(x[1] - tarSplit))[0] + 1, len(weight) - 1)\r\n\t\t\twtSplit = weightAcc[idxSplit - 1]\r\n\t\t\ts, v = [[0, 0], [0, 0]], [[0, 0], [0, 0]]\r\n\t\t\tfor i in range(2):\r\n\t\t\t\tif i == 0:\r\n\t\t\t\t\tpos = l + w * wtSplit // wtSum\r\n\t\t\t\t\trectl, rectr = (l, t, pos, b), (pos, t, r, b)\r\n\t\t\t\telse:\r\n\t\t\t\t\tpos = t + h * wtSplit // wtSum\r\n\t\t\t\t\trectl, rectr = (l, t, r, pos), (l, pos, r, b)\r\n\t\t\t\ts[i][0], v[i][0] = self.disectRect(weight[:idxSplit], *rectl, weightAcc[:idxSplit])\r\n\t\t\t\ts[i][1], v[i][1] = self.disectRect(weight[idxSplit:], *rectr, [x - wtSplit for x in weightAcc[idxSplit:]])\r\n\t\t\tsv = [sum(x) for x in v]\r\n\t\t\treturn itertools.chain(*s[0 if sv[0] < sv[1] else 1]), min(sv)\r\n\t\r\n\tdef __init__(self, parent):\r\n\t\tsuper(paintPanel, self).__init__(parent)\r\n\t\tself.SetBackgroundStyle(wx.BG_STYLE_CUSTOM)\r\n\t\tself.SetBackgroundColour(wx.WHITE)\r\n\t\tfor x in ['PAINT', 'SIZE']:\r\n\t\t\texec('self.Bind(wx.EVT_{}, self.on{})'.format(*([x] * 2)))\r\n\t\tself.weights = [2,4,6,8,10]\r\n\t\tself.weights.sort(reverse=True)\r\n\t\r\n\tdef onSIZE(self, event):\r\n\t\tevent.Skip()\r\n\t\tself.Refresh()\r\n\t\r\n\tdef onPAINT(self, event):\r\n\t\tw, h = self.GetClientSize()\r\n\t\tdc = wx.AutoBufferedPaintDC(self)\r\n\t\tdc.Clear()\r\n\t\ts, v = self.disectRect(self.weights, 10, 10, w - 20, h - 20)\r\n\t\tfor x in s:\r\n\t\t\tprint('Draw: l={}, t={}, w={}, h={}'.format(*x))\r\n\t\t\tdc.DrawRectangle(*x)\r\n\r\nclass inputPanel(wx.Panel):\r\n\tdef __init__(self, parent):\r\n\t\tsuper(inputPanel, self).__init__(parent)\r\n\t\tself.sizer = wx.BoxSizer(wx.HORIZONTAL)\r\n\t\tself.txtInput = wx.TextCtrl(self)\r\n\t\tself.txtInput.SetValue('2,4,6,8,10')\r\n\t\tself.btnUpdate = wx.Button(self, label='Update')\r\n\t\tself.btnUpdate.SetDefault()\r\n\t\tself.btnUpdate.Bind(wx.EVT_BUTTON, self.onUpdate)\r\n\t\tself.sizer.Add(self.txtInput, 1, wx.ALIGN_CENTER | wx.EXPAND)\r\n\t\tself.sizer.Add(self.btnUpdate, 0, wx.ALIGN_CENTER)\r\n\t\tself.SetSizer(self.sizer)\r\n\t\tself.Fit()\r\n\t\r\n\tdef onUpdate(self, event):\r\n\t\ttry:\r\n\t\t\tself.rootFrame.paintPanel.weights = list(map(int, self.txtInput.GetValue().split(',')))\r\n\t\t\tself.rootFrame.paintPanel.weights.sort(reverse=True)\r\n\t\t\tself.rootFrame.paintPanel.Refresh()\r\n\t\texcept:\r\n\t\t\tprint('?')\r\n\r\nclass mainFrame(wx.Frame):\r\n\tdef __init__(self):\r\n\t\tsuper(mainFrame, self).__init__(None)\r\n\t\tself.SetTitle('phi disect')\r\n\t\tself.SetClientSize((500, 600))\r\n\t\tself.splitter = wx.SplitterWindow(self, style=wx.SP_BORDER)\r\n\t\tfor x in ['paintPanel', 'inputPanel']:\r\n\t\t\texec('self.{} = {}(self.splitter); self.{}.rootFrame = self'.format(*([x] * 3)))\r\n\t\tself.splitter.SplitHorizontally(self.paintPanel, self.inputPanel, -30)\r\n\t\tself.splitter.SetSashGravity(1)\r\n\r\ndef main():\r\n\tapp = wx.App(False)\r\n\tframe = mainFrame()\r\n\tframe.Show()\r\n\tapp.MainLoop()\r\n\r\nif __name__ == '__main__':\r\n\tmain()\r\n","repo_name":"pandogozilla/playground","sub_path":"phi_rect_disect-ar.py","file_name":"phi_rect_disect-ar.py","file_ext":"py","file_size_in_byte":3141,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"48"} +{"seq_id":"71375724307","text":"# using the snake.py in this reposotory i want to create a neural network that will control the snake and try to get the highest score possible\n\n\n# Path: genetic_snake.py\n# Compare this snippet from snake.py:\n\nimport random\nimport snake\nimport pygame\nimport math\nimport numpy as np\ndef fitness(snake):\n return snake.score\n\ndef crossover(parent1, parent2):\n child = snake.Snake()\n child.brain = parent1.brain + parent2.brain\n return child\n\ndef mutate(child):\n child.brain = child.brain + np.random.normal(0, 0.1, child.brain.shape)\n return child\n\ndef selection(population):\n fitnesses = [fitness(snake) for snake in population]\n total_fitness = sum(fitnesses)\n probs = [f/total_fitness for f in fitnesses]\n parents = np.random.choice(population, 2, p=probs, replace=False)\n return parents\n\ndef next_generation(population):\n new_population = []\n for i in range(len(population)):\n parents = selection(population)\n child = crossover(parents[0], parents[1])\n child = mutate(child)\n new_population.append(child)\n return new_population\n\ndef main():\n population = [snake.Snake() for i in range(100)]\n for generation in range(100):\n for snake in population:\n snake.play()\n population = next_generation(population)\n print(fitness(population[0]))\n\nif __name__ == \"__main__\":\n main()\n\n","repo_name":"filippovicidomini/GeneticAI-snake","sub_path":"genetic_snake.py","file_name":"genetic_snake.py","file_ext":"py","file_size_in_byte":1384,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"48"} +{"seq_id":"16948469838","text":"\"\"\"\nTitle: triggered\nDate: 20181008\nAuthor: epi \n https://epi052.gitlab.io/notes-to-self/\nTested on: \n linux/i686 4.15.0-041500-generic #201802011154 \n Python 3.5.2 \n pyinotify 0.9.6\n\"\"\"\nimport os\nimport time\nimport tarfile\nimport argparse\nimport itertools\n\nfrom pathlib import Path\nfrom datetime import datetime\n\nimport pyinotify\n\nMY_TMP_DIR = Path('/tmp')\nCURRENT_YEAR = datetime.now().year\n\n\ndef spin(secs: int) -> None:\n \"\"\" Simple spinner, because why not.\n\n Args:\n secs: Number of seconds to spin\n \"\"\"\n clock_intervals = ['b', 'd', 'p', 'q']\n spinner = itertools.cycle(clock_intervals)\n speed = 0.1\n counter = 0\n while counter < secs:\n print(next(spinner), end='')\n time.sleep(speed)\n print(flush=True, end='')\n print('\\b', end='')\n counter += speed\n\n\ndef exclude_empty(path: str) -> bool:\n \"\"\" Helper for exclude keyword used when creating a tarfile.\n\n When called, if result is True, that directory is ignored by tarfile.\n\n Args:\n path: Filename to check for exclusion from tarfile\n\n Returns:\n bool\n \"\"\"\n return str(path).endswith('.empty')\n\n\nclass EventHandler(pyinotify.ProcessEvent):\n \"\"\"\n Handles notifications and takes actions through specific processing methods.\n For an EVENT_TYPE, a process_EVENT_TYPE function will execute.\n \"\"\"\n def __init__(self, *args, **kwargs):\n super().__init__(*args, **kwargs)\n\n self.tarball_name = \"\"\n self.used_files = dict()\n self.to_read = kwargs.get(\"to_read\")\n\n print('[+] Files to read:')\n for file_to_read in self.to_read:\n print('[-] {}'.format(file_to_read))\n print()\n\n def process_IN_CLOSE_WRITE(self, event: pyinotify.Event) -> None:\n \"\"\" Handles event produced when a file that was opened for writing is closed.\n\n This function is designed to trigger on the creation of the tarball generated by /usr/sbin/backuperer\n\n Args:\n event: pyinotify.Event\n \"\"\"\n file = Path(event.pathname)\n\n if not file.is_file():\n return\n\n try:\n tf = tarfile.open(str(file))\n except tarfile.ReadError as e:\n return print(\"{}: {}\".format(file, e))\n\n # if we reach this point, we have a legitimate tarball and can proceed\n print(\"[+] Tarball created by /usr/sbin/backuperer\")\n print(\"[-] {}\".format(file), end='\\n\\n')\n\n os.chdir(str(MY_TMP_DIR)) # ease tar creation later on\n self.tarball_name = str(file) # store for reference when processing the error_log modified event later on\n\n # extract the backup made by /usr/sbin/backuperer to /tmp; result /tmp/var...\n for tarred_file in tf:\n try:\n tf.extract(tarred_file)\n except IOError as e:\n # there's a file with weird perms, just skipping it\n # var/www/html/webservices/monstra-3.0.4/public/uploads/.empty\n pass\n else:\n os.chmod(tarred_file.name, tarred_file.mode)\n\n print('[+] Files from {} extracted'.format(file), end='\\n\\n')\n\n tmp_var = MY_TMP_DIR / 'var' / 'www' / 'html' / 'webservices'\n real_files = tmp_var.glob('**/*.*') # recursive listing of the extracted files (/tmp/var/www/html/webservices...)\n\n for file_to_read in self.to_read:\n file_to_overwrite = next(real_files) # get file/folder in the backup\n\n while not file_to_overwrite.is_file():\n # iterate over files/folders in the backup until we get an actual file\n try:\n file_to_overwrite = next(real_files)\n except StopIteration:\n return print('No (more?) files to overwrite')\n\n # file_to_overwrite should be something like /tmp/var/www/html/index.html\n\n # strip leading /tmp before appending for printing from error log later\n self.used_files[str(file_to_overwrite).replace('/tmp', '', 1)] = str(file_to_read)\n\n print('[+] Found file to overwrite: {}'.format(file_to_overwrite))\n file_to_overwrite.unlink()\n\n print('[-] Linking {} to {}'.format(file_to_overwrite, file_to_read))\n file_to_overwrite.symlink_to(file_to_read)\n\n print('[-] All files to be read are linked.', end='\\n\\n')\n\n print('[+] Tarring up the altered backup.')\n new_tf = tarfile.open(str(file), mode='w:gz')\n new_tf.add('var', exclude=exclude_empty)\n print('[-] Tarball {} created.'.format(str(file)), end='\\n\\n')\n\n def process_IN_MODIFY(self, event):\n \"\"\" Handles event produced when a file is modified.\n\n This function is designed to trigger when /var/backups/onuma_backup_error.txt is appended to.\n\n Args:\n event: pyinotify.Event\n \"\"\"\n print('[+] Error log modified, checking results.', end='\\n\\n')\n\n # the error log gets modified first with the timestamp, then with the diff; we sleep to wait for the diff to\n # complete or we may lose some entries\n spin(secs=10)\n most_recent = False\n\n with open(event.pathname, encoding='utf-8') as f:\n for i, line in enumerate(f):\n if not most_recent and line.startswith(self.tarball_name):\n # found line with backup name, everything below is our diff\n most_recent = True\n elif most_recent:\n if line.startswith('diff -r'):\n diff_line = line.split() # grab /var/www/html/index.html or similar\n if diff_line[2] in self.used_files: # lookup what we linked in its place\n print('\\n[+] {}'.format(self.used_files.get(diff_line[2])))\n elif line.startswith('> ') and 'while(c--)' not in line: # ugly javascript block filtered out\n print(line.replace('> ', '', 1), end='')\n raise SystemExit # we out\n\n\ndef main(args_ns):\n wm = pyinotify.WatchManager()\n\n handler = EventHandler(to_read=args_ns.to_read)\n\n notifier = pyinotify.Notifier(wm, handler)\n\n wm.add_watch(args_ns.to_watch, pyinotify.IN_CLOSE_WRITE) # for altering tarball\n wm.add_watch('/var/backups/onuma_backup_error.txt', pyinotify.IN_MODIFY) # for reading error_log\n\n notifier.loop()\n\n\nif __name__ == '__main__':\n parser = argparse.ArgumentParser()\n parser.add_argument('--to_read', nargs='*', help=\"Space separated list of file names to be read from the diff\", required=True)\n parser.add_argument('to_watch', help='Directory to watch for events')\n\n args = parser.parse_args()\n main(args)\n","repo_name":"epi052/htb-scripts-for-retired-boxes","sub_path":"tartarsauce/triggered/__main__.py","file_name":"__main__.py","file_ext":"py","file_size_in_byte":6751,"program_lang":"python","lang":"en","doc_type":"code","stars":20,"dataset":"github-code","pt":"48"} +{"seq_id":"36459026457","text":"# -*- coding: utf-8 -*-\n\nfrom setuptools import setup, find_packages\n\n\nwith open('README.md') as f:\n readme = f.read()\n\nwith open('LICENSE') as f:\n license = f.read()\n\nsetup(\n name='bumblebees_track',\n version='0.1.0',\n description='tracking bumblebees through detecting the light spot on images',\n long_description=readme,\n author='Chunyu Deng',\n author_email='cdeng5@sheffield.ac.uk',\n url='https://github.com/dcyril233/bumblebees-track',\n license=license,\n packages=find_packages(exclude=('tests', 'docs'))\n)","repo_name":"dcyril233/bumblebees_track","sub_path":"setup.py","file_name":"setup.py","file_ext":"py","file_size_in_byte":544,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"48"} +{"seq_id":"4434167654","text":"depths = []\nwindows = []\n\n### Part 1\n# function for counting increases\ndef count_increases(list):\n count = 0\n for i in range(len(list)):\n if i != 0:\n if list[i] > list[i-1]:\n count+= 1\n return count\n\n# read in sonar depths\nwith open(\".\\day1.txt\", \"r\") as f:\n for line in f:\n depths.append(int(line.rstrip()))\n\nprint(count_increases(depths))\n\n### Part 2\n# Creating windows\nfor i in range(len(depths)):\n if i + 2 < len(depths):\n window = depths[i] + depths[i+1] + depths[i+2]\n windows.append(window)\n\nprint(count_increases(windows))\n","repo_name":"stewajam98/Advent-Of-Code","sub_path":"2021/Day 1/day1.py","file_name":"day1.py","file_ext":"py","file_size_in_byte":600,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"48"} +{"seq_id":"4652253942","text":"T = int(input())\ngrade = ['A+', 'A0', 'A-', 'B+', 'B0', 'B-', 'C+', 'C0', 'C-', 'D0']\nfor tc in range(1, T+1):\n N, K = map(int, input().split())\n scores = [list(map(int, input().split())) for _ in range(N)]\n credit = []\n for i in range(N):\n credit.append(scores[i][0] * 0.35 + scores[i][1] * 0.45 + scores[i][2] * 0.2)\n k_credit = credit[K-1]\n credit.sort(reverse=True)\n k_idx = credit.index(k_credit)\n res = grade[k_idx//(N//10)]\n print(f'#{tc} {res}')\n ","repo_name":"Amyhds/codingtest","sub_path":"SWEA/D2/1983. 조교의 성적 매기기/조교의 성적 매기기.py","file_name":"조교의 성적 매기기.py","file_ext":"py","file_size_in_byte":496,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"48"} +{"seq_id":"1109897935","text":"# https://www.kaggle.com/cpmpml/spell-checker-using-word2vec\n# simplified and fast spell correction\n\nimport os\nimport numpy as np\nfrom gensim.models import KeyedVectors\nfrom gensim.scripts.glove2word2vec import glove2word2vec\nfrom gensim.models.word2vec import Word2Vec\n\n###########################################\n### Fast spelling (faster and more flexible than Textblob and Pyspellchecking)\n### Allow to use dictionary imported from different pretrained models:\n### GoogleNews, Glove, Twitter, Wiki, etc\n### Supported formats: .vec, .txt, .bin.gz\n###########################################\n\nclass FastSpelling():\n def __init__(self, input_file):\n \n # convert to gensim file\n if input_file.endswith('.txt'):\n output_text = input_file + '.gensim'\n if not os.path.isfile(output_text):\n print('generating .gensim file ...')\n glove2word2vec(glove_input_file=input_file, word2vec_output_file= output_text) \n print('loading vocabulary of pretrained model ...')\n self.model = KeyedVectors.load_word2vec_format(output_text)\n\n elif input_file.endswith('.vec'):\n # convert to '.bin' file to reduce file size\n output_text = input_file + '.bin'\n if not os.path.isfile(output_text):\n print('generating .bin file ...')\n vec_model = KeyedVectors.load_word2vec_format(input_file, binary=False)\n vec_model.save_word2vec_format(output_text, binary=True)\n print('loading vocabulary of pretrained model ...')\n self.model = KeyedVectors.load_word2vec_format(output_text, binary=True)\n\n elif input_file.endswith('.bin.gz'):\n output_text = input_file\n print('loading vocabulary of pretrained model ...')\n self.model = KeyedVectors.load_word2vec_format(output_text, binary=True)\n\n # build vocabulary \n self.words = self.model.index2word\n self.WORDS = dict((word, i) for i,word in enumerate(self.words))\n print('Vocabulary built')\n\n # Spelling correction engine\n def correction(self, word): \n \"Most probable spelling correction for word.\"\n return max(self.candidates(word), key=self.P)\n\n def P(self, word):\n \"Probability of `word`.\"\n # use inverse of rank as proxy\n # returns 0 if the word isn't in the dictionary\n return - self.WORDS.get(word, 0)\n\n def candidates(self, word): \n \"Generate possible spelling corrections for word.\"\n return (self.known([word]) or self.known(self.edits1(word)) \\\n or self.known(self.edits2(word)) or [word])\n\n def known(self, words): \n \"The subset of `words` that appear in the dictionary of WORDS.\"\n return set(w for w in words if w in self.WORDS)\n\n def edits1(self, word):\n \"All edits that are one edit away from `word`.\"\n letters = 'abcdefghijklmnopqrstuvwxyz'\n splits = [(word[:i], word[i:]) for i in range(len(word) + 1)]\n deletes = [L + R[1:] for L, R in splits if R]\n transposes = [L + R[1] + R[0] + R[2:] for L, R in splits if len(R)>1]\n replaces = [L + c + R[1:] for L, R in splits if R for c in letters]\n inserts = [L + c + R for L, R in splits for c in letters]\n return set(deletes + transposes + replaces + inserts)\n\n def edits2(self, word): \n \"All edits that are two edits away from `word`.\"\n return (e2 for e1 in self.edits1(word) for e2 in self.edits1(e1))\n\n###############################################\n#### LOAD EMBEDDING MATRIX\n#### Supported formats: .vec, .txt, .bin.gz\n#### Allows to load embedding matrix of:\n#### GoogleNews, GLOVE, Twitter, Wiki\n###############################################\n\ndef get_embedding(pretrained_model, vocab2index):\n initial_word_vector_dim = pretrained_model['init_dimension']\n input_file = pretrained_model['file']\n\n word_vec = Word2Vec(size=initial_word_vector_dim, min_count=1)\n word_vec.build_vocab([[word] for word in vocab2index.keys()])\n\n # read input file using gensim\n if input_file.endswith('.txt'):\n output_text = input_file + '.gensim'\n if not os.path.isfile(output_text):\n print('generating .gensim file ...')\n glove2word2vec(glove_input_file=input_file, word2vec_output_file= output_text)\n print('matching vocabulary with pretrained vocabulary ...')\n word_vec.intersect_word2vec_format(output_text, binary=False, lockf=1.0)\n \n elif input_file.endswith('.vec'):\n # convert to '.bin' file to reduce file size\n vec_bin_file = input_file + '.bin'\n if not os.path.isfile(vec_bin_file):\n print('generating .bin file ...')\n vec_model = KeyedVectors.load_word2vec_format(input_file, binary=False)\n vec_model.save_word2vec_format(vec_bin_file, binary=True)\n print('matching vocabulary with pretrained vocabulary ...')\n word_vec.intersect_word2vec_format(vec_bin_file, binary=True)\n \n elif input_file.endswith('.bin.gz'):\n vec_bin_file = input_file\n print('matching vocabulary with pretrained vocabulary ...')\n word_vec.intersect_word2vec_format(vec_bin_file, binary=True)\n \n # load embedding matrix\n embedding = word_vec.wv.syn0\n # add zero vector (for padding special token)\n pad_vec = np.zeros((1,initial_word_vector_dim))\n embedding = np.insert(embedding, 0,pad_vec,0)\n # add Gaussian initialized vector (for OOV special token)\n oov_vec = np.random.normal(size= initial_word_vector_dim) \n embedding = np.insert(embedding,0,oov_vec,0)\n print('embedding loaded')\n return embedding","repo_name":"6Ulm/Basic-NLP","sub_path":"PretrainedModel.py","file_name":"PretrainedModel.py","file_ext":"py","file_size_in_byte":5776,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"48"} +{"seq_id":"38063353293","text":"import random\n\nfirst_names = [\"Alfie\", \"Connor\", \"Deji\", \"Ed\", \"George\", \"Harry\", \"Jack\", \"Leo\", \"Matthew\", \"Stephen\", \"Tyler\", \"William\", \"Zeki\"]\nlast_names = [\"Adekoye\", \"Bray\", \"Eccles\", \"Garraway\", \"Halls\", \"Klein\", \"Little\", \"McMann\", \"Peterson\", \"Rushton\", \"Simpson\", \"Turner\"]\n\nrandom_first_name = random.choice (first_names)\nrandom_last_name = random.choice (last_names)\nrandom_name = random_first_name + \" \" + random_last_name\n\nprint(\"Name: \", random_name)","repo_name":"taylorturton/hello-world","sub_path":"name_generator.py","file_name":"name_generator.py","file_ext":"py","file_size_in_byte":465,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"48"} +{"seq_id":"28823496426","text":"#romeo.txt dosyasını açın ve satır satır okuyun. Her satırı, split() fonksiyonunu kullanarak satırı bir String listesine bölün .\n#Program bir kelime listesi oluşturmalıdır.\n#Her satırdaki her kelime için, kelimenin zaten listede olup olmadığını kontrol edin ve eğer listedeyse tekrar eklemeyin.\n#Program tamamlandığında, ortaya çıkan kelimeleri alfabetik sıraya göre sıralayın ve yazdırın.\n\nlist = list()\nfile = open( \"romeo.txt\")\n\nfor line in file:\n print(line.rstrip())\n words = (line.lower()). split()\n\n for word in words:\n \n if word not in list:\n list.append(word)\n\n\nlist.sort()\nprint(list)\n","repo_name":"EmineKala/Python-101","sub_path":"Python/Hafta4/alistirma1.py","file_name":"alistirma1.py","file_ext":"py","file_size_in_byte":643,"program_lang":"python","lang":"tr","doc_type":"code","stars":0,"dataset":"github-code","pt":"48"} +{"seq_id":"25441154916","text":"# bit 연산 : extraction(추출)\n# - masking에 큰 도움\n# - AND, OR, XOR, NOT를 사용한다.\n\n\nimport cv2\n\n# img1, img2의 크기를 맞춰줘야함\nimg1 = cv2.imread(\"paper.jpg\")\nprint(img1.shape)\nimg2 = cv2.imread(\"hummingbird.jpg\")\nimg2 = cv2.resize(img2, (640, 426))\nprint(img2.shape)\n\n\n# bit_and = cv2.bitwise_and(img1, img2) # and: eg. 빨간색은 빨간색끼로 모인다.\n\n# bit_or = cv2.bitwise_or(img1, img2)\n\n# bit_xor = cv2.bitwise_xor(img1, img2)\n\nbit_not = cv2.bitwise_not(img2)\n\ncv2.imshow(\"bit\", bit_not)\n\n\ncv2.waitKey(0)\ncv2.destroyAllWindows()","repo_name":"factorLee/computerVision_SIIS","sub_path":"cv_openCV_study04/opencv_detail05.py","file_name":"opencv_detail05.py","file_ext":"py","file_size_in_byte":569,"program_lang":"python","lang":"ko","doc_type":"code","stars":0,"dataset":"github-code","pt":"48"} +{"seq_id":"33256697061","text":"# Hayden Feddock\r\n# ECE 1935 - Dr. Dallal\r\n# 3/29/2023\r\n# Assignment 7\r\n\r\nimport numpy as np\r\nimport scipy.io\r\nimport matplotlib.pyplot as plt\r\n\r\n''' Questions 0 '''\r\n\r\n# Load in the data from the .mat file\r\ndata = scipy.io.loadmat('input/HW7_Data.mat')\r\n\r\n# Extract the data\r\nX = np.array(data['X'])\r\ny = np.array(data['y'])\r\n\r\n# Verify the dimensions\r\nprint(f\"Dimensions of X: {X.shape}\")\r\nprint(f\"Dimensions of y: {y.shape}\")\r\n\r\n''' Question 1: Forward Propagation '''\r\n\r\n'''\r\nPart a\r\n- Write a function that returns the predicted the class label for every example (q)\r\n'''\r\n\r\n# Import the function to predict the feed-forward result\r\nimport predict\r\n\r\n'''\r\nPart b\r\n- Load in pre-trained weight matricies Theta1 and Theta2\r\n- Call the function to compute the predictions based on the feed-forward propagation\r\n- Check the accuracy of the predictions\r\n'''\r\n\r\n# Load in the weights from the .mat file\r\nweights = scipy.io.loadmat('input/HW7_weights_2.mat')\r\n\r\n# Extract the weights\r\nTheta1 = np.array(weights['Theta1'])\r\nTheta2 = np.array(weights['Theta2'])\r\n\r\n# Call the function to predict the class labels for each example\r\np, h_x = predict.predict(Theta1, Theta2, X)\r\n\r\n# Check the accuracy of the data\r\naccuracy = np.mean(p == y.flatten())\r\nprint(f\"Accuracy: {accuracy}\")\r\n\r\n\r\n''' Question 2: Cost Function '''\r\n\r\n'''\r\nPart a\r\n- Write a function that computes the cost of the neural network\r\n- Recode the labels as vectors containing only values 0 or 1\r\n'''\r\n\r\n# Import the function to compute the cost\r\nimport nnCost\r\n\r\n# Count the number of classes\r\nnum_classes = len(np.unique(y))\r\n\r\n# Recode y as a vector or vectors containing only values 0 or 1\r\ndef recode(y):\r\n # Determine the number of rows in the y label vector\r\n m = y.shape[0]\r\n \r\n # Create a new y matrix to store the recoded class as a 1 in the \r\n y_recoded = np.zeros([m, num_classes])\r\n \r\n for i in range(m):\r\n i_class = y[i]\r\n y_recoded[i, i_class - 1] = 1\r\n \r\n return y_recoded\r\n\r\ny_recoded = recode(y)\r\n\r\n'''\r\nPart b\r\n- Use the nnCost function to compute the cost when lambda is 0, 1, and 2\r\n'''\r\n\r\n# Compute the cost when lambda = 0\r\nJ_0 = nnCost.nnCost(Theta1, Theta2, X, y_recoded, num_classes, 0)\r\nprint(f\"The cost when lambda = 0 is: {J_0}\")\r\n\r\n# Compute the cost when lambda = 1\r\nJ_1 = nnCost.nnCost(Theta1, Theta2, X, y_recoded, num_classes, 1)\r\nprint(f\"The cost when lambda = 1 is: {J_1}\")\r\n\r\n# Compute the cost when lambda = 2\r\nJ_2 = nnCost.nnCost(Theta1, Theta2, X, y_recoded, num_classes, 2)\r\nprint(f\"The cost when lambda = 2 is: {J_2}\")\r\n\r\n''' Question 3: Derivative of the Activation Function (Sigmoid Gradient) '''\r\n\r\n'''\r\nPart a\r\n- Write a function to calculate the gradient of the sigmoid function\r\n- Test the function\r\n'''\r\n\r\n# Import the function to compute the sigmoid gradient\r\nimport sigmoidGradient\r\n\r\n# Test the function with input z\r\nz = np.array([-10, 0, 10])\r\n\r\n# Compute g_prime (values should be [0, 0.25, 0])\r\ng_prime = sigmoidGradient.sigmoidGradient(z)\r\nprint(f\"The sigmoid gradient of z = [-10, 0, 10] is: {g_prime}\")\r\n\r\n\r\n''' Question 4: Backpropagation for Gradient of Cost Function and Stochastic Gradient Descent '''\r\n\r\n# Import the module with the functiont to compute the ideal thetas\r\nimport sGD\r\n\r\n'''\r\nPart d\r\n- Find and report the alpha value used to update the weights\r\n'''\r\n\r\n# This alpha was found by trial and error\r\nalpha = 0.005\r\n\r\n# Output the value used to compute the alpha\r\nprint(f\"The value used for alpha: {alpha}\")\r\n\r\n'''\r\nPart e\r\n- Compute the figure that shows the cost vs iteration using the training data\r\n'''\r\n\r\n# Compute the costs at each epoch by running the function to compute the thetas\r\nTheta1, Theta2 = sGD.sGD(X.shape[1], 8, num_classes, X, y_recoded, 1, alpha, 50)\r\n \r\n# Output a figure that shows the cost vs epoch\r\nepochs = range(1, len(sGD.costs) + 1)\r\nplt.plot(epochs, sGD.costs)\r\nplt.xlabel(\"Epoch\")\r\nplt.ylabel(\"Cost\")\r\nplt.savefig(\"output/ps7-4-e-1.png\")\r\n\r\n\r\n''' Question 5: Testing the Network '''\r\n\r\n'''\r\nPart a\r\n- Random split the data from HW7_Data.mat into 85% training and 15% testing sets\r\n- Run the code for different values of lambda and epochs and report accuracy and cost with each case\r\n'''\r\n\r\n# Import the library used for the training and testing data split\r\nimport sklearn.model_selection\r\n\r\n# Randomly split the data from X and y into 85% training and 15% testing data\r\nX_train, X_test, y_train, y_test = sklearn.model_selection.train_test_split(X, y, test_size=0.15, train_size=0.85)\r\n\r\n# Import the tabulate library to create the table\r\nfrom tabulate import tabulate\r\n\r\n### Create a table to display the parameter accuracies as a function of the epochs and lambda values ###\r\n# Create the list with the headers\r\nheaders = [\"lambda\", \"Training Data Accuracy @ 50 Epochs\", \"Testing Data Accuracy @ 50 Epochs\", \"Training Data Accuracy @ 100 Epochs\", \"Testing Data Accuracy @ 100 Epochs\"]\r\n\r\n# Create the list with the data\r\ndata = [[\"lambda = 0\", 0, 0, 0, 0],\r\n [\"lambda = 0.01\", 0, 0, 0, 0],\r\n [\"lambda = 0.1\", 0, 0, 0, 0],\r\n [\"lambda = 1\", 0, 0, 0, 0]]\r\n\r\n# Compute the training and testing accuracies for 50 and 100 epochs\r\nepochs = [50, 100]\r\nfor i in range(2):\r\n \r\n # Compute the training and testing data accuracy for each lambda\r\n lam = [0, 0.01, 0.1, 1]\r\n for j in range(4):\r\n \r\n # Compute the parameters with the new lambda value\r\n Theta1, Theta2 = sGD.sGD(X_train.shape[1], 8, num_classes, X_train, recode(y_train), lam[j], alpha, epochs[i])\r\n \r\n # Compute the training accuracy of the parameters using the predict function\r\n p_train = predict.predict(Theta1, Theta2, X_train)[0]\r\n training_accuracy = np.mean(p_train == y_train.flatten())\r\n data[j][1 + 2*i] = training_accuracy\r\n \r\n # Compute the testing accuracy of the parameters using the predict function\r\n p_test = predict.predict(Theta1, Theta2, X_test)[0]\r\n testing_accuracy = np.mean(p_test == y_test.flatten())\r\n data[j][2 + 2*i] = testing_accuracy\r\n\r\n# Print out the training and testing accuracies\r\nprint(tabulate(data, headers, tablefmt='grid'))\r\n \r\n \r\n### Create a table to display the parameter costs as a function of the epochs and lambda values ###\r\n# Create the list with the headers\r\nheaders = [\"lambda\", \"Training Data Cost @ 50 Epochs\", \"Testing Data Cost @ 50 Epochs\", \"Training Data Cost @ 100 Epochs\", \"Testing Data Cost @ 100 Epochs\"]\r\n\r\n# Create the list with the data\r\ndata = [[\"lambda = 0\", 0, 0, 0, 0],\r\n [\"lambda = 0.01\", 0, 0, 0, 0],\r\n [\"lambda = 0.1\", 0, 0, 0, 0],\r\n [\"lambda = 1\", 0, 0, 0, 0]]\r\n\r\n# Compute the training and testing costs for 50 and 100 epochs\r\nepochs = [50, 100]\r\nfor i in range(2):\r\n \r\n # Compute the training and testing data costs for each lambda\r\n lam = [0, 0.01, 0.1, 1]\r\n for j in range(4):\r\n \r\n # Compute the parameters with the new lambda value\r\n Theta1, Theta2 = sGD.sGD(X_train.shape[1], 8, num_classes, X_train, recode(y_train), lam[j], alpha, epochs[i])\r\n \r\n # Compute the training costs of the parameters using the cost function\r\n p_train = predict.predict(Theta1, Theta2, X_train)[0]\r\n training_cost = nnCost.nnCost(Theta1, Theta2, X_train, recode(y_train), num_classes, lam[j])\r\n data[j][1 + 2*i] = training_cost\r\n \r\n # Compute the testing costs of the parameters using the cost function\r\n p_test = predict.predict(Theta1, Theta2, X_test)[0]\r\n testing_cost = nnCost.nnCost(Theta1, Theta2, X_test, recode(y_test), num_classes, lam[j])\r\n data[j][2 + 2*i] = testing_cost\r\n\r\n# Print out the training and testing costs\r\nprint(tabulate(data, headers, tablefmt='grid'))\r\n \r\n\r\n\r\n\r\n","repo_name":"Feddockh/Learning_ML","sub_path":"HW_7/ps7_python_Feddock_Hayden/ps7.py","file_name":"ps7.py","file_ext":"py","file_size_in_byte":7777,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"48"} +{"seq_id":"72932834705","text":"from collections.abc import Sequence\nfrom itertools import islice\n\nfrom pypgx.api._pgx_id import PgxId\nfrom pypgx.api._pgx_context_manager import PgxContextManager\nfrom pypgx.api._pgx_entity import PgxEdge, PgxVertex, PgxEntity\nfrom pypgx._utils.error_handling import java_handler, java_caster\nfrom pypgx._utils.error_messages import (\n COMPARE_VECTOR,\n INVALID_TYPE_OR_ITERABLE_TYPE,\n INVALID_OPTION,\n)\nfrom pypgx._utils.item_converter import convert_to_java_type, convert_to_python_type\nfrom pypgx._utils.pgx_types import property_types\nfrom pypgx._utils.pyjnius_helper import PyjniusHelper\nfrom pypgx.api._pgx_map import PgxMap\nfrom typing import Any, Iterator, List, Optional, Set, Tuple, Union, TYPE_CHECKING\n\nif TYPE_CHECKING:\n # Don't import at runtime, to avoid circular imports.\n from pypgx.api._pgx_graph import PgxGraph\n\n\nclass PgxProperty(PgxContextManager):\n \"\"\"A property of a `PgxGraph`.\n\n .. note: This is a base class of :class:`VertexProperty` and :class:`EdgeProperty`,\n and is not instantiated on its own.\n \"\"\"\n\n _java_class = 'oracle.pgx.api.Property'\n\n def __init__(self, graph: \"PgxGraph\", java_prop) -> None:\n self._prop = java_prop\n self.name = java_prop.getName()\n self.entity_type = java_prop.getEntityType().toString()\n self.type = java_prop.getType().toString()\n self.is_transient = java_prop.isTransient()\n self.dimension = java_prop.getDimension()\n self.size = java_prop.size()\n self.graph = graph\n self.is_vector_property = self.dimension > 0\n\n @property\n def is_published(self) -> bool:\n \"\"\"Check if this property is published.\n\n :return: `True` if this property is published, `False` otherwise.\n :rtype: bool\n \"\"\"\n return self._prop.isPublished()\n\n def publish(self) -> None:\n \"\"\"Publish the property into a shared graph so it can be shared between sessions.\n\n :return: None\n \"\"\"\n java_handler(self._prop.publish, [])\n\n def rename(self, name: str) -> None:\n \"\"\"Rename this property.\n\n :param name: New name\n :return: None\n \"\"\"\n java_handler(self._prop.rename, [name])\n self.name = name\n\n def clone(self, name: Optional[str] = None) -> \"PgxProperty\":\n \"\"\"Create a copy of this property.\n\n :param name: name of copy to be created. If `None`, guaranteed unique name will be\n generated.\n :return: property result\n :rtype: this class\n \"\"\"\n cloned_prop = java_handler(self._prop.clone, [name])\n return self.__class__(self.graph, cloned_prop)\n\n def get_top_k_values(self, k: int) -> List[Tuple[PgxEntity, Any]]:\n \"\"\"Get the top k vertex/edge value pairs according to their value.\n\n :param k: How many top values to retrieve, must be in the range between 0 and number of\n nodes/edges (inclusive)\n :return: list of `k` key-value tuples where the keys vertices/edges and the values are\n property values, sorted in ascending order\n :rtype: list of tuple(PgxVertex or PgxEdge, Any)\n\n \"\"\"\n if self.dimension > 0:\n raise RuntimeError(COMPARE_VECTOR)\n else:\n top_k = java_handler(self._prop.getTopKValues, [k])\n it = top_k.iterator()\n return list(\n (\n convert_to_python_type(item.getKey(), self.graph),\n convert_to_python_type(item.getValue(), self.graph),\n )\n for item in islice(it, 0, k)\n )\n\n def get_bottom_k_values(self, k: int) -> List[Tuple[PgxEntity, Any]]:\n \"\"\"Get the bottom k vertex/edge value pairs according to their value.\n\n :param k: How many top values to retrieve, must be in the range between 0 and number of\n nodes/edges (inclusive)\n \"\"\"\n if self.dimension > 0:\n raise RuntimeError(COMPARE_VECTOR)\n else:\n bottom_k = java_handler(self._prop.getBottomKValues, [k])\n it = bottom_k.iterator()\n return list(\n (\n convert_to_python_type(item.getKey(), self.graph),\n convert_to_python_type(item.getValue(), self.graph),\n )\n for item in islice(it, 0, k)\n )\n\n def get_values(self) -> List[Tuple[PgxEntity, Any]]:\n \"\"\"Get the values of this property as a list.\"\"\"\n return list(self)\n\n def fill(self, value: Any) -> None:\n \"\"\"Fill this property with a given value.\n\n :param value: The value\n \"\"\"\n if self.dimension > 0:\n vec = None\n if self.entity_type == 'vertex':\n vec = self._prop.get(self.graph.get_random_vertex().id)\n else:\n vec = self._prop.get(self.graph.get_random_edge().id)\n t = type(vec.get(0))\n if isinstance(value, Sequence) and self.dimension == len(value):\n for idx in range(vec.getDimension()):\n java_caster(vec.set, (idx, 'integer'), (value[idx], self.type))\n elif isinstance(value, t):\n for idx in range(vec.getDimension()):\n java_caster(vec.set, (idx, 'integer'), (value, self.type))\n else:\n raise TypeError(\n INVALID_TYPE_OR_ITERABLE_TYPE.format(\n var='value', type=t.__name__, size=self.dimension\n )\n )\n java_handler(self._prop.fill, [vec])\n else:\n value = convert_to_java_type(value)\n java_handler(self._prop.fill, [value])\n\n def expand(self) -> Union[\"PgxProperty\", List[\"PgxProperty\"]]:\n \"\"\"If this is a vector property, expands this property into a list of scalar properties of\n same type.\n\n The first property will contain the first element of the vector, the second property the\n second element and so on.\n \"\"\"\n if self.dimension > 0:\n expanded = java_handler(self._prop.expand, [])\n expanded_list = []\n for p in expanded:\n expanded_list.append(self.__class__(self.graph, p))\n return expanded_list\n else:\n return self\n\n def close(self) -> None:\n \"\"\"Free resources on the server taken up by this Property.\n\n :return: None\n \"\"\"\n java_handler(self._prop.close, [])\n\n def get_property_id(self) -> PgxId:\n \"\"\"Get an internal identifier for this property.\n\n Only meant for internal usage.\n\n :return: the internal identifier of this property\n \"\"\"\n return PgxId(self._prop.getPropertyId())\n\n def wrap(self, property_value: Any, property_type: str) -> Any:\n \"\"\"Take a property value and wraps it pgx entities if applicable\n\n :param property_value: property value\n :type property_value: Any\n :param property_type: A valid property type.\n :type property_type: str\n \"\"\"\n if property_type not in property_types.keys():\n raise ValueError(\n INVALID_OPTION.format(var='property_type', opts=list(property_types.keys()))\n )\n if isinstance(property_value, (int, str)) and property_type == 'vertex':\n item = java_handler(self.graph._graph.getVertex, [property_value])\n return convert_to_python_type(item, self.graph)\n elif isinstance(property_value, (int, str)) and property_type == 'edge':\n item = java_handler(self.graph._graph.getEdge, [property_value])\n return convert_to_python_type(item, self.graph)\n else:\n return property_value\n\n def is_vector_property(self) -> bool:\n \"\"\"Return True if it is a vector property, False otherwise\"\"\"\n return self._prop.isVectorProperty()\n\n def destroy(self) -> None:\n \"\"\"Free resources on the server taken up by this Property.\n\n :return: None\n \"\"\"\n java_handler(self._prop.destroy, [])\n\n def __iter__(self) -> Iterator[Any]:\n it = self._prop.getValues().iterator()\n if self.dimension > 0:\n return (\n (convert_to_python_type(item.getKey(), self.graph), list(item.getValue().toArray()))\n for item in islice(it, 0, self.size)\n )\n else:\n return (\n (\n convert_to_python_type(item.getKey(), self.graph),\n convert_to_python_type(item.getValue(), self.graph),\n )\n for item in islice(it, 0, self.size)\n )\n\n def __getitem__(self, key: Union[slice, PgxEntity, int, str]) -> Any:\n if isinstance(key, slice):\n it = self._prop.getValues().iterator()\n if self.dimension > 0:\n return list(\n (\n convert_to_python_type(item.getKey(), self.graph),\n list(item.getValue().toArray()),\n )\n for item in islice(it, key.start, key.stop, key.step)\n )\n else:\n return list(\n (\n convert_to_python_type(item.getKey(), self.graph),\n convert_to_python_type(item.getValue(), self.graph),\n )\n for item in islice(it, key.start, key.stop, key.step)\n )\n else:\n return self.get(key)\n\n def __setitem__(self, key: Union[PgxEntity, int, str], value: Any) -> None:\n self.set(key, value)\n\n def __len__(self) -> int:\n return self.size\n\n def __repr__(self) -> str:\n return \"{}(name: {}, type: {}, graph: {})\".format(\n self.__class__.__name__, self.name, self.type, self.graph.name\n )\n\n def __str__(self) -> str:\n return repr(self)\n\n def __hash__(self) -> int:\n return hash((str(self), str(self.graph.name)))\n\n def __eq__(self, other: object) -> bool:\n if not isinstance(other, self.__class__):\n return False\n return self._prop.equals(other._prop)\n\n\nclass VertexProperty(PgxProperty):\n \"\"\"A vertex property of a :class:`PgxGraph`.\"\"\"\n\n _java_class = 'oracle.pgx.api.VertexProperty'\n\n def __init__(self, graph: \"PgxGraph\", java_prop) -> None:\n super().__init__(graph, java_prop)\n\n @staticmethod\n def _from_java(java_prop):\n # need to import here to avoid import loop\n from pypgx.api._pgx_session import PgxSession\n from pypgx.api._pgx_graph import PgxGraph\n\n java_graph = java_handler(java_prop.getGraph, [])\n java_session = java_handler(java_graph.getSession, [])\n graph = PgxGraph(PgxSession(java_session), java_graph)\n return VertexProperty(graph, java_prop)\n\n def set(self, key: Union[PgxVertex, int, str], value: Any) -> None:\n \"\"\"Set a property value.\n\n :param key: The key (vertex/edge) whose property to set\n :param value: The property value\n \"\"\"\n if isinstance(key, (int, str)):\n key = self.graph.get_vertex(key)\n key = convert_to_java_type(key)\n if self.dimension > 0:\n vec = java_handler(PyjniusHelper.getFromPropertyByKey, [self._prop, key])\n t = type(vec.get(0))\n if isinstance(value, Sequence) and self.dimension == len(value):\n for idx, v in enumerate(value):\n java_caster(vec.set, (idx, None), (v, self.type))\n elif isinstance(value, t):\n for idx in range(vec.getDimension()):\n java_caster(vec.set, (idx, 'integer'), (value, self.type))\n else:\n raise TypeError(\n INVALID_TYPE_OR_ITERABLE_TYPE.format(\n var='value', type=t.__name__, size=self.dimension\n )\n )\n java_handler(self._prop.set, [key, vec])\n else:\n value = convert_to_java_type(value)\n java_caster(self._prop.set, (key, None), (value, self.type))\n\n def set_values(self, values: PgxMap) -> None:\n \"\"\"Set the labels values.\n\n :param values: pgxmap with ids and values\n :type values: PgxMap\n \"\"\"\n values_keys = values.keys()\n for key in values_keys:\n self.set(key, values.get(key))\n\n def get(self, key: Union[PgxVertex, int, str]) -> Any:\n \"\"\"\n :param key: The key (vertex/edge) whose property to get\n \"\"\"\n if isinstance(key, (int, str)):\n key = self.graph.get_vertex(key)\n key = convert_to_java_type(key)\n value = java_handler(PyjniusHelper.getFromPropertyByKey, [self._prop, key])\n if self.dimension > 0:\n return list(value.toArray())\n else:\n return convert_to_python_type(value, self.graph)\n\n\nclass EdgeProperty(PgxProperty):\n \"\"\"An edge property of a :class:`PgxGraph`.\"\"\"\n\n _java_class = 'oracle.pgx.api.EdgeProperty'\n\n def __init__(self, graph: \"PgxGraph\", java_prop) -> None:\n super().__init__(graph, java_prop)\n\n def set(self, key: Union[PgxEdge, int], value: Any) -> None:\n \"\"\"Set a property value.\n\n :param key: The key (vertex/edge) whose property to set\n :param value: The property value\n \"\"\"\n if isinstance(key, (int, str)):\n key = self.graph.get_edge(key)\n key = convert_to_java_type(key)\n if self.dimension > 0:\n vec = java_handler(PyjniusHelper.getFromPropertyByKey, [self._prop, key])\n t = type(vec.get(0))\n if isinstance(value, Sequence) and self.dimension == len(value):\n for idx in range(vec.getDimension()):\n java_handler(vec.set, [idx, value[idx]])\n elif isinstance(value, t):\n for idx in range(vec.getDimension()):\n java_handler(vec.set, [idx, value])\n else:\n raise TypeError(\n INVALID_TYPE_OR_ITERABLE_TYPE.format(\n var='value', type=t.__name__, size=self.dimension\n )\n )\n java_handler(self._prop.set, [key, vec])\n else:\n value = convert_to_java_type(value)\n java_handler(self._prop.set, [key, value])\n\n def set_values(self, values: PgxMap) -> None:\n \"\"\"Set the labels values.\n\n :param values: pgxmap with ids and values\n :type values: PgxMap\n \"\"\"\n values_keys = values.keys()\n for key in values_keys:\n self.set(key, values.get(key))\n\n def get(self, key: Union[PgxEdge, int]) -> Any:\n \"\"\"\n :param key: The key (vertex/edge) whose property to get\n \"\"\"\n if isinstance(key, (int, str)):\n key = self.graph.get_edge(key)\n key = convert_to_java_type(key)\n value = java_handler(PyjniusHelper.getFromPropertyByKey, [self._prop, key])\n if self.dimension > 0:\n return list(value.toArray())\n else:\n return convert_to_python_type(value, self.graph)\n\n\nclass VertexLabels(VertexProperty):\n \"\"\"Class for storing labels for vertices.\n\n A vertex can have multiple labels. In effect this is a :class:`VertexProperty`\n where a set of strings is associated to each vertex.\n \"\"\"\n\n _java_class = 'oracle.pgx.api.VertexLabels'\n\n def __init__(self, graph: \"PgxGraph\", java_labels) -> None:\n self._labels = java_labels\n super().__init__(graph, java_labels)\n\n def __getitem__(\n self, key: Union[slice, PgxVertex, int, str]\n ) -> Union[List[Tuple[PgxVertex, Set[str]]], Set[str]]:\n if isinstance(key, slice):\n it = self._labels.getValues().iterator()\n return list(\n (PgxVertex(self.graph, item.getKey()), set(item.getValue()))\n for item in islice(it, key.start, key.stop, key.step)\n )\n else:\n return set(self.get(key))\n\n def get_values(self) -> List[Tuple[PgxVertex, Set[str]]]:\n \"\"\"Get the values of this label as a list.\n\n :return: a list of key-value tuples, where each key is a vertex and each key is the set of\n labels assigned to that vertex\n :rtype: list of tuple(PgxVertex, set of str)\n \"\"\"\n return list(self)\n\n def __iter__(self) -> Iterator[Tuple[PgxVertex, Set[str]]]:\n it = self._labels.getValues().iterator()\n return (\n (PgxVertex(self.graph, item.getKey()), set(item.getValue()))\n for item in islice(it, 0, self.size)\n )\n\n\nclass EdgeLabel(EdgeProperty):\n \"\"\"Class for storing a label type edge property.\"\"\"\n\n _java_class = 'oracle.pgx.api.EdgeLabel'\n\n def __init__(self, graph: \"PgxGraph\", java_label) -> None:\n self._label = java_label\n super().__init__(graph, java_label)\n","repo_name":"praveennhiremath/LouvainCommunityDetection","sub_path":"resources/oracle-graph-client-22.1.0/python/pypgx/api/_property.py","file_name":"_property.py","file_ext":"py","file_size_in_byte":16990,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"48"} +{"seq_id":"71725182546","text":"\"\"\"\n问跳到数组最后最少需要几次\n\"\"\"\n\nclass Solution(object):\n def jump(self, nums):\n \"\"\"\n :type nums: List[int]\n :rtype: int\n \"\"\"\n if nums is None and len(nums) == 0:\n return -1\n\n if len(nums) == 1:\n return 0\n\n n = len(nums)\n\n # 再跳一次的话,能跳的最远距离\n next_max = 0\n\n # 在当前跳跃的次数里,能跳到的最远距离\n cur_max = 0\n\n # 已经跳跃的次数\n jump = 0\n\n\n for i in range(n):\n # 假如说我们再跳一次的话,可以到达或者超越终点,那么我们返回当前的跳跃次数+1\n if next_max >= n-1:\n return jump + 1\n\n # 假如走到一个下标, 是我们再跳一次也达不到的\n # 那么说明到达不了这个下标 -> 我们也更跳不到终点\n if i > next_max:\n return -1\n\n # 假如到了一个下标,已经到我们当前跳跃次数的极限了\n # 那么说明我们要再跳一次\n if i > cur_max:\n jump += 1\n cur_max = next_max\n\n # 下一次的跳跃最大距离\n next_max = max(next_max, i+nums[i])\n\n return -1\n\n\"\"\"\nhttps://algocasts.io/episodesaAEpo1vmQ\nTime: O(n), Space: O(1)\n\"\"\"\n\n#Time: O(n), Space: O(n)\ndef jump(self, nums):\n \"\"\"\n :type nums: List[int]\n :rtype: int\n \"\"\"\n if nums is None or len(nums) == 0: return -1\n\n n = len(nums)\n next_max = 0\n step = [0] * n\n\n for i in xrange(n):\n if next_max >= n - 1: return step[n - 1]\n if i > next_max: return -1\n next_max = i + nums[i] if i + nums[i] > next_max else next_max\n last = next_max if next_max < n - 1 else n - 1\n for j in xrange(last, i, -1):\n if step[j] != 0:\n break\n step[j] = step[i] + 1\n\n return -1","repo_name":"Andrewlearning/Leetcoding","sub_path":"leetcode/Greedy/45. 跳跃游戏II.py","file_name":"45. 跳跃游戏II.py","file_ext":"py","file_size_in_byte":1949,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"48"} +{"seq_id":"23609609299","text":"from model.contact import Contact\nimport random\n\n\ndef test_edit_some_contact_firstname(app, db, check_ui):\n if app.contacts.count() == 0:\n app.contacts.create_new_contact(Contact(firstname=\"crab\"))\n old_contacts = db.get_contact_list()\n contact = random.choice(old_contacts)\n contact_data = Contact(firstname=\"helloman\")\n app.contacts.edit_contact_by_id(contact.id, contact_data)\n old_contacts.remove(contact)\n new_contacts = db.get_contact_list()\n contact_data.id = contact.id\n old_contacts.append(contact_data)\n assert sorted(old_contacts, key=Contact.id_or_max) == sorted(new_contacts, key=Contact.id_or_max)\n if check_ui:\n assert sorted(old_contacts, key=Contact.id_or_max) == sorted(app.contact.get_contact_list(),\n key=Contact.id_or_max)\n\n\n\n#def test_editfirstcontact_middlename(app):\n# if app.contacts.count() == 0:\n# app.contacts.create_new_contact(Contact(firstname=\"crab\"))\n# old_contacts = app.contacts.get_contact_list()\n# app.contacts.edit_first_contact(Contact(middlename=\"New MiddleName\"))\n# new_contacts = app.contacts.get_contact_list()\n# assert len(old_contacts) == len(new_contacts)","repo_name":"winsok/pythonlearning","sub_path":"test/test_editfirstcontact.py","file_name":"test_editfirstcontact.py","file_ext":"py","file_size_in_byte":1238,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"48"} +{"seq_id":"18893560479","text":"# -*- coding: utf-8 -*-\n\nimport requests\n\nfrom connect.config import Config\nfrom connect.logger import function_log, logger\nfrom connect.models import BaseScheme, ServerErrorScheme\nfrom connect.models.exception import ServerErrorException\nfrom .utils import joinurl\n\nconfig = Config()\n\n\nclass ApiClient(object):\n\n @property\n def headers(self):\n config.check_credentials(\n config.api_url, config.api_key, config.products)\n return {\n \"Authorization\": config.api_key,\n \"Content-Type\": \"application/json\",\n }\n\n @staticmethod\n def check_response(response):\n if not hasattr(response, 'content'):\n raise AttributeError(\n 'Response not attribute content. Check your request params'\n 'Response status - {}'.format(getattr(response, 'code')),\n )\n\n if not hasattr(response, 'ok') or not response.ok:\n data, error = ServerErrorScheme().loads(response.content)\n if data:\n raise ServerErrorException(data)\n\n return response.content\n\n @function_log\n def get(self, url, params=None, **kwargs):\n kwargs['headers'] = self.headers\n response = requests.get(url, params, **kwargs)\n return self.check_response(response)\n\n @function_log\n def post(self, url, data=None, json=None, **kwargs):\n kwargs['headers'] = self.headers\n response = requests.post(url, data, json, **kwargs)\n return self.check_response(response)\n\n @function_log\n def put(self, url, data=None, **kwargs):\n kwargs['headers'] = self.headers\n response = requests.put(url, data, **kwargs)\n return self.check_response(response)\n\n\nclass BaseResource(object):\n resource = None\n limit = 100\n api = ApiClient()\n scheme = BaseScheme()\n\n def __init__(self, *args, **kwargs):\n\n if self.__class__.resource is None:\n raise AttributeError('Resource name not specified in class {}'.format(\n self.__class__.__name__) + '. Add an attribute `resource` name of the resource')\n\n def build_filter(self):\n res_filter = {}\n if self.limit:\n res_filter['limit'] = self.limit\n\n return res_filter\n\n @property\n def _list_url(self):\n return joinurl(config.api_url, self.__class__.resource)\n\n def _obj_url(self, pk):\n return joinurl(self._list_url, pk)\n\n def __loads_scheme(self, response):\n objects, error = self.scheme.loads(response, many=True)\n if error:\n raise TypeError(\n 'Invalid structure for initialisation objects. \\n'\n 'Error: {}. \\nServer Response: {}'.format(error, response),\n )\n\n return objects\n\n def get(self, pk):\n response = self.api.get(url=self._obj_url(pk))\n objects = self.__loads_scheme(response)\n if isinstance(objects, list) and len(objects) > 0:\n return objects[0]\n\n def list(self):\n filters = self.build_filter()\n logger.info('Get list request by filter - {}'.format(filters))\n response = self.api.get(url=self._list_url, params=filters)\n return self.__loads_scheme(response)\n","repo_name":"ht-albert/connect-python-sdk","sub_path":"connect/resource/base.py","file_name":"base.py","file_ext":"py","file_size_in_byte":3223,"program_lang":"python","lang":"en","doc_type":"code","dataset":"github-code","pt":"48"} +{"seq_id":"44032425488","text":"#!/usr/bin/env python\n# coding: utf-8\n\nimport matplotlib.pyplot as plt\nimport torch\nimport numpy as np\nfrom torch import nn\nimport time\nfrom sklearn.metrics import accuracy_score\nimport data_process2\nfrom model import TextCNN\nimport argparse\nimport pickle\n\ndevice = torch.device(\"cuda:1\" if torch.cuda.is_available() else \"cpu\")\n\n\n\n# 定义超参数\nparser = argparse.ArgumentParser()\nparser.add_argument('--vocab_size', type=int, default=80000)\nparser.add_argument('--batch_size', type=int, default=64)\nparser.add_argument('--max_len', type=int, default=2048)\nparser.add_argument('--lr', type=float, default=0.0001)\nparser.add_argument('--embedding_size', type=int, default=300)\nparser.add_argument('--input_channel', type=int, default=1)\nparser.add_argument('--output_channel', type=int, default=512)\nparser.add_argument('--dropout', type=float, default=0.5)\nparser.add_argument('--output_size', type=int, default=2)\nparser.add_argument('--num_epochs', type=int, default=100)\nparser.add_argument('--kernal_sizes', type=list, default=[2,3,4,5])\nparser.add_argument('--test_per_step', type=int, default=100)\nparser.add_argument('--pretrained', type=bool, default=True)\n\nargs = parser.parse_args()\n\n\n# 加载数据\ntrain_iter,test_iter,vocab_words = data_process2.load_data(args)\nargs.vocab_size = len(vocab_words)\nprint('vocab_size:',len(vocab_words))\n\n# 加载预训练词向量\nwith open('./data/wvmodel.pkl', 'rb') as inp:\n wvmodel = pickle.load(inp)\nprint('wvmodel loaded!')\n\nweight = torch.zeros(args.vocab_size, args.embedding_size)\nfor i in range(len(wvmodel.index2word)):\n try:\n index = word_to_idx[wvmodel.index2word[i]]\n except:\n continue\n weight[index,:] = torch.from_numpy(wvmodel.get_vector(\n idx_to_word[word_to_idx[wvmodel.index2word[i]]]))\n\n# 加载模型\nnet = TextCNN(args,weight).to(device)\n\n# 定义损失函数和优化器\ncriterion = nn.CrossEntropyLoss() # 使用交叉熵损失函数\noptimizer = torch.optim.Adam(filter(lambda p:p.requires_grad, net.parameters()),lr = args.lr)\n\n# 模型训练\nprint('training on ',device)\nbest_acc = 0.0\nstep = 0\nfor epoch in range(1, args.num_epochs + 1):\n net.train()\n for X,y in train_iter:\n X, y = X.to(device), y.to(device)\n y_hat = net(X) # 计算预测概率值\n loss = criterion(y_hat, y) # 计算loss值\n optimizer.zero_grad() # 梯度置零\n loss.backward() # 反向传播\n optimizer.step() # 参数更新\n step+=1\n\n # 测试\n if step % args.test_per_step == 0: \n net.eval()\n all_pre=[]\n all_label=[]\n\n for X,y in test_iter:\n X, y = X.to(device), y.to(device)\n y_hat = net(X)\n y_pre = torch.argmax(y_hat, dim=-1)\n all_pre.extend(y_pre.tolist())\n all_label.extend(y.tolist())\n test_acc_sum = sum([int(line[0]==line[1]) for line in zip(all_pre,all_label)])\n test_acc = test_acc_sum/len(all_label)\n\n print('train_step %d, loss: %.4f, test_acc: %.4f'%(step, loss, test_acc))\n\n if test_acc > best_acc:\n best_acc = test_acc\n torch.save(net.state_dict(),'./model/best_model.bin')\nprint('best_acc: ', best_acc)\n\n\n\n","repo_name":"HuihuiChyan/BJTUNLP_Practice2020","sub_path":"text_classification/20125185/train.py","file_name":"train.py","file_ext":"py","file_size_in_byte":3276,"program_lang":"python","lang":"en","doc_type":"code","stars":18,"dataset":"github-code","pt":"48"} +{"seq_id":"7798050237","text":"import sys\nsys.stdin = open('input.txt')\n\ndef min_search():\n min_num = 987654321\n min_index = -1\n for i in range(len(height)):\n if height[i] < min_num:\n min_num = height[i]\n min_index = i\n return min_index\n\ndef max_search():\n max_num = -1\n max_index = -1\n for i in range(len(height)):\n if height[i] > max_num:\n max_num = height[i]\n max_index = i\n return max_index\n\nfor tc in range(1, 11):\n T = int(input())\n height = list(map(int, input().split()))\n\n for v in range(T):\n height[max_search()] -= 1\n height[min_search()] += 1\n\n print(height[max_search()] - height[min_search()])","repo_name":"asooso1/ssafy_algorithm","sub_path":"0810/박근석/1208_Flatten/s1.py","file_name":"s1.py","file_ext":"py","file_size_in_byte":684,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"48"} +{"seq_id":"20999698604","text":"#!/usr/bin/env python\n\nimport sys\nimport pandas as pd\nimport matplotlib.pyplot as plt\n\n#how does expression of diff transcripts track along the chr\n\n#use readtable so you dont have to specify tabs\ndf = pd.read_table( sys.argv[1] )\n\n#just chr 3; another boolean select.\n\ndf_roi = df[\"chr\"] == \"3L\"\ndf_chrom = df[df_roi]\n\n#rolling size = 200, and what FPKM values\n#calculate a mean for every step of 200\nsmoothed = df_chrom['FPKM'].rolling(200).mean()\n\n#print smoothed\n\nplt.figure()\nplt.plot(smoothed)\nplt.title(\"Chrom 3L, FPKM rolling mean 200\")\nplt.show()\nplt.savefig(\"smoothed.png\")\n\n#\n# plt.close()\n\n#calculate some stat over that window, use mean\n","repo_name":"raonina/qbb2016-answers","sub_path":"day4/02-plotrolling.py","file_name":"02-plotrolling.py","file_ext":"py","file_size_in_byte":650,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"48"} +{"seq_id":"21508993373","text":"from typing import List\n\nimport importlib, nltk, re, numpy\n\n\ndef create_object_from_class_string(\n module_name: str, class_name: str, parameters: dict\n):\n module = importlib.import_module(module_name)\n class_ = getattr(module, class_name)\n instance = class_(**parameters)\n return instance\n\n\ndef load_object_from_dict(parameters: dict, **kwargs):\n parameters.update(kwargs)\n type = parameters.get(\"type\")\n if type is None:\n return None\n else:\n type = type.split(\".\")\n module_name, class_name = \".\".join(type[:-1]), type[-1]\n params = {k: v for k, v in parameters.items() if k != \"type\"}\n return create_object_from_class_string(module_name, class_name, params)\n\n\n## A few tokenization methods:\ndef whitespace_tokenizer(text: str) -> List[str]:\n return text.split(\" \")\n\n\ndef default_tokenizer(text) -> str:\n # remove punctuation from string\n text = re.sub(r\"[^\\w\\s]\", \"\", text)\n return nltk.word_tokenize(text)\n\n\ndef default_tokenizer_lower(text) -> str:\n return default_tokenizer(text.lower())\n\n\ndef load_tokenizer(name: str = None) -> callable:\n if name is None:\n return None\n elif name == \"nltk-punct\":\n return default_tokenizer\n elif name == \"nltk-punct-lower\":\n return default_tokenizer_lower\n elif name == \"whitespace\":\n return whitespace_tokenizer\n elif name == \"nltk\":\n return nltk.word_tokenize\n else:\n raise NotImplementedError(f\"'{name}' is currently not supported...\")\n\n\ndef load_embeddings_from_filepath(filepath: str) -> numpy.array:\n word2embeddings = {}\n with open(filepath, encoding=\"utf-8\") as f:\n for line in f:\n line = line.split()\n word = line[0]\n embedding = numpy.array([float(e) for e in line[1:]], dtype=numpy.float32)\n word2embeddings[word] = embedding\n\n return word2embeddings\n","repo_name":"sameersingh/uci-statnlp","sub_path":"hw3/code/utils.py","file_name":"utils.py","file_ext":"py","file_size_in_byte":1898,"program_lang":"python","lang":"en","doc_type":"code","stars":21,"dataset":"github-code","pt":"40"} +{"seq_id":"23623675010","text":"def gen_fragment(peptide):\n frag_list = []\n for left, aa in enumerate(peptide):\n if aa in ['R', 'K']:\n frag_list.append(peptide[:left+1])\n for right, _ in enumerate(peptide):\n if right > left:\n if peptide[left:right][-1] in ['R','K'] and peptide[left-1] in [\"R\", \"K\"]:\n if len(peptide[left:right]) > 1:\n frag_list.append(peptide[left:right])\n return frag_list\n\ndef mw_cal(peptide, modification):\n aa_weight = {'A':89.05, 'C':121.02, 'D':133.04, 'E': 147.05, 'F':165.08, \n 'G':75.03, 'H':155.07, 'I':131.09, 'K': 146.11, 'L':131.09, \n 'M':149.05, 'N': 132.05, 'P': 115.06, 'Q': 146.07, 'R': 174.11, \n 'S': 105.04, 'T': 119.06, 'V': 117.08,'W':204.09,'Y':181.07}\n w = 0\n for i, aa in enumerate(peptide):\n w += aa_weight[aa] - 18.01\n # return [round(w+18.01,1), round(w+55.04,1)]\n return [str(round(w+x,1)) for x in modification]\n\ndef peptide_fragment_mass(peptide, modification, output_path):\n frags = gen_fragment(peptide)\n with open(f\"{output_path}/frags.csv\", 'w+') as of:\n for frag in frags:\n result = mw_cal(frag, modification)\n of.write(\",\".join([frag] + result)+\"\\n\")\n\n\nif __name__ == '__main__':\n peptide = \"ALSKGEELFTGVVPILVELDGDVNGHKFSVRGEGEGDATNGKLTLKFICTTGKLPVPWPTLVTTLTYGVLCFSRYPDHMKRHDFFKSAMPEGYVQERTISFKDDGTYKTRAEVKFEGDTLVNRIELKGIDFKEDGNILGHKLEYNFNSHNVYITADKQKNGIKAYFKIRHNVEDGSVQLADHYQQNTPIGDGPVLLPDNHYLSTQSVLSKDPNEKRDHMVLLEFVTAAGITHGASLFG\"\n modification = [18.01, 55.04]\n output_path = './'\n peptide_fragment_mass(peptide, modification, output_path)","repo_name":"JinyuanSun/lab-gui-tools","sub_path":"lab_gui_tools/peptide_mass_calculator.py","file_name":"peptide_mass_calculator.py","file_ext":"py","file_size_in_byte":1682,"program_lang":"python","lang":"en","doc_type":"code","stars":2,"dataset":"github-code","pt":"40"} +{"seq_id":"70907099321","text":"from flask import Flask, render_template\r\nfrom flask_sqlalchemy import SQLAlchemy\r\nfrom datetime import datetime\r\n\r\napp = Flask(__name__)\r\napp.config['SQLALCHEMY_DATABASE_URI'] = \"sqlite:///C:\\\\Users\\\\91983\\\\OneDrive\\\\Desktop\\\\New folder\\\\todo.db\"\r\n\r\napp.config['SQLALCHEMY_TRACK_MODIFICATIONS'] = False\r\n\r\n\r\ndb = SQLAlchemy(app)\r\nclass TODO(db.Model):\r\n sno = db.Column(db.Integer, primary_key=True)\r\n title = db.Column(db.String(200), nullable=False)\r\n desc = db.Column(db.String(500), nullable=False)\r\n date_created = db.Column(db.DateTime, default=datetime.utcnow)\r\n\r\n\r\napp.app_context().push()\r\ndb.create_all()\r\ndb.session.commit()\r\n","repo_name":"Krishi24/fkaskandsqlalchemy","sub_path":"app.py","file_name":"app.py","file_ext":"py","file_size_in_byte":650,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"40"} +{"seq_id":"72740152761","text":"from typing import List\n\n\n# Given a fixed length array arr of integers, duplicate each occurrence of zero,\n# shifting the remaining elements to the right.\n#\n# Note that elements beyond the length of the original array are not written.\n#\n# Do the above modifications to the input array in place, do not return anything from your function.\n#\n# Note:\n# 1 <= arr.length <= 10000\n# 0 <= arr[i] <= 9\nclass Solution:\n def duplicateZeros(self, arr: List[int]) -> None:\n \"\"\"\n Do not return anything, modify arr in-place instead.\n \"\"\"\n inserted_zero_index = None\n for i in range(len(arr)):\n if arr[i] == 0 and (inserted_zero_index is None or inserted_zero_index != i):\n arr.insert(i + 1, 0)\n arr.pop()\n inserted_zero_index = i + 1\n\n\nclass TestCases:\n def get(self):\n return [\n (\n [1, 0, 2, 3, 0, 4, 5, 0],\n [1, 0, 0, 2, 3, 0, 0, 4]\n ),\n (\n [0, 1, 0, 2, 0],\n [0, 0, 1, 0, 0]\n ),\n (\n [0, 0],\n [0, 0]\n ),\n (\n [1, 0],\n [1, 0]\n ),\n (\n [1, 2, 3],\n [1, 2, 3]\n ),\n ]\n\n\nif __name__ == \"__main__\":\n solution = Solution()\n\n for test_case, expected_result in TestCases().get():\n solution.duplicateZeros(arr=test_case)\n assert all(i == j for i, j in zip(test_case, expected_result)) is True\n","repo_name":"dgreda/leetcode","sub_path":"fun_with_arrays/duplicate_zeros.py","file_name":"duplicate_zeros.py","file_ext":"py","file_size_in_byte":1559,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"40"} +{"seq_id":"3305879112","text":"# -*- coding:utf-8 -*-\nimport time\nimport requests\n\nfrom config.game_server_config import platform_server_info\nfrom config.mapping_conf import platform_str_mapping\nfrom core.views import ResetView\n\n\nclass SendMail(ResetView):\n def post(self, request, *args, **kwargs):\n return self._do(request, *args, **kwargs)\n\n def get(self, request, *args, **kwargs):\n return self._do(request, *args, **kwargs)\n\n def _do(self, request, *args, **kwargs):\n from django.http import QueryDict\n _body = self.request.body\n _body = _body.replace(';', '%3B')\n parameter_info = QueryDict(_body)\n channelRange = parameter_info[\"channelRange\"] # 渠道范围\n channelId = parameter_info[\"channelId\"] # 渠道ID\n sendType = parameter_info[\"sendType\"] # 发送对象\n platformId = parameter_info[\"platformId\"] # 平台\n serverId = parameter_info[\"serverId\"] # 区服\n roleId = parameter_info[\"roleId\"] # 角色ID\n sender = parameter_info[\"sender\"] # 发件人\n title = parameter_info[\"title\"] # 标题\n content = parameter_info[\"content\"] # 内容\n items = str(parameter_info[\"items\"]) # 奖励道具列表\n startTime = parameter_info[\"startTime\"] # 开始时间\n endTime = parameter_info[\"endTime\"] # 结束时间\n startTime = int(time.mktime(time.strptime(startTime, \"%Y-%m-%d %H:%M:%S\")))\n endTime = int(time.mktime(time.strptime(endTime, \"%Y-%m-%d %H:%M:%S\")))\n\n platformId = platform_str_mapping.get(platformId, platformId)\n\n response_dic = {\n \"status\": \"success\", # 处理结果编码\n \"code\": 1, # 处理结果\n \"info\": \"\", # 错误信息\n \"roleName\": \"\", # 角色名称\n } # 基础返回数据\n\n if not platform_server_info.get(platformId, None): # 判断平台游戏服务器是否存在\n response_dic.update({\"status\": \"fail\", \"code\": 0, \"info\": \"platformId err\"})\n return self.HttpResponse(response_dic)\n\n platform_conf = platform_server_info[platformId]\n url = \"http://%s:%s/platform_server/sendmail\" % (\n platform_conf[\"host\"], platform_conf[\"port\"])\n send_parameter = {\"channelRange\": channelRange, \"channelId\": channelId, \"sendType\": sendType,\n \"serverId\": serverId, \"roleId\": roleId, \"sender\": sender, \"title\": title, \"content\": content,\n \"items\": items, \"startTime\": startTime, \"endTime\": endTime, \"test\": [1, 2], \"test2\": []}\n http_info = requests.post(url, send_parameter)\n if http_info.status_code != 200:\n response_dic.update({\"info\": \"server conn err\", \"status\": \"fail\", \"code\": 0})\n return self.HttpResponse(response_dic)\n http_response_info = self.json_loads(http_info.text)\n if http_response_info[\"code\"] != 1:\n http_response_info[\"status\"] = \"fail\"\n response_dic.update(http_response_info)\n return self.HttpResponse(response_dic)","repo_name":"houguangdong/djcode","sub_path":"bma_server/app/logics/mail/sendmail.py","file_name":"sendmail.py","file_ext":"py","file_size_in_byte":3047,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"40"} +{"seq_id":"38569315075","text":"\nfrom time import sleep\nfrom random import random\nfrom threading import Thread\n\nimport pytest\nfrom wasp_c_extensions.cmcqueue import WCMCQueue, WCMCQueueItem\n\n\nclass TestWCMCQueue:\n\n def test_auto_ack(self):\n q = WCMCQueue()\n assert(q.messages() == 0)\n\n q.push(1)\n assert(q.messages() == 0)\n\n token1 = q.subscribe()\n assert(isinstance(token1, WCMCQueueItem) is True)\n assert(q.messages() == 1)\n assert(token1.pull() is None)\n assert(q.messages() == 1) # there are no changes in the queue, it has the last token event\n\n q.push('2')\n assert(q.messages() == 2)\n assert(token1.pull() == '2')\n assert(q.messages() == 1)\n assert(token1.pull() is None)\n\n token2 = q.subscribe()\n assert(q.messages() == 2)\n\n assert(token1.pull() is None)\n assert(q.messages() == 1) # all tokens point to the same last message\n\n q.push(3)\n q.push(4)\n q.push(5)\n assert(token1.pull() == 3)\n assert(token1.pull() == 4)\n assert(token2.pull() == 3)\n assert(token2.pull() == 4)\n assert(token2.pull() == 5)\n assert(token1.pull() == 5)\n\n token1.unsubscribe()\n assert(q.messages() == 2) # no clean up process yet\n token2.unsubscribe()\n assert(q.messages() == 0) # no live tokens anymore\n pytest.raises(RuntimeError, token1.unsubscribe) # unable to unsubscribe twice\n pytest.raises(RuntimeError, token2.pull) # unable to pull unsubscribed object\n\n def test_manual_ack(self):\n q = WCMCQueue(manual_acknowledge=True)\n assert(q.messages() == 0)\n\n q.push(1)\n assert(q.messages() == 0)\n\n token1 = q.subscribe()\n assert(isinstance(token1, WCMCQueueItem) is True)\n assert(q.messages() == 1)\n assert(token1.pull() is None)\n assert(q.messages() == 1) # there are no changes in the queue, it has the last token event\n assert(token1.acknowledge() is False)\n\n q.push('2')\n assert(q.messages() == 2)\n assert(token1.pull() == '2')\n assert(q.messages() == 2) # 1->2\n assert(token1.pull() == '2') # None - > '2' it is there still\n\n assert(token1.acknowledge() is True)\n assert(q.messages() == 1)\n assert(token1.pull() is None)\n assert(q.messages() == 1)\n\n token2 = q.subscribe()\n assert(q.messages() == 2)\n\n assert(token1.pull() is None)\n assert(q.messages() == 2) # ack is False because there is no user payload but internal message truncated\n assert(token1.acknowledge() is False)\n assert(q.messages() == 1) # ack is False because there is no user payload but internal message truncated\n\n q.push(3)\n token1.unsubscribe()\n token2.unsubscribe()\n q.push(4)\n assert(q.messages() == 0)\n\n def test_item(self):\n pytest.raises(RuntimeError, WCMCQueueItem)\n\n def test_next(self):\n q = WCMCQueue()\n token1 = q.subscribe()\n pytest.raises(TypeError, next, token1)\n\n q = WCMCQueue(manual_acknowledge=True)\n token1 = q.subscribe()\n pytest.raises(StopIteration, next, token1) # no elements to iterate\n\n q.push(1)\n q.push(2)\n q.push(3)\n\n assert(next(token1) == 1)\n assert(next(token1) == 2)\n assert(next(token1) == 3)\n pytest.raises(StopIteration, next, token1) # no elements to iterate\n\n q.push(4)\n q.push(5)\n\n assert(next(token1) == 1)\n assert(next(token1) == 2)\n assert(next(token1) == 3)\n\n token1.acknowledge() # acknowledge resets iteration\n assert(next(token1) == 2)\n assert(next(token1) == 3)\n assert(next(token1) == 4)\n assert(next(token1) == 5)\n pytest.raises(StopIteration, next, token1) # no elements to iterate\n\n assert(next(token1) == 2)\n assert(next(token1) == 3)\n assert(next(token1) == 4)\n token1.unsubscribe()\n pytest.raises(RuntimeError, next, token1) # unable to iterate unsubscribed tokens\n\n def test_iter(self):\n q = WCMCQueue()\n token1 = q.subscribe()\n pytest.raises(TypeError, iter, token1)\n\n q = WCMCQueue(manual_acknowledge=True)\n token1 = q.subscribe()\n iter(token1) # it is ok\n assert([] == [x for x in iter(token1)])\n assert([] == [x for x in token1])\n\n q.push(1)\n q.push(2)\n q.push(3)\n\n token1.acknowledge()\n assert([2, 3] == [x for x in token1])\n\n\nclass TestWCMCQueueConcurrency:\n __test_running__ = False\n __threads_count__ = 50\n __input_sequence__ = [int(random() * 10) for _ in range(10 ** 4)]\n __wait_pause__ = 0.01\n\n class Subscriber:\n\n def __init__(self, queue):\n self.queue = queue\n self.token = queue.subscribe()\n self.result = []\n\n def thread_fn(self):\n while TestWCMCQueueConcurrency.__test_running__:\n if not self.token.has_next():\n sleep(TestWCMCQueueConcurrency.__wait_pause__)\n item = self.token.pull()\n if item is not None:\n self.result.append(item)\n\n while self.token.has_next():\n item = self.token.pull()\n if item is not None:\n self.result.append(item)\n\n @pytest.mark.parametrize('runs', range(5))\n def test_concurrency(self, runs):\n subscribers = []\n queue = WCMCQueue()\n\n def pub_thread():\n for v in TestWCMCQueueConcurrency.__input_sequence__:\n queue.push(v)\n\n pub_thread = Thread(target=pub_thread)\n sub_threads = []\n for i in range(TestWCMCQueueConcurrency.__threads_count__):\n s = TestWCMCQueueConcurrency.Subscriber(queue)\n subscribers.append(s)\n sub_threads.append(Thread(target=s.thread_fn))\n\n TestWCMCQueueConcurrency.__test_running__ = True\n pub_thread.start()\n for th in sub_threads:\n th.start()\n\n pub_thread.join()\n TestWCMCQueueConcurrency.__test_running__ = False\n for th in sub_threads:\n th.join()\n\n for s in subscribers:\n assert(s.result == TestWCMCQueueConcurrency.__input_sequence__)\n","repo_name":"a1ezzz/wasp-c-extensions","sub_path":"tests/wasp_c_extensions_cmcqueue_test.py","file_name":"wasp_c_extensions_cmcqueue_test.py","file_ext":"py","file_size_in_byte":6364,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"40"} +{"seq_id":"6827538276","text":"\"\"\"Business logic for processing Grobid extracted references.\"\"\"\n\nimport re\nimport io\nimport xml.etree.ElementTree\nfrom xml.etree.ElementTree import Element\nfrom typing import List, Dict\n\nfrom arxiv.base import logging\nfrom references.domain import Reference\n\nlogger = logging.getLogger(__name__)\n\nRE_XMLNS = re.compile(r'^[{](.*?)[}].*')\nXMLNS = 'http://www.tei-c.org/ns/1.0'\n\n\ndef _xml_set_ns(root: Element) -> None:\n global XMLNS\n XMLNS = RE_XMLNS.findall(root.tag)[0]\n\n\ndef _xml_tag(tag: str) -> str:\n return '{{{xmlns}}}{tag}'.format(xmlns=XMLNS, tag=tag)\n\n\ndef _xml_path_elem(elem: Element, path: str) -> List[Element]:\n path = '/'.join([xt(i) for i in path.split('/')])\n return elem.findall(path)\n\n\ndef _xml_path_attr(elem: Element, path: str, attrib: str) -> str:\n found = _xml_path_elem(elem, path)\n return ' '.join([\n f.attrib.get(attrib, '') for f in found if f is not None\n ])\n\n\ndef _xml_path_text(elem: Element, path: str) -> str:\n found = _xml_path_elem(elem, path)\n return ' '.join([\n f.text for f in found if f is not None and f.text is not None\n ])\n\n\nxt = _xml_tag\n\n\ndef _xml_format_biblStruct(bbl: Element) -> dict:\n \"\"\"\n Given a TEI biblStruct, format the reference to our schema.\n\n Note that once again, the extraction process seems to have trouble.\n Therefore, we must case out the presence of and \n sections, straying from the strict definitions in TEI.\n\n Parameters\n ----------\n bbl : xml.etree.ElementTree\n A particular part of the xml tree corresponding to a TEI:biblStruct\n\n Returns\n -------\n reference_metadata : dict\n A single schema formatted reference line\n \"\"\"\n def _authors(bbl: Element, path: str) -> List[Dict[str, str]]:\n authors = []\n for elem in _xml_path_elem(bbl, path):\n first = ' '.join(map(lambda x: x.text, elem.iter(xt('forename')))) # type: ignore\n last = ' '.join(map(lambda x: x.text, elem.iter(xt('surname')))) # type: ignore\n auth = {\n 'givennames': first,\n 'surname': last\n }\n authors.append(auth)\n return authors\n\n if _xml_path_elem(bbl, 'analytic'):\n # we have an article that is part of a collection or journal\n authors = _authors(bbl, 'analytic/author')\n title = _xml_path_text(bbl, 'analytic/title')\n source = _xml_path_text(bbl, 'monogr/title')\n elif _xml_path_elem(bbl, 'monogr'):\n # we have a book or mis-labelled article\n authors = _authors(bbl, 'monogr/author')\n title = _xml_path_text(bbl, 'monogr/title')\n source = _xml_path_text(bbl, 'monogr/imprint/publisher')\n\n # no matter what, these values come the monogr section\n year = _xml_path_attr(\n bbl, 'monogr/imprint/date[@type=\"published\"]', 'when'\n )\n pages = '{}-{}'.format(\n _xml_path_attr(bbl, 'monogr/imprint/biblScope[@unit=\"page\"]', 'from'),\n _xml_path_attr(bbl, 'monogr/imprint/biblScope[@unit=\"page\"]', 'to')\n )\n volume = _xml_path_text(bbl, 'monogr/imprint/biblScope[@unit=\"volume\"]')\n issue = _xml_path_text(bbl, 'monogr/imprint/biblScope[@unit=\"issue\"]')\n\n if pages == '-':\n pages = ''\n\n return {\n 'authors': authors,\n 'title': title,\n 'year': year,\n 'pages': pages,\n 'source': source,\n 'volume': volume,\n 'issue': issue,\n }\n\n\ndef format_grobid_output(output: bytes) -> List[Reference]:\n \"\"\"\n Transform GROBID output to internal metadata struct.\n\n Take the output of GROBID and return the metadata in the format expected by\n the references schema. For a description of TEI, Text Encoding Initiative\n (the format of the XML), see the documentation on the website\n (particularly, the bibliography section):\n\n http://www.tei-c.org/release/doc/tei-p5-doc/en/html/ref-biblStruct.html\n\n Parameters\n ----------\n output : dict\n The output of the GROBID API call, structured dict of metadata\n\n Returns\n -------\n metadata : list\n List of reference metadata (dict) conforming to references schema.\n \"\"\"\n filestring = io.StringIO(output.decode('utf-8'))\n root = xml.etree.ElementTree.parse(filestring).getroot()\n _xml_set_ns(root)\n\n # make sure we are only dealing with the final reference list\n try:\n listbbl = list(root.iter(tag=xt('listBibl')))[0]\n except IndexError:\n msg = 'GROBID output does not contain references'\n logger.error(msg)\n raise IndexError(msg)\n\n blank_reference = {\n 'identifiers': [{'identifier_type': '', 'identifier': ''}],\n 'raw': '', 'volume': '', 'issue': '', 'pages': '', 'reftype': '',\n 'doi': '', 'authors': [], 'title': '', 'year': '', 'source': '',\n }\n\n # ========================================================================\n # iterate over the references in that list\n references = []\n for bbl in listbbl.iter(tag=xt('biblStruct')):\n reference = dict(blank_reference)\n reference.update(_xml_format_biblStruct(bbl))\n references.append(Reference(**reference)) # type: ignore\n\n return references\n","repo_name":"arXiv/arxiv-references","sub_path":"references/services/grobid/parse.py","file_name":"parse.py","file_ext":"py","file_size_in_byte":5204,"program_lang":"python","lang":"en","doc_type":"code","stars":6,"dataset":"github-code","pt":"40"} +{"seq_id":"7073103066","text":"import optuna\nimport pandas as pd\nimport xgboost as xgb\nfrom sklearn import svm, datasets\nfrom sklearn.model_selection import GridSearchCV \nfrom sklearn.model_selection import train_test_split\nfrom sklearn.metrics import mean_squared_error, mean_absolute_error\nimport logging\nimport sys\nimport numpy as np\nfrom pandas.core.frame import DataFrame\ntest = pd.read_pickle('test_add_cate.pkl')\ntrain = pd.read_pickle('train_add_cate.pkl')\nlabel = train['price']\ntrain = train.drop(['price'],axis=1)\n# train = train.drop(['listing_id','make_model_combined','svd9_category','suggested_price','price'],axis=1)\n# test = test.drop(['listing_id','make_model_combined','suggested_price','svd9_category'],axis=1)\n\nX_train,X_test,y_train,y_test = train_test_split(train,label,test_size=0.2,random_state=111)\ndata_train = xgb.DMatrix(X_train.fillna(-1), label=y_train)\ndata_test = xgb.DMatrix(X_test.fillna(-1), label=y_test)\ndata_rmse_test = xgb.DMatrix(X_test.fillna(-1))\ntest_DMatrix = xgb.DMatrix(test.fillna(-1))\nwatch_list = [(data_test, 'eval'), (data_train, 'train')]\n\n# train = pd.read_csv('train_data3.csv',index_col=0)\n# test = pd.read_csv('test_data3.csv',index_col=0)\n# feature_use=['make',\n# 'model',\n# 'type_of_vehicle',\n# 'transmission',\n# 'curb_weight',\n# 'power',\n# 'fuel_type',\n# 'engine_cap',\n# 'no_of_owners',\n# 'depreciation',\n# 'coe',\n# 'dereg_value',\n# 'mileage',\n# 'omv',\n# 'des1',\n# 'des2',\n# 'des3',\n# 'des4',\n# 'des5',\n# 'des6',\n# 'des7',\n# 'fea1',\n# 'fea2',\n# 'fea3',\n# 'fea4',\n# 'fea5',\n# 'fea6',\n# 'fea7',\n# 'acc1',\n# 'acc2',\n# 'acc3',\n# 'acc4',\n# 'acc5',\n# 'acc6',\n# 'acc7',\n# 'engine_type',\n# 'coe_validity',\n# 'low_mileage',\n# 'warranty',\n# 'reg_year',\n# 'reg_month',\n# 'vintage cars',\n# 'coe car',\n# 'consignment car',\n# 'sta evaluated car',\n# 'sgcarmart warranty cars',\n# 'low mileage car',\n# 'electric cars',\n# 'direct owner sale',\n# 'parf car',\n# 'opc car',\n# 'premium ad car',\n# 'hybrid cars',\n# 'imported used vehicle',\n# 'almost new car',\n# 'rare & exotic',\n# 'lifespan_year',\n# 'lifespan_month',\n# 'usable_days',\n# 'car_age',\n# 'make_target_mean',\n# 'model_target_mean',\n# 'type_of_vehicle_target_mean',\n# 'fuel_type_target_mean',\n# 'transmission_target_mean']\n\n# X_train,X_test,y_train,y_test = train_test_split(train[feature_use],train['price'],test_size=0.02,random_state=111)\n# data_train = xgb.DMatrix(X_train.fillna(-1), label=y_train)\n# data_test = xgb.DMatrix(X_test.fillna(-1), label=y_test)\n# data_rmse_test = xgb.DMatrix(X_test.fillna(-1))\n# test_DMatrix = xgb.DMatrix(test.fillna(-1))\n# watch_list = [(data_test, 'eval'), (data_train, 'train')]\n\ndef train_xgboost(trial):\n param = {\n 'max_depth': trial.suggest_int(\"max_depth\", 8, 30), \n 'eta': 0.01, \n 'silent': 1, \n 'gamma':trial.suggest_float(\"gamma\", 0, 0.8),\n 'objective': 'reg:linear',\n 'reg_alpha':trial.suggest_float(\"reg_alpha\", 0, 100),\n 'reg_lambda':trial.suggest_float(\"reg_lambda\", 0, 100),\n# 'num_boost_round':trial.suggest_int(\"num_boost_round\", 800, 3000),\n 'subsample':trial.suggest_float(\"subsample\", 0.5, 1),\n 'colsample_bytree':0.6,\n 'min_child_weight':trial.suggest_int(\"min_child_weight\", 1, 30)\n }\n print(param)\n bst = xgb.train(param, data_train, num_boost_round=trial.suggest_int(\"num_boost_round\", 800, 3000),evals=watch_list)\n rmse = np.sqrt(mean_squared_error(y_test.tolist(),list(bst.predict(data_rmse_test))))\n res = {\n\n 'Predicted':list(bst.predict(test_DMatrix))\n }\n res=DataFrame(res)\n res.to_csv('model_saving4/xgboost_res_'+str(trial.number)+'.csv')\n return rmse\n\noptuna.logging.get_logger(\"optuna\").addHandler(logging.StreamHandler(sys.stdout))\nstudy_name = \"xgboost-study4\" # Unique identifier of the study.\nstorage_name = \"sqlite:///{}.db\".format(study_name)\nstudy = optuna.create_study(study_name=study_name, storage=storage_name, pruner=optuna.pruners.MedianPruner())\nstudy.enqueue_trial(\n {\n \"max_depth\": 11,\n \"gamma\": 0,\n \"reg_alpha\": 1,\n \"reg_lambda\": 1,\n \"num_boost_round\": 1500,\n \"subsample\": 0.9,\n \"min_child_weight\": 3,\n }\n)\n\n'''\nparam = {\n 'max_depth': 11, \n 'eta': 0.01, \n 'silent': 1, \n 'gamma':0,\n 'objective': 'reg:linear',\n 'reg_alpha':1,\n 'reg_lambda':1,\n 'num_boost_round':1500,\n 'subsample':0.9,\n 'colsample_bytree':0.6,\n 'min_child_weight':3\n }\n'''\n\nimport logging\nimport sys\n\n# optuna.logging.get_logger(\"optuna\").addHandler(logging.StreamHandler(sys.stdout))\nstudy.optimize(train_xgboost, n_trials=5000)","repo_name":"yichenCY/sgCarMart_Kaggle_Competition","sub_path":"Price_prediction/src/optuna_test.py","file_name":"optuna_test.py","file_ext":"py","file_size_in_byte":4827,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"40"} +{"seq_id":"15241626934","text":"from julia import Main\n# For some reason, I need to do 'using REopt' right after 'from julia import Main' otherwise\n# I get an open SSL error\n# This adds the latest version of the feature branch of REopt.jl, but could be done in docker build if it was stable\nMain.eval('using Pkg; Pkg.add(url = \"https://github.com/NREL/REopt.jl\", rev = \"handle-urdb-matrix\")')\nMain.eval('using REopt')\nimport json\nimport numpy as np\n\ndef urdb_type_conversion(urdb_response):\n for k, v in urdb_response.items():\n if type(v) is tuple:\n if type(v[0]) is tuple:\n arr = []\n for i, n in enumerate(v): \n if type(n[0]) is dict:\n for m in n:\n if \"max\" in m:\n if m[\"max\"] > 1e15:\n m[\"max\"] = 1e15\n arr.append(np.array(n, dtype=dict))\n #if \"flatdemandstructure\" in k:\n # Append extra element to trick REopt\n # arr.append(np.array(n, dtype=dict).tolist())\n elif \"schedule\" in k:\n arr.append(np.array(n, dtype=int))\n else:\n arr.append(np.array(n))\n urdb_response[k] = np.array(arr)\n else:\n if \"flatdemandmonths\" in k:\n urdb_response[k] = np.array(v, dtype=int)\n else:\n urdb_response[k] = np.array(v)\n \n return urdb_response\n\nwith open(\"urdb_response.json\", \"r\") as read_file:\n print(\"Converting JSON encoded data into Python dictionary\")\n urdb_response = json.load(read_file)\n\nurdb_response = urdb_type_conversion(urdb_response)\n\nMain.eval('using JSON')\n\nMain.urdb_response = urdb_response \n\n# Create a URDBRate struct with this external/outer constructor\n# This may error or be wrong without the matrix -> array conversions\nMain.eval('urdb_rate = REopt.URDBrate(urdb_response, 2017)')\n\n# How to actually check that e.g. demandweekdayschedule is converted properly from matrix to array?\n# demandweekdayschedule is not a field of URDBRate struct\nMain.eval('println(urdb_rate.demandweekdayschedule[2][16])')","repo_name":"Bill-Becker/reopt_pyjulia","sub_path":"test_urdb.py","file_name":"test_urdb.py","file_ext":"py","file_size_in_byte":2261,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"40"} +{"seq_id":"23515343482","text":"# Problem 21 - Amicable numbers\n#\n# Let d(n) be defined as the sum of proper divisors of n\n# (numbers less than n which divide evenly into n).\n\n# If d(a) = b and d(b) = a, where a ≠ b, then a and b are an\n# amicable pair and each of a and b are called amicable numbers.\n\n# For example, the proper divisors of 220 are 1, 2, 4, 5, 10, 11,\n# 20, 22, 44, 55 and 110; therefore d(220) = 284. The proper divisors\n# of 284 are 1, 2, 4, 71 and 142; so d(284) = 220.\n\n# Evaluate the sum of all the amicable numbers under 10000.\n\nimport time\nimport math\n\n\ndef divisor_sum(num):\n num_sqr = math.ceil(math.sqrt(num))\n divisors = [1]\n\n for i in range(2, num_sqr + 1):\n if num % i == 0 and i * i != num:\n divisors.append(i)\n divisors.append(int(num / i))\n elif i * i == num:\n divisors.append(i)\n\n return sum(divisors)\n\n\nstart_time = time.time()\n\nall_divisors_sums = dict()\namicable_divisor_sums = dict()\nlimit = 10000\n\nfor n in range(1, limit + 1):\n all_divisors_sums[n] = divisor_sum(n)\n\nfor n in range(1, limit + 1):\n this_sum = all_divisors_sums[n]\n\n if 1 < this_sum <= 10000 and n != this_sum:\n friend_sum = all_divisors_sums[this_sum]\n\n if n == friend_sum:\n amicable_divisor_sums[n] = this_sum\n amicable_divisor_sums[this_sum] = n\n\nprint(amicable_divisor_sums)\nanswer = sum(amicable_divisor_sums)\n\nprint(\"Problem 21: \" + str(answer))\nprint(\"{} ms\".format(round(1000 * (time.time() - start_time))))\n","repo_name":"crybx/project-euler","sub_path":"python/problem_021.py","file_name":"problem_021.py","file_ext":"py","file_size_in_byte":1495,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"40"} +{"seq_id":"31987041025","text":"import math\nimport random\n\nrandom.seed(0)\n\n\ndef rand(a, b):\n return (b - a) * random.random() + a\n\n#创建一个指定大小的矩阵\ndef make_matrix(m, n, fill=0.0):\n mat = []\n for i in range(m):\n mat.append([fill] * n)\n return mat\n\n#定义sigmod 函数和它的倒数\ndef sigmoid(x):\n return 1.0 / (1.0 + math.exp(-x))\n\n\ndef sigmoid_derivative(x):\n return x * (1 - x)\n\n#定义BPNeuralNetwork类\nclass BPNeuralNetwork:\n def __init__(self):\n #输入层\n self.input_n = 0\n #隐含层\n self.hidden_n = 0\n #输出层\n self.output_n = 0\n self.input_cells = []\n self.hidden_cells = []\n self.output_cells = []\n self.input_weights = []\n self.output_weights = []\n self.input_correction = []\n self.output_correction = []\n\n#初始化神经网络\n def setup(self, ni, nh, no):\n self.input_n = ni + 1\n self.hidden_n = nh\n self.output_n = no\n # 初始化神经元\n self.input_cells = [1.0] * self.input_n\n self.hidden_cells = [1.0] * self.hidden_n\n self.output_cells = [1.0] * self.output_n\n # 初始化权值\n self.input_weights = make_matrix(self.input_n, self.hidden_n)\n self.output_weights = make_matrix(self.hidden_n, self.output_n)\n # random activate\n for i in range(self.input_n):\n for h in range(self.hidden_n):\n self.input_weights[i][h] = rand(-0.2, 0.2)\n for h in range(self.hidden_n):\n for o in range(self.output_n):\n self.output_weights[h][o] = rand(-2.0, 2.0)\n # init correction matrix\n self.input_correction = make_matrix(self.input_n, self.hidden_n)\n self.output_correction = make_matrix(self.hidden_n, self.output_n)\n\n#定义predict方法进行一次前馈 并返回输��\n def predict(self, inputs):\n # 激活输入层\n for i in range(self.input_n - 1):\n self.input_cells[i] = inputs[i]\n # 激活隐含层\n for j in range(self.hidden_n):\n total = 0.0\n for i in range(self.input_n):\n total += self.input_cells[i] * self.input_weights[i][j]\n self.hidden_cells[j] = sigmoid(total)\n # 激活输出层\n for k in range(self.output_n):\n total = 0.0\n for j in range(self.hidden_n):\n total += self.hidden_cells[j] * self.output_weights[j][k]\n self.output_cells[k] = sigmoid(total)\n return self.output_cells[:]\n\n#定义一次反响传播和更新权值的过程,并返回最终预测误差\n def back_propagate(self, case, label, learn, correct):\n # 前馈\n self.predict(case)\n # 获取输出层误差\n output_deltas = [0.0] * self.output_n\n for o in range(self.output_n):\n error = label[o] - self.output_cells[o]\n output_deltas[o] = sigmoid_derivative(self.output_cells[o]) * error\n #获取隐含层误差\n hidden_deltas = [0.0] * self.hidden_n\n for h in range(self.hidden_n):\n error = 0.0\n for o in range(self.output_n):\n error += output_deltas[o] * self.output_weights[h][o]\n hidden_deltas[h] = sigmoid_derivative(self.hidden_cells[h]) * error\n # 更新输出权重\n for h in range(self.hidden_n):\n for o in range(self.output_n):\n change = output_deltas[o] * self.hidden_cells[h]\n self.output_weights[h][o] += learn * change + correct * self.output_correction[h][o]\n self.output_correction[h][o] = change\n # 更新输入权重\n for i in range(self.input_n):\n for h in range(self.hidden_n):\n change = hidden_deltas[h] * self.input_cells[i]\n self.input_weights[i][h] += learn * change + correct * self.input_correction[i][h]\n self.input_correction[i][h] = change\n # 获取全局误差\n error = 0.0\n for o in range(len(label)):\n error += 0.5 * (label[o] - self.output_cells[o]) ** 2\n return error\n\n#定义train方法控制迭代\n# limit:最大迭代次数\n# learn:学习率\n# correct:矫正率\n def train(self, cases, labels, limit=10000, learn=0.05, correct=0.1):\n for j in range(limit):\n error = 0.0\n for i in range(len(cases)):\n label = labels[i]\n case = cases[i]\n error += self.back_propagate(case, label, learn, correct)\n#利用BPNN学习异或逻辑\n def test(self):\n cases = [\n [0, 0],\n [0, 1],\n [1, 0],\n [1, 1],\n ]\n labels = [[0], [1], [1], [0]]\n self.setup(2, 5, 1)\n self.train(cases, labels, 10000, 0.05, 0.1)\n for case in cases:\n print(self.predict(case))\n\n\nif __name__ == '__main__':\n nn = BPNeuralNetwork()\n nn.test()\n'''\n[0.030152448584251753]\n[0.9640072675811762]\n[0.9660646638773007]\n[0.03636092800912755]\n'''","repo_name":"crr121/BP-neural-network","sub_path":"src/BPNN.py","file_name":"BPNN.py","file_ext":"py","file_size_in_byte":5060,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"40"} +{"seq_id":"37100927463","text":"#! -*- coding: utf-8\n# literumilo_check_word.py - (kontrolu_vorton)\n#\n# This file has functions which check the spelling of an Esperanto word.\n#\n# Author: Klivo Lendon\n# Last edit date: 2020-05-01\n#\n\nimport os, sys\nfrom .literumilo_entry import *\nfrom .literumilo_ending import *\nfrom .literumilo_suffix import check_suffix\nfrom .literumilo_morpheme_list import MorphemeList\nfrom .literumilo_scan_morphemes import scan_morphemes\nfrom .literumilo_utils import *\nfrom .literumilo_load import load_dictionary\n\nesperanto_dictionary = load_dictionary()\n\n# AnalysisResult\n# 'word' has the original word divided into morphemes, eg. 'mis.dir.it.a'.\n# valid is True if the word is a valid Esperanto word. (correctly spelled)\n\nclass AnalysisResult:\n def __init__(self, original, word, valid):\n \"\"\"\n Params:\n original word\n word - divided into morphemes\n valid - True or False\n \"\"\"\n self.word = restore_capitals(original, word)\n self.valid = valid\n\ndef check_synthesis(rest_of_word, dictionary, index, morpheme_list, last_morpheme):\n \"\"\"check_synthesis (kontrolu sintezon)\n This method checks the synthesis of suffixes when they are found,\n and other morphemes (prefixes, roots) after the word has been\n completely divided, by calling scan_morphemes().\n Params:\n rest of word\n dictionary\n index of morpheme (int)\n list of morphemes\n last_morpheme (t/f)\n Return:\n True if valid, False otherwise\n \"\"\"\n\n entry = morpheme_list.get(index)\n if not entry: return False\n\n syn = entry.synthesis\n morph = entry.morpheme\n\n if syn == Synthesis.Suffix and not check_suffix(morph, index, morpheme_list):\n return False\n\n if not last_morpheme:\n # Divide the rest of the word into morphemes.\n if find_morpheme(rest_of_word, dictionary, index + 1, morpheme_list):\n return True\n return False\n\n if last_morpheme:\n # Check prefixes (and limited morphemes) after the word has been\n # divided, because the validity of a prefix depends on the morphemes\n # which come after it.\n return scan_morphemes(morpheme_list)\n\n return False\n # end of check_synthesis()\n\n\ndef find_morpheme(rest_of_word, dictionary, index, morpheme_list):\n \"\"\"find_morpheme (trovu_radikon)\n This function divides a (presumably) compound word into morphemes,\n while checking synthesis. It is recursive.\n Params:\n rest_of_word - the remainder to be analyzed\n dictionary - a map of word data\n index of morpheme (indekso de radiko)\n morpheme_list - holds a list of previously collected morphemes\n Return:\n True for valid synthesis, False for invalid.\n \"\"\"\n\n if len(rest_of_word) == 0:\n return False\n\n if index >= MorphemeList.MAX_MORPHEMES:\n return False\n\n if index > 0:\n entry = dictionary.get(rest_of_word)\n if entry:\n # Do we allow this morpheme to join with others?\n if entry.synthesis != Synthesis.No:\n morpheme_list.put(index, entry)\n valid = check_synthesis(rest_of_word, dictionary, index, morpheme_list, True)\n if valid: return True\n\n length_of_word = len(rest_of_word)\n min_length = 2; # minimum length of a morpheme\n max_length = length_of_word - 2\n\n # Try to find a valid morpheme, by dividing the rest of the word.\n for size in range(max_length, min_length - 1, -1):\n morpheme = rest_of_word[0:size]\n entry = dictionary.get(morpheme)\n if entry:\n # Do we allow this morpheme to join with others?\n if entry.synthesis != Synthesis.No:\n rest_of_word2 = rest_of_word[size:] # Careful, rest_of_word != rest_of_word2\n morpheme_list.put(index, entry)\n valid = check_synthesis(rest_of_word2, dictionary, index, morpheme_list, False)\n if valid: return True\n\n # Sometimes there is a separator (a grammatical ending) between morphemes.\n # This is usually done to aid pronunciation. Instead of 'fingr.montri.', most would\n # write 'fingr.o.montr.i'. Other examples are: ĝust.a.temp.e, unu.a.foj.e, etc.\n # This algorithm will accept one separator per word. It must be 'o', 'a' or 'e'.\n if index == 0 or length_of_word < 3: return False\n separator_entry = EspDictEntry.new_separator(rest_of_word[0])\n if separator_entry:\n morpheme_list.put(index, separator_entry)\n rest_of_word2 = rest_of_word[1:]\n valid = check_synthesis(rest_of_word2, dictionary, index, morpheme_list, False)\n if valid: return True\n\n return False\n\ndef check_word(original_word):\n \"\"\"This function tests whether a word is correctly spelled.\n Params:\n original word\n dictionary - a map of word data\n Return:\n AnalysisResult\n \"\"\"\n\n if len(original_word) == 1: # Just a letter or hyphen.\n if is_word_char(original_word):\n return AnalysisResult(original_word, original_word, True)\n else:\n return AnalysisResult(original_word, original_word, False)\n\n # Check for abbreviations, such as n-r.oj, s-in.oj\n if len(original_word) > 2:\n second_char = original_word[1]\n if is_hyphen(second_char):\n entry = esperanto_dictionary.get(original_word)\n if entry:\n return AnalysisResult(original_word, entry.morpheme, True)\n else:\n return AnalysisResult(original_word, original_word, False)\n\n original_word = remove_hyphens(original_word)\n\n # Lower case for analysis.\n word = original_word.lower()\n length_of_word = len(word)\n\n # Exceptions.\n # A few words cause difficulties for the algorithm, especially accusative pronouns.\n # For example, the pronoun 'vin' means 'you' (accusative), but it is also the root for 'wine' (vino).\n # I want the pronoun to divided as 'vi.n' and the beverage to be 'vin.o' (not vi.n.o). The dictionary\n # has 'vin' as a key, but the keys in a dictionary must be unique. To solve this problem, some\n # pronouns (etc.) will be excluded from the dictionary, and handled as exceptions here.\n\n if length_of_word < 5:\n if (word == \"ĝin\"): return AnalysisResult(original_word, \"ĝi.n\", True)\n if (word == \"lin\"): return AnalysisResult(original_word, \"li.n\", True)\n if (word == \"min\"): return AnalysisResult(original_word, \"mi.n\", True)\n if (word == \"sin\"): return AnalysisResult(original_word, \"si.n\", True)\n if (word == \"vin\"): return AnalysisResult(original_word, \"vi.n\", True)\n if (word == \"lian\"): return AnalysisResult(original_word, \"li.an\", True)\n if (word == \"cian\"): return AnalysisResult(original_word, \"ci.an\", True)\n\n # First, check the dictionary for words which have no\n # grammatical ending, eg. 'ne', 'dum', 'post'.\n entry = esperanto_dictionary.get(word)\n if entry:\n if entry.without_ending == WithoutEnding.Yes:\n return AnalysisResult(original_word, entry.morpheme, True)\n\n ending = get_ending(word)\n if ending == None:\n return AnalysisResult(original_word, word, False)\n else:\n length = length_of_word - ending.length\n word_without_ending = word[0:length]\n entry = esperanto_dictionary.get(word_without_ending)\n if entry:\n if entry.with_ending == WithEnding.Yes:\n word_with_ending = entry.morpheme + \".\" + ending.ending\n return AnalysisResult(original_word, word_with_ending, True)\n else:\n # The root was not found. Maybe it's a compound word.\n # Do a morphological analysis.\n\n # The morpheme list needs the ending for later analysis.\n morpheme_list = MorphemeList(ending)\n\n valid_word = find_morpheme(word_without_ending, esperanto_dictionary, 0, morpheme_list)\n\n if valid_word:\n display_form = morpheme_list.display_form()\n return AnalysisResult(original_word, display_form, True)\n else:\n return AnalysisResult(original_word, word, False)\n\n return AnalysisResult(original_word, word, False)\n\n# check_word\n","repo_name":"Indrikoterio/literumilo-python","sub_path":"literumilo/literumilo_check_word.py","file_name":"literumilo_check_word.py","file_ext":"py","file_size_in_byte":8280,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"40"} +{"seq_id":"27636159859","text":"import pandas as pd\r\nimport numpy as np\r\nfrom flask import *\r\nimport pickle\r\nfrom sklearn.ensemble import RandomForestClassifier\r\nfrom sklearn.model_selection import train_test_split\r\nfrom sklearn.metrics import accuracy_score\r\napp=Flask(__name__)\r\npickle_in=open('model.pkl','rb')\r\nclassifier=pickle.load(pickle_in)\r\n# df=pd.read_csv(r'E:\\Work_Data\\titanic.csv')\r\n# X = df[['Age', 'Fare', 'Sex', 'sibsp', 'Pclass']]\r\n# y = df[['2urvived']]\r\nprint('------------------')\r\n# X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.3, random_state=53)\r\n# X_train.isnull().sum()\r\n\r\n@app.route('/')\r\ndef index():\r\n return render_template('index.html')\r\n@app.route('/model')\r\ndef model():\r\n # print('------------------')\r\n # df=pd.read_csv(r'E:\\Work_Data\\titanic.csv')\r\n #\r\n # print('$$$$$$$$$$$$$$$$$$$')\r\n # X_train.dropna(axis=0,inplace=True)\r\n # X_test.dropna(axis=0,inplace=True)\r\n # model = RandomForestClassifier()\r\n # model.fit(X_train, y_train)\r\n # y_prd = model.predict(X_test)\r\n # dd=accuracy_score(y_prd, y_test)\r\n # print(dd)\r\n return render_template('services.html')\r\n@app.route('/prediction',methods=['POST','GET'])\r\ndef prediction():\r\n print('ssssss')\r\n if request.method == 'POST':\r\n print('mmmm')\r\n f1=request.form['f1']\r\n f2=request.form['f2']\r\n f3=request.form['f3']\r\n f4=request.form['f4']\r\n f5=request.form['f5']\r\n print('kkkk')\r\n val=[int(f1),int(f2),int(f3),int(f4),int(f5)]\r\n model=RandomForestClassifier()\r\n # model.fit(X_train,y_train)\r\n # filename = 'finalized_model.sav'\r\n # pickle.dump(model, open(filename, 'wb'))\r\n # print('llll')\r\n\r\n # filename = 'finalized_model.sav'\r\n # pickle_in = open('model.pkl', 'rb')\r\n # loaded_model = pickle.load(open(filename, 'rb'))\r\n result = classifier.predict([val])\r\n print('llll')\r\n # result=model.predict([val])\r\n print(result)\r\n if result==0:\r\n a='Survived'\r\n else:\r\n a='Not Survived'\r\n return render_template('portfolio.html',result=result)\r\n return render_template('portfolio.html')\r\n\r\n\r\nif __name__=='__main__':\r\n app.run(host='0.0.0.0', port = 8000)\r\n\r\n","repo_name":"seerammouli/Titanic-Docker","sub_path":"main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":2268,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"40"} +{"seq_id":"41130109078","text":"from tensorflow import keras\nimport os\nimport cv2\nimport numpy as np\n\nLABELS = ['apple', 'banana', 'beetroot', 'bell pepper', 'cabbage', 'capsicum',\n 'carrot', 'cauliflower', 'chilli pepper', 'corn', 'cucumber', 'eggplant',\n 'garlic', 'ginger', 'grapes', 'jalepeno', 'kiwi', 'lemon', 'lettuce',\n 'mango', 'onion', 'orange', 'paprika', 'pear', 'peas', 'pineapple',\n 'pomegranate', 'potato', 'raddish', 'soy beans', 'spinach', 'sweetcorn',\n 'sweetpotato', 'tomato', 'turnip', 'watermelon']\n\n\ndef load_model():\n model = keras.models.load_model('model/model.keras')\n return model\n\n\ndef to_array(image):\n image_array = cv2.imread(image, cv2.IMREAD_COLOR)\n image_resized = cv2.resize(image_array, (100, 100))\n return image_resized\n\n\ndef predict(image):\n print(\">>> Loading the model...\")\n model = load_model()\n print(\">>> Loading successful !\")\n print(\">>> image to array... \")\n image = to_array(image)\n print(\">>> Transformation successful !\")\n print(\">>> Predicting...\")\n image_reshaped = image.reshape(-1, 100, 100, 3)\n index_pred = np.argmax(model.predict(image_reshaped), axis=-1)[0]\n prediction = LABELS[index_pred]\n if prediction in ['apple', 'eggplant', 'onion', 'orange']:\n return print(f\" This image is an {prediction}\")\n return print(f\" This image is a {prediction}\")\n\n\nif __name__ == \"__main__\":\n image_test = f\"raw_data/test/apple/Image_3.jpg\"\n predict(image_test)\n","repo_name":"DamienBusson/FandV_recognition","sub_path":"FandV_recognition/trainer.py","file_name":"trainer.py","file_ext":"py","file_size_in_byte":1451,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"40"} +{"seq_id":"27174467005","text":"from osgeo import gdal, osr,ogr\nimport numpy as np\nimport json\n\ndef vectorize_raster(geoJsonFileName,array2d,layerName=\"BuildingID\",fieldName=\"BuildingID\"):\n \n\n memdrv = gdal.GetDriverByName('MEM')\n src_ds = memdrv.Create('', array2d.shape[1], array2d.shape[0], 1)\n band = src_ds.GetRasterBand(1)\n band.WriteArray(array2d)\n\n dst_layername = \"BuildingID\"\n drv = ogr.GetDriverByName(\"geojson\")\n dst_ds = drv.CreateDataSource(geoJsonFileName)\n dst_layer = dst_ds.CreateLayer(layerName, srs=None)\n\n fd = ogr.FieldDefn(fieldName, ogr.OFTInteger)\n dst_layer.CreateField(fd)\n dst_field = 0\n\n gdal.Polygonize(band, None, dst_layer, dst_field, [], callback=None)\n\n \n \n return\ndef predict_score_batch(temporary_fold,batch_y,prediction):\n '''\n Spacenet IoU metrics: explained in https://github.com/SpaceNetChallenge/utilities\n '''\n minPolygonSize=5\n \n tot_score_batch=0\n tot_f1_score_batch=0\n tot_ious_batch=0\n\n for i in range(len(batch_y)):\n vectorize_raster(temporary_fold+str(i)+'_test_gt.geojson',batch_y[i])\n vectorize_raster(temporary_fold+str(i)+'_test_pred.geojson',prediction[i])\n with open(temporary_fold+str(i)+'_test_gt.geojson') as f:\n geojson_groundtruth = json.load(f)\n with open(temporary_fold+str(i)+'_test_pred.geojson') as f:\n geojson_prediction = json.load(f)\n \n\n \n M=len(geojson_prediction['features'])\n N=len(geojson_groundtruth['features'])\n# print('Image %d: %d predictions proposed and %d groundtruth'%(i,M,N))\n score=0\n IOUs_sum=0\n for feature_pred in geojson_prediction['features']: \n IoUs=[]\n IoUs_accu=[]\n \n# print(ogr.CreateGeometryFromJson(json.dumps(feature_pred['geometry'])).GetArea())\n# print('Polygone')\n \n for feature_gt in geojson_groundtruth['features']:\n# print(ogr.CreateGeometryFromJson(json.dumps(feature_gt['geometry'])).GetArea())\n poly1=ogr.CreateGeometryFromJson(json.dumps(feature_gt['geometry']))\n poly2=ogr.CreateGeometryFromJson(json.dumps(feature_pred['geometry']))\n intersection = poly1.Intersection(poly2)\n union = poly1.Union(poly2)\n if intersection is None:\n IoUs.append(0.0)\n else:\n IoUs.append(intersection.GetArea()/union.GetArea())\n \n IoUs=np.asarray(IoUs)\n# print(IoUs)\n IoUs_accu=(IoUs>0.5).astype(int)*IoUs\n# print(IoUs_accu)\n if (IoUs_accu.size and np.amax(IoUs_accu)>0):\n index=np.argmax(IoUs_accu)\n# print('index %d'%index)\n geojson_groundtruth['features'].remove(geojson_groundtruth['features'][index])\n# print('new size groundtruth %d'%len(geojson_groundtruth['features']))\n score+=1\n IOUs_sum+=IoUs[index]\n# print('score: %f: '%score)\n# print('IOUs_sum: %f: '%IOUs_sum)\n tot_ious_batch+=IOUs_sum/N\n tot_score_batch+=score/N\n tot_f1_score_batch+=2*score/(M+N)\n tot_ious_batch/=len(batch_y)\n tot_score_batch/=len(batch_y)\n tot_f1_score_batch/=len(batch_y)\n return tot_score_batch*100,tot_f1_score_batch*100,tot_ious_batch\n\n ","repo_name":"melissande/dhi-segmentation-buildings","sub_path":"IOU_computations.py","file_name":"IOU_computations.py","file_ext":"py","file_size_in_byte":3408,"program_lang":"python","lang":"en","doc_type":"code","stars":10,"dataset":"github-code","pt":"40"} +{"seq_id":"32279605495","text":"st=\"K1KA5CB7\"\nst2=\"AJKDLSI412K4JSJ9D\"\n\nprint(chr(57))\n\ndef maker(st):\n num=0\n word=[]\n answer=\"\"\n for i in range(len(st)):\n if ord(st[i])<=90 and ord(st[i])>=65:\n word.append(st[i])\n\n if ord(st[i])<=57 and ord(st[i])>=48:\n # print(st[i])\n num+=int(st[i])\n word.sort()\n for i in word:\n answer+=i\n answer+=str(num)\n # print(num,word)\n print(answer)\nmaker(st)","repo_name":"kimth007kim/python_algorithm","sub_path":"this_is_coding_test_2회차/Part12 구현문제/12-08 문자열 재정렬.py","file_name":"12-08 문자열 재정렬.py","file_ext":"py","file_size_in_byte":437,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"40"} +{"seq_id":"1573384544","text":"import time\nimport urllib.request\nimport asyncio\nimport aiohttp\n\nURL = 'https://api.github.com/events'\nMAX_CLIENTS = 3\n\n\ndef fetch_sycn(pid):\n print(f'Fetch sync process {pid} started')\n start = time.time()\n response = urllib.request.urlopen(URL)\n datetime = response.getheader('Date')\n\n print(f'Process {pid}: {datetime}, took: {time.time() - start:.2f} seconds')\n\n return datetime\n\n\nasync def fetch_async(pid):\n print('Fetch async process {} started'.format(pid))\n start = time.time()\n session = aiohttp.ClientSession()\n response = await session.get(URL)\n datetime = response.headers.get('Date')\n\n print(f'Process {pid}: {datetime}, took: {time.time() - start:.2f} seconds')\n\n session.close()\n return datetime\n\n\ndef synchronous():\n start = time.time()\n for i in range(1, MAX_CLIENTS + 1):\n fetch_sycn(i)\n print(f'Process took: {time.time() - start:.2f} seconds')\n\n\nasync def asynchronous():\n start = time.time()\n tasks = [asyncio.ensure_future(\n fetch_async(i)) for i in range(1, MAX_CLIENTS + 1)]\n await asyncio.wait(tasks)\n print(f\"Process took: {time.time() - start:.2f} seconds\")\n\n\nprint('Synchronous:')\nsynchronous()\n\nprint('Asynchronous:')\nioloop = asyncio.get_event_loop()\nioloop.run_until_complete(asynchronous())\nioloop.close()\n","repo_name":"AleksandrTsimbulov/common","sub_path":"acyncio/aiothhpexample.py","file_name":"aiothhpexample.py","file_ext":"py","file_size_in_byte":1316,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"40"} +{"seq_id":"18140634627","text":"from random import randint\nfrom pickle import load\nfrom keras.models import load_model\nfrom keras.preprocessing.sequence import pad_sequences\nimport json\nimport re\n\n# load doc into memory\ndef load_doc(filename):\n # open the file as read only\n file = open(filename, 'r')\n # read all text\n text = file.read()\n # close the file\n file.close()\n return text\n\n# generate a sequence from a language model\ndef generate_seq(model, tokenizer, seq_length, seed_text, n_words):\n result = list()\n in_text = seed_text\n # generate a fixed number of words\n for _ in range(n_words):\n # encode the text as integer\n encoded = tokenizer.texts_to_sequences([in_text])[0]\n # truncate sequences to a fixed length\n encoded = pad_sequences([encoded], maxlen=seq_length, truncating='pre')\n # predict probabilities for each word\n yhat = model.predict_classes(encoded, verbose=0)\n # map predicted word index to word\n out_word = ''\n for word, index in tokenizer.word_index.items():\n if index == yhat:\n out_word = word\n break\n # append to input\n in_text += ' ' + out_word\n result.append(out_word)\n return ' '.join(result)\n\ndef format_text(input_text):\n punc = ['.', '!', '?', '...']\n names = [\n 'harry',\n 'draco',\n 'snape',\n 'michael',\n 'anthony',\n 'goldstein',\n 'vernon',\n 'russell',\n 'crookshanks',\n 'mcgonagall',\n 'scamander',\n 'newt',\n 'warren',\n 'queenie',\n 'ron',\n 'fred',\n 'remus',\n 'clarkson',\n 'jack',\n 'gary',\n 'voldemort',\n 'hagrid',\n 'trump',\n 'donald',\n 'tonks',\n 'dean',\n 'thomas',\n 'lupin',\n 'elizabeth',\n 'luna',\n 'harambe',\n 'teddy',\n 'myrtle',\n 'jim',\n 'moaning',\n 'dumbledore',\n 'muggle',\n 'salem',\n 'arthur',\n 'graves',\n 'grindelwald',\n 'norris',\n 'sirius',\n 'black',\n 'rowling',\n 'albus',\n 'lily',\n 'dursley'\n ]\n replacements = [\n ['its', 'it\\'s'],\n ['i', 'I'],\n ['hogwarts', 'Hogwarts'],\n ['theyre', 'they\\'re'],\n ['american', 'American'],\n ['america', 'America'],\n ['scottish', 'Scottish'],\n ['scotland', 'Scotland'],\n ['england', 'England'],\n ['italy', 'Italy'],\n ['gryffindor', 'Gryffindor'],\n ['gryffindors', 'Gryffindors'],\n ['slytherin', 'Slytherin'],\n ['slytherins', 'Slytherins'],\n ['hufflepuff', 'Hufflepuff'],\n ['hufflepuffs', 'Hufflepuffs'],\n ['ravenclaw', 'Ravenclaw'],\n ['lgbt', 'LGBT'],\n ['nomaj', 'no-maj'],\n ['mrs', 'Mrs'],\n ['scotlandteam', 'Scotland Rugby Team'],\n ['timetravelling', 'time-travelling'],\n ['horcrux', 'Horcrux'],\n ['uk', 'UK'],\n ['phoenix', 'Phoenix'],\n ['thats', 'that\\'s'],\n ['youd', 'you\\'d'],\n ['horcruxreceptacle', 'Horcrux receptacle'],\n ['theyve', 'they\\'ve'],\n ['shes', 'she\\'s'],\n ['nomajes', 'no-majes'],\n ['philosophers', 'Philosophers'],\n ['couldnt', 'couldn\\'t'],\n ['jewish', 'Jewish'],\n ['new york', 'New York'],\n ['arent', 'aren\\'t'],\n ['im', 'I\\'m'],\n ['cant', 'can\\'t'],\n ['jk', 'JK'],\n ['dont', 'don\\'t'],\n ['youre', 'you\\'re'],\n ['wouldnt', 'wouldn\\'t']\n ]\n\n puncreplacements = [\n ['puncfullstoppunc', '.'],\n ['punccommapunc', ','],\n ['puncexclamationpunc', '!'],\n ['puncquestionpunc', '?'],\n ['puncelipsispunc', '...'],\n ['punccolonpunc', ':'],\n ['puncsemicolonpunc', ';'],\n ['puncampersandpunc', ' &'],\n ['puncstoppunc', '\\n']\n ]\n\n text = ''\n\n while (text == ''):\n text = ' ' + input_text + ' '\n\n for replacement in replacements:\n text = text.replace(' ' + replacement[0] + ' ', ' ' + replacement[1] + ' ')\n\n for name in names:\n text = text.replace(' ' + name + ' ', ' ' + name.capitalize() + ' ')\n text = text.replace(' ' + name + 's ', ' ' + name.capitalize() + '\\'s ')\n \n for puncreplacements in puncreplacements:\n text = text.replace(' ' + puncreplacements[0], puncreplacements[1])\n\n text = re.sub(r'([.!?]) ([a-zA-Z0-9])', sub_match, text)\n\n punctuation = punc[randint(0, len(punc) - 1)]\n\n text = text[:-1].lstrip(' .,!?:;&')\n\n while len(text) + len(punctuation) > 140:\n text = text.rsplit(' ', 1)[0]\n \n\n text = text[0].capitalize() + text[1:] + punctuation\n\n return text\n\ndef sub_match(match):\n return match.group(1) + ' ' + match.group(2).upper()\n\n\ndef generate_text(model, tokenizer, seq_length, lines, n_words):\n data = ''\n while (data == ''):\n seed_text = lines[randint(0, len(lines) - 1)]\n data = format_text(generate_seq(model, tokenizer, seq_length, seed_text, n_words)).split('\\n')[0]\n\n return data\n\n# load cleaned text sequences\nin_filename = 'tmp/data_sequences.txt'\ndoc = load_doc(in_filename)\nlines = doc.split('\\n')\nseq_length = len(lines[0].split()) - 1\n\ngenerated = {}\n\nfor i in range(1, 10):\n accuracy = i / 10\n accuracy_str = str(accuracy)\n\n # load the model\n model = load_model('tmp/model-' + accuracy_str + '.h5')\n # load the tokenizer\n tokenizer = load(open('tmp/tokenizer-' + accuracy_str + '.pkl', 'rb'))\n\n generated[accuracy_str] = []\n\n # generate new text\n num_vals = 500\n for i in range(num_vals):\n # append generated text\n generated_text = generate_text(model, tokenizer, seq_length, lines, 30)\n generated[accuracy_str].append(generated_text)\n print('.', end='', flush=True)\n\n print()\n print('Generated', num_vals, 'tweets at', accuracy_str, 'accuracy')\n print('Example:')\n print(generated[accuracy_str][randint(0, len(generated[accuracy_str]) - 1)])\n\nwith open('../data/data.json', 'w') as outfile:\n json.dump(generated, outfile)","repo_name":"Accudio/jk-rowling-bot","sub_path":"neural-network/generate.py","file_name":"generate.py","file_ext":"py","file_size_in_byte":5577,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"40"} +{"seq_id":"36421285516","text":"#/usr/bin/python\n# -*- coding:utf-8 -*-\n# 작성자 : 한석현\n\n\nfrom matplotlib import pyplot as plt\n\ndef Ex1():\n x_val = [0, 1, 2, 3, 4]\n y_val = [0, 1, 4, 9, 4]\n plt.plot(x_val, y_val)\n plt.show()\n\n\ndef Ex2():\n x_values = [0, 1, 2, 3, 4, 5, 10]\n y_values_1 = [10, 12, 12, 10, 14, 22, 24]\n y_values_2 = [11, 14, 15, 15, 22, 21, 12]\n plt.plot(x_values, y_values_1, 'o')\n plt.plot(x_values, y_values_2)\n plt.show()\n\n\ndef Legend():\n plt.plot([0, 1, 2, 3, 4], [0, 1, 4, 9, 16])\n plt.plot([0, 1, 2, 3, 4], [0, 1, 8, 27, 64])\n plt.legend(['parabola', 'cubic'], loc=10)\n plt.show()\n\n#loc=?\n#0: best\n#1: upper right\n#2: upper left\n#3: lower left\n#4: lower right\n#5: right\n#6: center left\n#7: center right\n#8: lower center\n#9: upper center\n#10: center\n\ndef Legend2():\n plt.plot([0, 1, 2, 3, 4], [0, 1, 4, 9, 16], label=\"parabola\")\n plt.plot([0, 1, 2, 3, 4], [0, 1, 8, 27, 64], label=\"cubic\")\n plt.legend() # 꼭 적어줘야 한다.\n plt.show()\n\ndef lineStyle():\n#https://www.w3schools.com/colors/colors_names.asp\n#https://www.w3schools.com/colors/colors_picker.asp\n \n # A circle:\n #plt.plot(x_values, y_values, marker='o')\n # A square:\n #plt.plot(x_values, y_values, marker='s')\n # A star:\n #plt.plot(x_values, y_values, marker='*')\n\n # Dashed:\n #plt.plot(x_values, y_values, linestyle='--')\n # Dotted:\n #plt.plot(x_values, y_values, linestyle=':')\n # No line:\n #plt.plot(x_values, y_values, linestyle='')\n\n x_values = [0, 1, 2, 3, 4, 5, 10]\n y_values_1 = [10, 12, 12, 10, 14, 22, 24]\n y_values_2 = [11, 14, 15, 15, 22, 21, 12]\n plt.plot(x_values, y_values_1, color='green', linestyle='--')\n plt.plot(x_values, y_values_2, color='#AAAAAA', marker='o')\n plt.show()\n\ndef Title():\n #x\n hours = [9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20]\n #y\n happiness = [9.8, 9.9, 9.2, 8.6, 8.3, 9.0, 8.7, 9.1, 7.0, 6.4, 6.9, 7.5]\n\n # X Y\n plt.plot(hours, happiness)\n\n plt.xlabel('Time of day')\n plt.ylabel('Happiness Rating (out of 10)')\n\n plt.title('My Self-Reported Happiness While Awake')\n plt.show()\n\ndef Subplot():#다단 나누기\n x = [1, 2, 3, 4]\n y = [1, 2, 3, 4]\n\n # First Subplot\n plt.subplot(1, 2, 1)\n plt.plot(x, y, color='green')\n plt.title('First Subplot')\n\n # Second Subplot\n plt.subplot(1, 2, 2)\n plt.plot(x, y, color='steelblue')\n plt.title('Second Subplot')\n\n # Display both subplots\n plt.show()\n\ndef Subplot2():\n x = range(7)\n a = [0, 1, 2, 3, 4, 5, 6]\n b = [0, 1, 4, 9, 16, 25, 36]\n c = [0, 1, 8, 27, 64, 125, 216]\n\n plt.subplot(2,1,1)\n plt.plot(x, a)\n plt.subplot(2,2,3)\n plt.plot(x, b)\n plt.subplot(2,2,4)\n plt.plot(x, c)\n plt.show()\n\n#subplot의 세부적인 위치는 plt.subplots_adjust()로 조절\n#left — 왼쪽 마진, 기본값 0.125. y축 레이블이 표시될 공간을 확보\n#right — 오른쪽 마진, 기본값 0.9. 그래프 이미지(figure)을 넉넉하게 \n# 반대로 줄일 경우 항목 레이블(legend)를 위한 공간을 확보\n#bottom — 아래쪽 마진, 기본값 0.1. 눈금이나 x 축 레이블이 표시될 공간을 확보\n#top — 위쪽 마진, 기본값 0.9.\n#wspace — 가로로 인접한 subplot 사이 공간, 기본값 0.2.\n#hspace — 세로로 인접한 subplot 사이 공간, 기본값 0.2.\n#\n#ex)\n#plt.subplots_adjust(wspace=0.35)\n#plt.show()\n\ndef Axis():\n# plt.axis() 안에 리스트를 넣어 x축, y축 각각의 최대값/최소값을 지정\n# [x축 최소값, x축 최대값, y축 최소값, y축 최대값] 형태 \n\n x = [0, 1, 2, 3, 4]\n y = [0, 1, 4, 9, 16]\n plt.plot(x, y)\n plt.axis([0, 3, 2, 5])\n plt.show()\n\ndef Tick():\n #눈금\n # ax = plt.subplot()<==> ax = plt.subplot(1, 1, 1) 동일함\n\n plt.plot([0, 1, 2, 3, 4], [0, 1, 4, 9, 16])\n plt.plot([0, 1, 2, 3, 4], [0, 1, 8, 27, 64])\n ax = plt.subplot()\n \n #특정 눈금만 표시\n ax.set_xticks([1, 2, 4])\n plt.show()\n\ndef Tick2():\n plt.plot([1, 3, 3.5], [0.1, 0.6, 0.8], 'o')\n ax = plt.subplot()\n ax.set_yticks([0.1, 0.6, 0.8]) #y축특정눈금 표시\n ax.set_yticklabels(['10%', '60%', '80%'])\n plt.savefig('sample.png')\n plt.show()\n\n\n# graphSize\n# plt.figure() 안에 figsize=(width, height)를 직접 적어 넣으면 그래프 크기를 조정\n# ex)\n# plt.figure(figsize=(4, 10))\n\n# delete\n# plt.close('all')\n\n# savefig():\n# plt.savefig('sample.png')\n\n\nif __name__ == '__main__':\n \n# Ex2()\n# Legend2()\n# lineStyle()\n# Title()\n# Subplot2()\n Tick2()\n","repo_name":"shhan0226/Algorithms-Python","sub_path":"Matplotlib/line.py","file_name":"line.py","file_ext":"py","file_size_in_byte":4588,"program_lang":"python","lang":"ko","doc_type":"code","stars":0,"dataset":"github-code","pt":"40"} +{"seq_id":"30236862534","text":"#!/usr/bin/env python3\n# -*- coding: utf-8 -*-\n\"\"\"\nCreated on Mon Jan 3 08:17:38 2022\n\n@author: shavak\n\"\"\"\n\nimport numpy as np\n\nE = {}\nV = {}\n\ndef add_edge(u, v):\n global E\n if u not in E.keys():\n E[u] = []\n E[u].append(v)\n\ndef add_visitation_policy(u):\n global V\n if u not in V.keys():\n V[u] = 2 if u == u.lower() else np.inf\n \nwith open(\"input.txt\", \"r\") as f:\n for line in f:\n x = [s.strip() for s in line.split(\"-\")]\n add_edge(x[0], x[1]) \n add_edge(x[1], x[0])\n add_visitation_policy(x[0])\n add_visitation_policy(x[1])\n\nV[\"end\"] = 1\npath = [\"start\"]\nptr = [0]\nV[\"start\"] = 0\nnum_paths = 0\ndouble_dragon = False\n\nwhile path:\n x = path[-1]\n if x == \"end\":\n num_paths += 1\n V[path.pop()] += 1\n ptr.pop()\n else:\n n = len(E[x])\n y = \"\"\n while ptr[-1] < n:\n y = E[x][ptr[-1]]\n if V[y] > (0 if (not double_dragon or y == \"end\") else 1):\n break\n ptr[-1] += 1\n if ptr[-1] == n:\n y = path.pop()\n V[y] += 1\n if (y != \"start\" and y != \"end\" and V[y] == 1):\n double_dragon = False\n ptr.pop()\n else:\n path.append(y)\n V[y] -= 1\n double_dragon = double_dragon or (V[y] == 0 and y != \"end\")\n ptr[-1] += 1\n ptr.append(0)\n\nprint(\"Answer = {}\".format(num_paths))","repo_name":"shavak/advent_of_code","sub_path":"2021/Day_12/day_12b.py","file_name":"day_12b.py","file_ext":"py","file_size_in_byte":1453,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"40"} +{"seq_id":"2172385741","text":"# -*- coding: utf-8 -*-\nimport scrapy\nfrom News.items import NewsItem\n\n\nclass NewsSpider(scrapy.Spider):\n name = 'news'\n allowed_domains = ['eeada.cn']\n start_urls = ['http://www.eeada.cn/'] # 今日关注\n\n def parse(self, response): # 获取新闻列表\n article_list = response.xpath(\"//*[@id='content']//article\")\n # print(article_list)\n for article in article_list:\n item = NewsItem()\n item[\"title\"] = article.xpath(\".//h2/a/@title\").extract_first()\n item[\"href\"] = article.xpath(\".//h2/a/@href\").extract_first()\n item[\"date\"] = article.xpath(\".//span/text()\").extract_first().strip(\" \").strip('\\r\\n')\n\n yield scrapy.Request(\n item[\"href\"],\n callback=self.parse_detail,\n meta={\"item\": item}\n )\n # 翻页\n next_url = response.xpath(\"//*[@id='content']//a[@class='next page-numbers']/@href\").extract_first()\n #print(next_url)\n if next_url is not None:\n yield scrapy.Request(\n next_url,\n callback=self.parse\n )\n\n def parse_detail(self, response): # 处理详情页\n item = response.meta[\"item\"]\n item[\"text\"] = response.xpath(\"//div[@id='content']//p//text()\").extract()\n item[\"text\"] = [str.strip(\" \").strip('\\r\\n').replace(u'\\u3000', u'').replace(u'\\xa0', u'') for str in\n item[\"text\"]]\n item[\"text\"] = ''.join(item[\"text\"])\n item[\"source\"] = \"今日关注\"\n yield item\n","repo_name":"shadow131/PycharmProjects","sub_path":"News/News/spiders/news.py","file_name":"news.py","file_ext":"py","file_size_in_byte":1569,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"40"} +{"seq_id":"8503316813","text":"# Problem: Given two strings check to see if they are anagrams. Anagram is when the two strings can be written using the exact same letters.\n# For example:\n# \"public relations\" is an anagram of \"crap built on lies.\"\n# \"clint eastwood\" is an anagram of \"old west action\"\ndef anagram(s1, s2):\n # remove spaces and make lowercase\n s1 = s1.replace(\" \", \"\").lower() \n s2 = s2.replace(\" \", \"\").lower()\n \n # Return boolean for sorted match. \n return sorted(s1) == sorted(s2)\n\nprint(anagram(\"clint eastwood\", \"old west action\"))\n\n\n# doing the same thing with a dictionary\ndef anagram_dict(s1, s2):\n # remove spaces and make lowercase\n s1 = s1.replace(\" \", \"\").lower()\n s2 = s2.replace(\" \", \"\").lower()\n \n # checl if the length of the strings are not equal\n if len(s1) != len(s2):\n return False\n \n # create a dictionary for each string\n count = {}\n\n for letter in s1: # loop through string 1\n if letter in count:\n count[letter] += 1 # add one to the value\n else:\n count[letter] = 1 # add the letter to the dictionary with a value of 1\n\n for letter in s2: # loop through string 2\n if letter in count:\n count[letter] -= 1 # subtract one from the value\n else:\n count[letter] = 1 # add the letter to the dictionary with a value of 1 \n\n for k in count: # loop through the dictionary\n if count[k] != 0: # if the value is not 0\n return False # return false\n\n return True # return true if all values are 0\n\n \nprint(anagram_dict(\"clint eastwood\", \"old west action\"))","repo_name":"shemar100/coding_challenge","sub_path":"anagram.py","file_name":"anagram.py","file_ext":"py","file_size_in_byte":1607,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"40"} +{"seq_id":"29089561478","text":"# A demo of networking inside of pygame\nimport pygame\nimport socket\n\nHOST = '127.0.0.1' # Server hostname\nPORT = 1234 # Server port\n\nsize = (500,500)\ntitle = 'Networking demo'\n\nBLACK = (0,0,0)\nWHITE = (255,255,255)\n\nclass Player():\n def __init__(self,x,y):\n self.x = x\n self.y = y\n \n def draw(self,screen):\n rect = pygame.Rect(self.x, self.y, 20, 100)\n pygame.draw.rect(screen, BLACK, rect) \n \ndef sendUpdate(socket,command):\n # Update the box position on the server side\n print(\"sending update\")\n data = {'direction': command}\n socket.sendall(data)\n\ndef drawElements(data, player, screen): \n # Fetch elements from the server and draw them\n print(\"making stuff\")\n x,y = data['player'] \n player.x = x\n player.y = y\n player.draw(screen)\n print(\"Done making stuff\")\n\n\n\n\ndef main():\n # Connect to the server\n pygame.init()\n screen = pygame.display.set_mode(size)\n pygame.display.set_caption(title)\n \n clock = pygame.time.Clock()\n with socket.socket(socket.AF_INET, socket.SOCK_STREAM) as s:\n s.connect((HOST, PORT))\n print('Running')\n \n screen.fill(WHITE)\n pygame.display.flip()\n clock.tick(5)\n player = Player(100,100)\n player.draw(screen)\n pygame.display.flip()\n clock.tick(5)\n \n while True:\n events = pygame.event.get()\n for event in events:\n print(event.type)\n if event.type == pygame.KEYDOWN:\n print('pressed')\n sendUpdate(socket, 'DOWN')\n data = s.recv(1024)\n if data:\n drawElements(data, player, screen)\n pygame.display.flip()\n clock.tick(5)\n \nif __name__ == '__main__':\n main()\n","repo_name":"StanTheMan132/pygame_networking_demo","sub_path":"client.py","file_name":"client.py","file_ext":"py","file_size_in_byte":1806,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"40"} +{"seq_id":"41462286418","text":"import torch\nfrom transformers import RobertaTokenizer, RobertaModel\n\n\nPLM_MODEL = \"microsoft/codebert-base\"\n\n\ndef nlpl2vec(nlpl_list: list[str],\n tokenizer: RobertaTokenizer,\n model: RobertaModel):\n \"\"\"\n\n :param nlpl_list: .\n :param tokenizer: Codebert RobertaTokenizer object from HF.\n :param model: Codebert RobertaModel object from HF.\n :return:\n \"\"\"\n with torch.no_grad():\n\n tokens = [tokenizer.cls_token]\n\n for s in nlpl_list:\n tokens.extend(tokenizer.tokenize(s))\n tokens.append(tokenizer.sep_token)\n\n tokens_ids = tokenizer.convert_tokens_to_ids(tokens)\n context_embeddings = model(torch.tensor(tokens_ids)[None, :])[0]\n\n return context_embeddings\n\n","repo_name":"goncalocapelalopes/kaggle_ai4code","sub_path":"lm.py","file_name":"lm.py","file_ext":"py","file_size_in_byte":755,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"40"} +{"seq_id":"19196677598","text":"# -*- coding: utf-8 -*-\n\nfrom LearnModule import StringSplit\n\n# 定义一个过滤的行政区划名表\n#\nfilter_province = ('省', '市', '自治区')\nfilter_city = ('区', '县')\nfilter_towns = ('街道', '镇', '乡', '回民乡')\nfilter_street = ('社区','村')\n\nclass wordlist(object): #定义一个词表内词输出的类\n\n def __init__(self,word_name,word_nominal,word_freq,word_note):\n self.word_name = word_name\n self.word_nominal = word_nominal\n self.word_freq = word_freq\n self.word_note = word_note\n\nclass toponymy(object): #定义一个地名词的类\n\n def __init__(self,province,city,towns,street):\n self.province = province\n self.city = city\n self.towns = towns\n self.street = street\n\n def alias_province(self):\n alias_province_list = []\n for astr in filter_province:\n if(len(self.province) > len(astr) and len(self.province) > 2):\n filter_index = len(self.province) - len(astr)\n if(self.province.find(astr) == filter_index):\n alias_province_list.append(self.province[:filter_index])\n if (alias_province_list):\n return alias_province_list\n else:\n return None\n\n def alias_city(self):\n alias_city_list = []\n for astr in filter_city:\n if (len(self.city) > len(astr) and len(self.city) > 2):\n filter_index = len(self.city) - len(astr)\n if(self.city.find(astr) == filter_index):\n alias_city_list.append(self.city[:filter_index])\n if(alias_city_list):\n return alias_city_list\n else:\n return None\n\n def alias_towns(self):\n alias_towns_list = []\n for astr in filter_towns:\n if (len(self.towns) > len(astr) and len(self.towns) > 2):\n filter_index = len(self.towns) - len(astr)\n if(self.towns.find(astr) == filter_index):\n alias_towns_list.append(self.towns[:filter_index])\n if (alias_towns_list):\n return alias_towns_list\n else:\n return None\n\n def alias_street(self):\n alias_street_list = []\n for astr in filter_street:\n if (len(self.street) > len(astr) and len(self.street) > 2):\n filter_index = len(self.street) - len(astr)\n if(self.street.find(astr) == filter_index):\n alias_street_list.append(self.street[:filter_index])\n if (alias_street_list):\n return alias_street_list\n else:\n return None\n\ntoponymy_list = []\nthe_towns = '-'\nwith open('C:/Users/flyingaura/Desktop/昌平区.dat', mode = 'rb') as in_file:\n the_province = '北京市'\n the_city = in_file.readline().decode('utf-8').strip()\n for rec in in_file.readlines():\n rec_data = rec.decode('utf-8').strip()\n if ('\\t' in rec_data):\n rec_TS = StringSplit.stringsplit(rec_data,'\\t')\n the_towns = rec_TS[0]\n rec_street = rec_TS[1].strip('\\\"')\n else:\n rec_street = rec_data.strip('\\\"')\n\n if(rec_street):\n for the_street in StringSplit.stringsplit(rec_street,'、'):\n rec_toponymy = toponymy(the_province, the_city, the_towns, the_street)\n toponymy_list.append(rec_toponymy)\n\n# for rec_ty in toponymy_list:\n# print('============ %s' %rec_ty.street)\n\nprovince_list = []\ncity_list = []\ntowns_list = []\nstreet_list = []\nAprovince_list = []\nAcity_list = []\nAtowns_list = []\nAstreet_list = []\n\nfor A_toponymy in toponymy_list:\n if(A_toponymy.province not in Aprovince_list):\n province_list.append(wordlist(A_toponymy.province, 'tag', 1000, A_toponymy.province))\n Aprovince_list.append(A_toponymy.province)\n alias_PL = A_toponymy.alias_province()\n if(alias_PL):\n for A_province in alias_PL:\n if(A_province not in Aprovince_list):\n province_list.append(wordlist(A_province, 'tag', 1000, A_toponymy.province))\n Aprovince_list.append(A_province)\n # print(province_list)\n\n if (A_toponymy.city not in Acity_list):\n city_list.append(wordlist(A_toponymy.city, 'tag', 1000, A_toponymy.province))\n Acity_list.append(A_toponymy.city)\n alias_CL = A_toponymy.alias_city()\n if(alias_CL):\n for A_city in alias_CL:\n if (A_city not in Acity_list):\n city_list.append(wordlist(A_city, 'tag', 1000, A_toponymy.province))\n Acity_list.append(A_city)\n\n if (A_toponymy.towns not in Atowns_list):\n towns_list.append(wordlist(A_toponymy.towns, 'tag', 1000, A_toponymy.city))\n Atowns_list.append(A_toponymy.towns)\n alias_TL = A_toponymy.alias_towns()\n if(alias_TL):\n for A_towns in alias_TL:\n if (A_towns not in Atowns_list):\n towns_list.append(wordlist(A_towns, 'tag', 1000, A_toponymy.city))\n Atowns_list.append(A_towns)\n\n # if (A_toponymy.street not in street_list):\n street_list.append(wordlist(A_toponymy.street, 'tag', 1000, A_toponymy.towns))\n alias_SL = A_toponymy.alias_street()\n if(alias_SL):\n for A_street in alias_SL:\n # if (A_street not in street_list):\n street_list.append(wordlist(A_street, 'tag', 1000, A_toponymy.towns))\n\nwith open('C:/Users/flyingaura/Desktop/北京地址1.txt', mode = 'a') as out_file:\n for A_province in province_list:\n print('%s\\t%s\\t%d\\t%s' %(A_province.word_name, A_province.word_nominal,\n A_province.word_freq, A_province.word_note))\n out_file.write('%s\\t%s\\t%d\\t%s\\n' %(A_province.word_name, A_province.word_nominal,\n A_province.word_freq, A_province.word_note))\n for A_city in city_list:\n print('%s\\t%s\\t%d\\t%s' % (A_city.word_name, A_city.word_nominal,\n A_city.word_freq, A_city.word_note))\n out_file.write('%s\\t%s\\t%d\\t%s\\n' % (A_city.word_name, A_city.word_nominal,\n A_city.word_freq, A_city.word_note))\n\n for A_towns in towns_list:\n print('%s\\t%s\\t%d\\t%s' % (A_towns.word_name, A_towns.word_nominal,\n A_towns.word_freq, A_towns.word_note))\n out_file.write('%s\\t%s\\t%d\\t%s\\n' % (A_towns.word_name, A_towns.word_nominal,\n A_towns.word_freq, A_towns.word_note))\n\n for A_street in street_list:\n print('%s\\t%s\\t%d\\t%s' % (A_street.word_name, A_street.word_nominal,\n A_street.word_freq, A_street.word_note))\n try:\n out_file.write('%s\\t%s\\t%d\\t%s\\n' % (A_street.word_name, A_street.word_nominal,\n A_street.word_freq, A_street.word_note))\n except UnicodeEncodeError as e:\n out_file.write('******\\t%s\\n' %e)\n\n\n\n\n\n\n\n\n\n\n\n","repo_name":"flyingaura/PythonLearning","sub_path":"LearnOOP/learning0417002.py","file_name":"learning0417002.py","file_ext":"py","file_size_in_byte":6981,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"40"} +{"seq_id":"22000063641","text":"import rclpy\nfrom rclpy.node import Node\nimport random\nimport json\n\nfrom std_msgs.msg import String\nimport dotenv\nimport socket\nimport pynmeagps\nimport base64\n\nNMEA_HOST = \"localhost\"\nNMEA_PORT = 2121\n\n\nclass Telemetry(Node):\n\n def __init__(self):\n super().__init__('top_nmea')\n self.publisher_ = self.create_publisher(String, 'top_nmea', 10)\n\n self.stream = socket.socket(socket.AF_INET, socket.SOCK_STREAM)\n self.stream.connect((NMEA_HOST, NMEA_PORT))\n\n for raw_data, parsed_data in pynmeagps.NMEAReader(self.stream).iterate():\n json_ = {\n \"iqn\": self.get_uuid(),\n \"nmea\": base64.b64encode(raw_data).decode('ascii')\n }\n # encode bytes as base64 for JSON serialization\n\n msg = String()\n msg.data = json.dumps(json_)\n self.publisher_.publish(msg)\n self.get_logger().info('Publishing: \"%s\"' % msg.data)\n\n\n def get_uuid(self):\n iscsi_conf = dotenv.dotenv_values(\"/etc/iscsi/initiatorname.iscsi\")\n return iscsi_conf[\"InitiatorName\"]\n\n\ndef main(args=None):\n rclpy.init(args=args)\n p = Telemetry()\n rclpy.spin(p)\n\n # Destroy the node explicitly\n # (optional - otherwise it will be done automatically\n # when the garbage collector destroys the node object)\n p.destroy_node()\n rclpy.shutdown()\n\n\nif __name__ == '__main__':\n main()","repo_name":"UEA-MComp/telemetry","sub_path":"src/telemetry/telemetry/telemetry.py","file_name":"telemetry.py","file_ext":"py","file_size_in_byte":1412,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"40"} +{"seq_id":"72407625080","text":"#!/usr/bin/env python\n# coding=utf-8\nimport pandas as pd\nimport numpy as np \n'''\n 说明:本文件的目的是计算数据的一节差分数据,基于3个构造的新特征.\n\n'''\n\ndef load_data():\n \n index = ['s0','s1','s2','s3','s4','s5','s6','s7','s8','s9','s10','s11','s12','s13','s14','s15','s16','s17','s18','s19','s20']\n index1 = ['s1','s2','s3','s6','s7','s8','s10','s11','s12','s13','s14','s16','s19','s20']\n \n sensor_data_train = pd.read_table('FD001/train_X_FD001.txt',delim_whitespace=True,header=None,names=index,encoding='utf-8')\n sensor_data_train_14 = sensor_data_train.loc[:,index1] # 提取14个测量指标 \n sensor_data_train_14 = sensor_data_train_14.apply(lambda x:(x-np.min(x))/(np.max(x)-np.min(x))) #将数据标准化 \n first_difference_train_14 = sensor_data_train_14.diff()\n\n \n \n\n sensor_data_test = pd.read_table('FD001/test_X_FD001.txt',delim_whitespace=True,header=None,names=index,encoding='utf-8')\n sensor_data_test_14 = sensor_data_test.loc[:,index1]\n sensor_data_test_14 = sensor_data_test_14.apply(lambda x:(x-np.min(x))/(np.max(x)-np.min(x)))\n first_difference_test_14 = sensor_data_test_14.diff()\n\n\n\n\n #train_y = pd.read_table('FD001/train_y_FD001.txt',delim_whitespace=True,header=None,encoding='utf-8')\n\n #test_y = pd.read_table('FD001/test_y_FD001.txt',delim_whitespace=True,header=None,encoding='utf-8')\n \n #now_age = pd.read_table('FD001/now_age_FD001.txt',delim_whitespace=True,header=None,encoding='utf-8')\n \n #RUL = pd.read_table('FD001/RUL_FD001.txt',delim_whitespace=True,header=None,encoding='utf-8')\n \n \n return first_difference_train_14,first_difference_test_14\n\n \n\n\nif __name__ == '__main__':\n f1,f2 = load_data()\n print(f1[0:5])\n print(f2[0:5])\n\n\n\n\n\n\n","repo_name":"ChampionZP/engine_RUL","sub_path":"projects/engine/standard1/Experiment_based_on_first_diff_data/gradient_data.py","file_name":"gradient_data.py","file_ext":"py","file_size_in_byte":1795,"program_lang":"python","lang":"en","doc_type":"code","stars":2,"dataset":"github-code","pt":"40"} +{"seq_id":"73922683639","text":"import torch\ntorch.cuda.empty_cache()\nfrom torch import nn\nimport torchvision\n\nclass Block(nn.Module):\n def __init__(self, in_ch, out_ch):\n super().__init__()\n self.conv1 = nn.Conv2d(in_ch, out_ch, 3)\n self.relu = nn.ReLU()\n self.conv2 = nn.Conv2d(out_ch, out_ch, 3)\n \n def forward(self, x):\n return self.conv2(self.relu(self.conv1(x)))\n\n\nclass Encoder(nn.Module):\n def __init__(self, chs=(3,64,128,256,512,1024)):\n super().__init__()\n self.enc_blocks = nn.ModuleList([Block(chs[i], chs[i+1]) for i in range(len(chs)-1)])\n self.pool = nn.MaxPool2d(2)\n \n def forward(self, x):\n ftrs = []\n for block in self.enc_blocks:\n x = block(x)\n ftrs.append(x)\n x = self.pool(x)\n return ftrs\n\n\nclass Decoder(nn.Module):\n def __init__(self, chs=(1024, 512, 256, 128, 64)):\n super().__init__()\n self.chs = chs\n self.upconvs = nn.ModuleList([nn.ConvTranspose2d(chs[i], chs[i+1], 2, 2) for i in range(len(chs)-1)])\n self.dec_blocks = nn.ModuleList([Block(chs[i], chs[i+1]) for i in range(len(chs)-1)]) \n \n def forward(self, x, encoder_features):\n for i in range(len(self.chs)-1):\n x = self.upconvs[i](x)\n enc_ftrs = self.crop(encoder_features[i], x)\n x = torch.cat([x, enc_ftrs], dim=1)\n x = self.dec_blocks[i](x)\n return x\n \n def crop(self, enc_ftrs, x):\n _, _, H, W = x.shape\n enc_ftrs = torchvision.transforms.CenterCrop([H, W])(enc_ftrs)\n return enc_ftrs\n\n\nclass UNet(nn.Module):\n def __init__(self, enc_chs=(3,64,128,256,512,1024), dec_chs=(1024, 512, 256, 128, 64), num_class=1, retain_dim=False, out_sz = None):\n super().__init__()\n self.encoder = Encoder(enc_chs)\n self.decoder = Decoder(dec_chs)\n self.head = nn.Conv2d(dec_chs[-1], num_class, 1)\n self.retain_dim = retain_dim\n\n def forward(self, x):\n enc_ftrs = self.encoder(x)\n out = self.decoder(enc_ftrs[::-1][0], enc_ftrs[::-1][1:])\n out = self.head(out)\n # if user want to keep outpus the same size as input \n # need to set retain_dim = True and give out_sz\n if self.retain_dim:\n import torch.nn.functional as F\n out = F.interpolate(out, out_sz)\n return out\n \n \n# Test the network\n\n# x = torch.randn(10, 3, 64, 64)\n# enc_block_ck = CNN_AE()\n# ftrs = enc_block_ck(x)\n# for ftr in ftrs: print(ftr.shape)","repo_name":"Khayrulbuet13/HSC_ML","sub_path":"src/Models/UNet.py","file_name":"UNet.py","file_ext":"py","file_size_in_byte":2587,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"40"} +{"seq_id":"11703730928","text":"from utils.greyscaling import *\nfrom utils.image_splitting import *\n# (inherits all imports)\n\nfrom utils.utils import progress_bar\nimport re\n\n# Load project variables\nfrom configparser import ConfigParser\nconfig = ConfigParser()\nconfig.read('config.ini')\nimg_root = config.get('main', 'img_root')\ncropped_root = config.get('main', 'cropped_root')\nresized_root = config.get('main', 'resized_root')\n\n\ndef analyze_image_scores(bands_df):\n corpus_size = bands_df.shape[0]\n with open('scores_log.ini', 'a') as file:\n file.write('NEW RUN*********\\n')\n for i, row in bands_df.iterrows():\n if i % 50 == 0:\n progress_bar('Processing image #', i, corpus_size)\n try:\n if (bands_df['Blur scores'][i] == None or \\\n bands_df['Border scores'][i] == None) & \\\n bands_df['Overall valid'][i]:\n file_name = img_root + '/' + bands_df['Full paths'][i]\n image = load_image(file_name)\n greyscale_image = max_rgb2grey(image)\n normalized_image = normalize_image(greyscale_image)\n border_score = find_border_score(normalized_image)\n blur_score = find_blur_score(normalized_image)\n bands_df.set_value(i, 'Blur scores', blur_score)\n bands_df.set_value(i, 'Border scores', border_score)\n except:\n with open('scores_log.ini', 'a') as file:\n file.write(bands_df['Full paths'][i] + '\\n')\n return bands_df\n\n\ndef validate_scores(bands_df, blur_threshold=.025, border_threshold=.01):\n corpus_size = bands_df.shape[0]\n with open('validation_log.ini', 'a') as file:\n file.write('NEW RUN*********\\n')\n for i, row in bands_df.iterrows():\n if i % 50 == 0:\n progress_bar('Processing image #', i, corpus_size)\n try:\n if bands_df['Unicode valid'][i] and \\\n bands_df['Logo file'][i] != 'nan' and \\\n bands_df['Logo file'][i] != 'NO LOGO FOUND':\n if bands_df['Border scores'][i] <= border_threshold:\n bands_df.set_value(i, 'Border valid', True)\n else:\n bands_df.set_value(i, 'Border valid', False)\n if bands_df['Blur scores'][i] <= blur_threshold:\n bands_df.set_value(i, 'Blur valid', True)\n else:\n bands_df.set_value(i, 'Blur valid', False)\n if bands_df['Blur valid'][i] and bands_df['Border valid'][i]:\n bands_df.set_value(i, 'Overall valid', True)\n except:\n bands_df.set_value(i, 'Overall valid', False)\n with open('scores_log.ini', 'a') as file:\n file.write(bands_df['Full paths'][i] + '\\n')\n return bands_df\n\n\ndef view_distributions(bands_df, key, number_of_examples=20, output_file='test.html'):\n bands_df_copy = bands_df.dropna()\n bands_df_copy = bands_df_copy.sort(key)\n file_list = [img_root + '/' + i for i in bands_df_copy['Full paths']]\n score_list = list(bands_df_copy[key])\n assert len(file_list) == len(score_list)\n save_to_html(output_file, file_list, score_list, number_of_examples)\n\n\ndef score_statistics(bands_df):\n bands_df_copy = bands_df.dropna()\n blur_scores = [i for i in bands_df_copy['Blur scores'] if i is not None]\n border_scores = [i for i in bands_df_copy['Border scores'] if i is not None]\n blur_scores.sort()\n border_scores.sort()\n plot_arbitrary_array(blur_scores)\n plot_arbitrary_array(border_scores)\n print('% of images above the blur score threshold')\n print(format_as_percent(np.mean(bands_df['Blur valid'])))\n print('# of images above the blur score threshold')\n print(np.sum(bands_df['Blur valid']))\n print('% of images above the border score threshold')\n print(format_as_percent(np.mean(bands_df['Border valid'])))\n print('# of images above the border score threshold')\n print(np.sum(bands_df['Border valid']))\n print('% of validated images in the corpus (including border, blur, and unicode)')\n print(format_as_percent(np.mean(bands_df['Overall valid'])))\n print('# of validated images in the corpus (including border, blur, and unicode)')\n print(np.sum(bands_df['Overall valid']))\n\n\ndef initialize_cropped_df():\n cropped_df = pd.DataFrame(columns=['Band',\n 'Country',\n 'Genre',\n 'Black',\n 'Full paths',\n 'Height',\n 'Width',\n 'Diag',\n 'Valid size',\n 'Number extracted',\n ])\n return cropped_df\n\n\ndef export_cropped_images(bands_df, cropped_df):\n with open('cropping_log.ini', 'a') as file:\n file.write('NEW RUN*********\\n')\n\n corpus_size = bands_df.shape[0]\n for i, row in bands_df.iterrows():\n if i % 100 == 0:\n progress_bar('Processing image #', i, corpus_size)\n cropped_df.to_csv('image_databases/cropped_bands_df.csv')\n try:\n if bands_df['Overall valid'][i] and (not (cropped_df['Full paths'].fillna('missing') == bands_df['Full paths'][i]).any()):\n\n formatted_bucket = '{0:0>4}'.format(bands_df['Bins'][i])\n if not os.path.isdir(cropped_root + '/' + formatted_bucket):\n os.makedirs(cropped_root + '/' + formatted_bucket)\n\n file_name = img_root + '/' + bands_df['Full paths'][i]\n image = load_image(file_name)\n greyscale_image = max_rgb2grey(image)\n normalized_image = normalize_image(greyscale_image)\n cropped_image = remove_bounding_box(normalized_image)\n extracted_masks = mark_images_for_splitting(normalized_image)\n number_extracted = len(extracted_masks)\n carryover_data = ['Band', 'Country', 'Genre', 'Black']\n\n height = normalized_image.shape[0]\n width = normalized_image.shape[1]\n diag = math.sqrt(height**2 + width**2)\n\n new_name = bands_df['Full paths'][i]\n new_name = re.sub(r'\\?\\d+', '', new_name)\n save_image(cropped_image, cropped_root, new_name)\n\n new_data_row = {'Valid size': None}\n for entry in carryover_data:\n new_data_row[entry] = bands_df[entry][i]\n new_data_row['Height'] = height\n new_data_row['Width'] = width\n new_data_row['Diag'] = diag\n new_data_row['Number extracted'] = number_extracted\n new_data_row['Full paths'] = new_name\n cropped_df = cropped_df.append(new_data_row, ignore_index=True)\n except:\n with open('cropping_log.ini', 'a') as file:\n file.write(bands_df['Full paths'][i] + '\\n')\n return cropped_df\n\n\ndef move_splits_for_manual_review(cropped_df):\n\n duplicates_df = cropped_df.loc[cropped_df['Number extracted'] > 1]\n duplicates_size = duplicates_df.shape[0]\n duplicates_df.index = range(duplicates_size)\n\n for i, row in duplicates_df.iterrows():\n if i % 50 == 0:\n progress_bar('Processing image #', i, duplicates_size)\n\n file_name = cropped_root + '/' + duplicates_df['Full paths'][i]\n image = load_image(file_name)\n greyscale_image = max_rgb2grey(image)\n normalized_image = normalize_image(greyscale_image)\n\n formatted_bucket = duplicates_df['Full paths'][i]\n if formatted_bucket[0] == '/':\n formatted_bucket = formatted_bucket[1:]\n formatted_bucket = re.sub(r'/[\\s\\S]*', '', duplicates_df['Full paths'][i])\n if not os.path.isdir(cropped_root + '/dupes/' + formatted_bucket):\n os.makedirs(cropped_root + '/dupes/' + formatted_bucket)\n\n save_image(normalized_image, cropped_root + '/dupes/', duplicates_df['Full paths'][i])\n\n\ndef re_import_dupes(cropped_df):\n master_count = -1\n for root, dirs, filenames in os.walk(cropped_root + '/dupes'):\n for file_name in filenames:\n master_count += 1\n\n count = -1\n for root, dirs, filenames in os.walk(cropped_root + '/dupes'):\n for file_name in filenames:\n count += 1\n\n if count % 50 == 0:\n progress_bar('Processing image #', count, master_count)\n\n full_path = os.path.join(root, file_name)\n bin_path = full_path[full_path[:full_path.rfind('/')].rfind(\n '/') + 1:] # Returns onward from after the second '/' from the right\n dataframe_row = cropped_df[cropped_df['Full paths'] == bin_path]\n dataframe_index = dataframe_row.index.tolist()[0]\n cropped_data = dict(cropped_df.ix[dataframe_index])\n\n image = load_image(full_path)\n greyscale_image = max_rgb2grey(image)\n normalized_image = normalize_image(greyscale_image)\n extracted_images = return_split_and_cropped_images(normalized_image)\n\n try:\n os.remove(cropped_root + '/' + bin_path)\n except:\n pass\n cropped_df.drop(cropped_df.index[[1, 3]])\n\n for image_num in extracted_images:\n individual_image = extracted_images[image_num]\n height = individual_image.shape[0]\n width = individual_image.shape[1]\n diag = math.sqrt(height ** 2 + width ** 2)\n new_name = bin_path\n if new_name[0] == '/':\n new_name = new_name[1:]\n if image_num >= 2:\n new_name = new_name[:-4] + '_' + str(image_num) + new_name[-4:]\n cropped_data['Full paths'] = new_name\n cropped_data['Height'] = height\n cropped_data['Width'] = width\n cropped_data['Diag'] = diag\n\n save_image(individual_image, cropped_root, new_name)\n cropped_df = cropped_df.append(cropped_data, ignore_index=True)\n return cropped_df\n\n\ndef image_size_analysis(cropped_df):\n # Generate aspect ratios\n cropped_df['Aspect ratios'] = np.divide(cropped_df['Width'], cropped_df['Height'])\n log_ars = np.log(cropped_df['Aspect ratios'])\n cropped_df['Intuitive aspect ratios'] = np.multiply(np.sign(log_ars), np.exp(np.abs(log_ars)))\n cropped_df['Abs aspect ratios'] = np.exp(np.abs(log_ars))\n\n # Analyze aspect ratios\n int_aspect_ratios = list(cropped_df['Intuitive aspect ratios'])\n int_aspect_ratios.sort()\n plot_arbitrary_array(int_aspect_ratios, [-2, 10])\n\n # Trim based on aspect ratios\n upper_threshold = 6\n lower_threshold = -1.5\n cropped_df['Valid size'] = np.multiply(cropped_df['Abs aspect ratios'] >= lower_threshold,\n cropped_df['Abs aspect ratios'] <= upper_threshold)\n percent_saved = np.mean(cropped_df['Valid size'])\n print(percent_saved)\n\n # Analyze resizing\n target_box = 512\n upscaling_threshold = 3\n cropped_df['Max dim'] = np.maximum(cropped_df['Height'], cropped_df['Width'])\n cropped_df['Scale factor'] = np.divide(target_box, cropped_df['Max dim'])\n scale_factor = list(cropped_df['Scale factor'])\n scale_factor.sort()\n plot_arbitrary_array(scale_factor)\n\n # Trim based on resizing\n cropped_df['Valid size'] = np.multiply(np.multiply(cropped_df['Abs aspect ratios'] >= lower_threshold,\n cropped_df['Abs aspect ratios'] <= upper_threshold),\n cropped_df['Scale factor'] <= upscaling_threshold)\n percent_saved = np.mean(cropped_df['Valid size'])\n print(percent_saved)\n return cropped_df\n\n\ndef pad_to_square_black(normalized_image):\n max_dim = max(normalized_image.shape)\n min_dim = min(normalized_image.shape)\n short_axis = normalized_image.shape.index(min_dim)\n short_padding = math.floor((max_dim - min_dim) / 2)\n long_padding = math.ceil((max_dim - min_dim) / 2)\n short_indices = [short_padding, max_dim]\n long_indices = [long_padding, max_dim]\n short_pad = np.zeros((short_indices[short_axis], short_indices[1-short_axis]))\n long_pad = np.zeros((long_indices[short_axis], long_indices[1-short_axis]))\n new_image = np.concatenate((short_pad, normalized_image, long_pad), short_axis)\n new_shape = new_image.shape\n assert new_shape[0] == new_shape[1]\n return new_image\n\n\ndef initialize_resized_df():\n cropped_df = pd.DataFrame(columns=['Band',\n 'Country',\n 'Genre',\n 'Black',\n 'Full paths',\n ])\n return cropped_df\n\n\ndef resize_library(cropped_df, resized_df):\n with open('resizing_log.ini', 'a') as file:\n file.write('NEW RUN*********\\n')\n\n carryover_data = ['Band', 'Country', 'Genre', 'Black']\n corpus_size = cropped_df.shape[0]\n\n for i, row in cropped_df.iterrows():\n if i % 100 == 0:\n progress_bar('Processing image #', i, corpus_size)\n resized_df.to_csv('image_databases/resized_logos_df.csv')\n try:\n if cropped_df['Valid size'][i]:\n\n old_name = cropped_df['Full paths'][i]\n\n formatted_bucket = old_name\n if formatted_bucket[0] == '/':\n formatted_bucket = formatted_bucket[1:]\n formatted_bucket = re.sub(r'/[\\s\\S]*', '', old_name)\n if not os.path.isdir(resized_root + '/512/' + formatted_bucket):\n os.makedirs(resized_root + '/512/' + formatted_bucket)\n\n file_name = cropped_root + '/' + old_name\n image = load_image(file_name)\n normalized_image = max_rgb2grey(image)\n normalized_image = normalized_image\n padded_image = pad_to_square_black(normalized_image)\n loaded_image = PIL.Image.fromarray(padded_image)\n resized_image = loaded_image.resize([512, 512], PIL.Image.ANTIALIAS)\n\n new_name = old_name[:old_name.rfind('.')] + '.png'\n save_image(np.asarray(resized_image), resized_root + '/512', new_name)\n\n new_data_row = {'Full paths': new_name}\n for entry in carryover_data:\n new_data_row[entry] = cropped_df[entry][i]\n resized_df = resized_df.append(new_data_row, ignore_index=True)\n except:\n with open('resizing_log.ini', 'a') as file:\n file.write(cropped_df['Full paths'][i] + '\\n')\n\n return resized_df\n\n\ndef iterative_resizing(resized_df):\n with open('resizing_iterations_log.ini', 'a') as file:\n file.write('NEW RUN*********\\n')\n\n corpus_size = resized_df.shape[0]\n sizes = [256, 128, 64, 32, 16]\n\n for i, row in resized_df.iterrows():\n if i % 100 == 0:\n progress_bar('Processing image #', i, corpus_size)\n try:\n file_name = resized_df['Full paths'][i]\n\n formatted_bucket = file_name\n if formatted_bucket[0] == '/':\n formatted_bucket = formatted_bucket[1:]\n formatted_bucket = re.sub(r'/[\\s\\S]*', '', file_name)\n\n source_file = resized_root + '/512/' + file_name\n image = load_image(source_file)\n loaded_image = PIL.Image.fromarray(image)\n\n for size in sizes:\n\n new_root = resized_root + '/' + str(size) + '/'\n if not os.path.isdir(new_root + formatted_bucket):\n os.makedirs(new_root + formatted_bucket)\n\n resized_image = loaded_image.resize([size, size], PIL.Image.ANTIALIAS)\n save_image(np.asarray(resized_image), resized_root + '/' + str(size), file_name)\n\n except:\n with open('resizing_iterations_log.ini', 'a') as file:\n file.write(file_name + '\\n')\n\ndef main():\n bands_df = pd.read_csv('image_databases/downloaded_bands_df.csv', index_col=0)\n\n bands_df['Border scores'] = None\n bands_df['Blur scores'] = None\n bands_df = analyze_image_scores(bands_df)\n bands_df.to_csv('image_databases/downloaded_bands_df.csv')\n\n bands_df['Border valid'] = None\n bands_df['Blur valid'] = None\n bands_df['Overall valid'] = False\n bands_df = validate_scores(bands_df)\n bands_df.to_csv('image_databases/downloaded_bands_df.csv')\n\n view_distributions(bands_df, 'Blur scores', 100, 'outputs/blur_scores.html')\n view_distributions(bands_df, 'Border scores', 100, 'outputs/border_scores.html')\n score_statistics(bands_df)\n\n cropped_df = initialize_cropped_df()\n cropped_df = export_cropped_images(bands_df, cropped_df)\n cropped_df.to_csv('image_databases/cropped_bands_df.csv')\n\n move_splits_for_manual_review(cropped_df)\n # ++++++++++++++++++++++++++++++++++++++++\n # BREAK\n # Then manually pruned false positives, which was most of them\n # ++++++++++++++++++++++++++++++++++++++++\n cropped_df = re_import_dupes(cropped_df)\n cropped_df.to_csv('image_databases/cropped_bands_df.csv')\n\n cropped_df = image_size_analysis(cropped_df)\n\n resized_df = initialize_resized_df()\n resized_df = resize_library(cropped_df, resized_df)\n resized_df.to_csv('image_databases/resized_logos_df.csv')\n\n iterative_resizing(resized_df)\n\n","repo_name":"dmgreenwald7/metal-cnn","sub_path":"A04_image_quality.py","file_name":"A04_image_quality.py","file_ext":"py","file_size_in_byte":17643,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"40"} +{"seq_id":"3236073696","text":"from django.shortcuts import render, redirect, HttpResponse\nfrom faceDetection.detection import FaceRecognition\nfrom patient.models import PatientModel, AppointmentModel\nfrom .models import DoctorModel\n\n# Create your views here.\nfaceRecognition = FaceRecognition()\n\ndef patientLogin(request):\n face_id = faceRecognition.recognizeFace()\n patient = PatientModel.objects.get(mobile=face_id)\n\n appointments = AppointmentModel.objects.filter(userId=face_id)\n\n doctors = DoctorModel.objects.filter(status=\"Free\")\n\n currentAppointment = appointments[0]\n currentDoctor = doctors[0]\n\n currentAppointment.status = \"Reached\"\n currentAppointment.docterId = doctors[0].email\n\n currentAppointment.save()\n\n currentDoctor.status = \"Occupied\"\n currentDoctor.occupiedBy = face_id\n currentDoctor.save()\n\n print(\"succefully updated\")\n\n return HttpResponse(f\"Hello {patient.firstName} {patient.lastName}\")\n\n\ndef patientLogout(request):\n face_id = faceRecognition.recognizeFace()\n patient = PatientModel.objects.get(mobile=face_id)\n\n appointments = AppointmentModel.objects.filter(userId=face_id)\n\n doctors = DoctorModel.objects.filter(occupiedBy=face_id)\n\n currentAppointment = appointments[0]\n currentDoctor = doctors[0]\n\n currentAppointment.status = \"Reached\"\n currentAppointment.save()\n\n currentDoctor.status = \"Free\"\n currentDoctor.occupiedBy = \"\"\n currentDoctor.save()\n\n print(\"succefully updated\")\n\n return HttpResponse(f\"Bye {patient.firstName} {patient.lastName}\")\n\n \n\ndef createDoctor(request):\n if request.method == \"POST\":\n doctor = DoctorModel()\n doctor.name = request.POST.get(\"name\")\n doctor.email = request.POST.get(\"email\")\n doctor.save()\n return HttpResponse(\"Created The Doctor\")\n \n return render(request, \"hospital/Doctor.html\")\n","repo_name":"rushii1192/wecare","sub_path":"hospital/views.py","file_name":"views.py","file_ext":"py","file_size_in_byte":1855,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"40"} +{"seq_id":"13692297223","text":"import numpy as np\nimport math as math\n\n\nclass Ray:\n def __init__(self, originPoint, directionVector):\n self.originPoint = originPoint\n self.directionVector = directionVector\n\n def printPoint(self):\n print(self.originPoint)\n\n def determineRayPoint(self,distance):\n return self.originPoint + np.dot(distance,self.directionVector)\n\n\nclass Object():\n def __init__(self):\n self.color = Color(0,0,0,0)\n\n def intersect(self, ray):\n pass\n\nclass Triangle(Object):\n def __init__(self, a, b, c, color):\n self.VectA = a\n self.VectB = b\n self.VectC = c\n self.color = color\n self.normal = self.calcNormal()\n\n def calcNormal(self):\n CA = self.VectC.subtract(self.VectA)\n BA = self.VectB.subtract(self.VectA)\n return CA.cross(BA).normalize()\n\n def distance(self):\n return self.normal.dot(self.VectA)\n\n def calcNormalAt(self, intersectPos):\n return self.normal\n\n def intersect(self, ray):\n rayDir = ray.directionVector\n rayOrigin = ray.originPoint\n\n\n # edge1 = self.VectB.subtract(self.VectA)\n # edge2 = self.VectC.subtract(self.VectA)\n #\n # h = rayDir.cross(edge2)\n # a = edge1.dot(h)\n #\n # if a > -0.000001 and a < 0.000001:\n # return -1\n #\n # f = 1/a\n #\n # s = rayOrigin.subtract(self.VectA)\n # u = s.dot(h) * f\n # if u < 0 or u > 1:\n # return -1\n #\n # q = s.cross(edge1)\n # v = f * (rayDir.dot(q))\n # if v < 0 or v > 1:\n # return -1\n #\n # t = f * (edge2.dot(q))\n # if t > 0.000001:\n # newA = rayDir.dot(self.normal)\n # newB = self.normal.dot(ray.originPoint.add(self.normal.multiply(self.distance()).negative()))\n # return -1 * newB/newA\n # # outIntersectionPoint = rayOrigin.add(rayDir.multiply(t))\n # # add1 = (outIntersectionPoint.x - rayOrigin.x)**2 + (outIntersectionPoint.y - rayOrigin.y)*2 + (outIntersectionPoint.z - rayOrigin.z)**2\n # # if add1 >= 0:\n # # return math.sqrt(add1)\n # # else:\n # # magnitude = math.sqrt(add1 * -1)\n # # return magnitude\n # else:\n # return -1\n\n # Ray Origin distance to point of intersection\n # distance = self.distance()\n\n a = rayDir.dot(self.normal)\n\n if a == 0:\n return -1\n else:\n if a > 0:\n self.normal.negative()\n distance = self.normal.dot(self.VectA)\n\n dot1 = self.normal.dot(rayOrigin)\n add1 = (dot1 + distance) * -1\n dot2 = self.normal.dot(rayDir)\n t = add1 / dot2\n\n if t <= 0:\n return -1\n Q = rayOrigin.add(rayDir.multiply(t))\n\n b = self.normal.dot(ray.originPoint.add(self.normal.multiply(distance).negative()))\n\n CA = self.VectC.subtract(self.VectA)\n QA = Q.subtract(self.VectA)\n test1 = self.normal.dot(CA.cross(QA))\n\n BC = self.VectB.subtract(self.VectC)\n QC = Q.subtract(self.VectC)\n test2 = self.normal.dot(BC.cross(QC))\n\n AB = self.VectA.subtract(self.VectB)\n QB = Q.subtract(self.VectB)\n test3 = self.normal.dot(AB.cross(QB))\n\n if test1 >=0 and test2 >= 0 and test3 >= 0:\n return t\n else:\n return -1\n # pass\n\nclass Sphere(Object):\n def __init__(self, radius, center, color):\n self.radius = radius\n self.center = center\n self.color = color\n\n def calcNormal(self, point):\n return\n\n def calcNormalAt(self, intersectPos):\n Vector = intersectPos.add(self.center.negative()).normalize()\n return Vector\n\n def intersect(self, ray):\n rayOrigin = ray.originPoint\n rayOriginX = rayOrigin.x\n rayOriginY = rayOrigin.y\n rayOriginZ = rayOrigin.z\n\n rayDir = ray.directionVector\n rayDirX = rayDir.x\n rayDirY = rayDir.y\n rayDirZ = rayDir.z\n\n sphCent = self.center\n sphCentX = sphCent.x\n sphCentY = sphCent.y\n sphCentZ = sphCent.z\n\n B = 2*((rayOriginX - sphCentX)*rayDirX + (rayOriginY - sphCentY)*rayDirY + (rayOriginZ - sphCentZ)*rayDirZ)\n C = ((rayOriginX - sphCentX)**2 + (rayOriginY - sphCentY)**2 + (rayOriginZ - sphCentZ)**2) - self.radius**2\n\n discriminant = B ** 2 - 4 * C\n if discriminant < 0:\n return -1\n\n t1 = (-B + math.sqrt(discriminant)) / 2\n t2 = (-B - math.sqrt(discriminant)) / 2\n if t1 > 0 and t2 > 0:\n if t1 < t2:\n return t1\n else:\n return t2\n elif t1 <= 0 and t2 > 0:\n return t2\n elif t2 <= 0 and t1 > 0:\n return t1\n else:\n return -1\n\n\nclass Color:\n def __init__(self,r,g,b,special):\n self.r = r\n self.g = g\n self.b = b\n self.special = special\n\n def toString(self):\n return (str(int(self.r * 255)) + \" \" + str(int(self.g * 255)) + \" \" + str(int(self.b * 255)) + \" \")\n\n def brightness(self):\n return (self.r + self.g + self.b)/3\n\n def scaleColor(self, c):\n return Color(self.r * c, self.g * c, self.b * c, self.special)\n\n def add(self, color):\n return Color(self.r + color.r, self.g + color.g, self.b + color.b, self.special)\n\n def multiply(self, color):\n return Color(self.r * color.r, self.g * color.g, self.b * color.b, self.special)\n\n def average(self, color):\n return Color((self.r + color.r)/2, (self.g + color.g)/2, (self.b + color.b)/2, self.special)\n\n def clip(self):\n allLight = self.r + self.g + self.b\n excessLight = allLight - 3\n if(excessLight > 0):\n self.r = self.r + excessLight * (self.r/allLight)\n self.g = self.g + excessLight * (self.g / allLight)\n self.b = self.b + excessLight * (self.b / allLight)\n if self.r > 1:\n self.r = 1\n if self.g > 1:\n self.g = 1\n if self.b > 1:\n self.b = 1\n if self.r < 0:\n self.r = 0\n if self.g < 0:\n self.g = 0\n if self.b < 0:\n self.b = 0\n\n return Color(self.r, self.g, self.b, self.special)\n\n\nclass Light:\n def __init__(self, position, color):\n self.position = position\n self.color = color\n\nclass Camera:\n def __init__(self, position, direction, right, down):\n self.position = position\n self.direction = direction\n self.right = right\n self.down = down\n\nclass Vector:\n def __init__(self, x, y, z):\n self.x = x\n self.y = y\n self.z = z\n\n def magnitude(self):\n return math.sqrt((self.x**2) + (self.y**2) + (self.z**2))\n\n def normalize(self):\n magnitude = self.magnitude()\n if magnitude != 0:\n return Vector(self.x / magnitude, self.y / magnitude, self.z / magnitude)\n else:\n return self\n\n def negative(self):\n return Vector(-self.x, -self.y, -self.z)\n\n def dot(self, vector):\n return (self.x * vector.x) + (self.y * vector.y) + (self.z*vector.z)\n\n def cross(self, vector):\n return Vector(self.y*vector.z - self.z*vector.y,\n self.z * vector.x - self.x * vector.z,\n self.x * vector.y - self.y * vector.x)\n\n def add(self, vector):\n return Vector(self.x + vector.x, self.y + vector.y, self.z + vector.z)\n\n def multiply(self, c):\n return Vector(self.x*c, self.y*c, self.z*c)\n\n def subtract(self, vector):\n return Vector(self.x - vector.x, self.y - vector.y, self.z - vector.z)\n\nclass RayTracer:\n def __init__(self):\n self.camPosition = Vector(0,0,1)\n self.rays = []\n pass\n\n def getColorAt(self, intersectPos, intersectDir, objects, bestIndex, accuracy, ambientLight, light, depth, phongConstant):\n bestObjectColor = objects[bestIndex].color\n bestObjectNormal = objects[bestIndex].calcNormalAt(intersectPos)\n final_color = bestObjectColor.scaleColor(ambientLight)\n D = intersectDir.negative()\n\n if bestObjectColor.special > 1 and depth <= 2:\n dotProduct1 = D.dot(bestObjectNormal)\n scalar1 = bestObjectNormal.multiply(dotProduct1)\n scalar2 = scalar1.multiply(-2)\n add1 = scalar2.add(D)\n reflectionDir = add1.normalize().negative()\n\n offset = reflectionDir.multiply(0.001)\n relectRay = Ray(intersectPos.add(offset), reflectionDir)\n\n reflectIntersects = []\n\n for i in range(len(objects)):\n reflectIntersects.append(objects[i].intersect(relectRay))\n\n newIndex = self.calcClosestObject(reflectIntersects)\n\n if newIndex != -1:\n if reflectIntersects[newIndex] > accuracy:\n reflectIntersectPos = intersectPos.add(reflectionDir.multiply(reflectIntersects[newIndex]))\n reflectIntersectDir = reflectionDir\n reflectIntersectColor = self.getColorAt(reflectIntersectPos, reflectIntersectDir, objects, newIndex, accuracy, ambientLight, light, depth + 1, phongConstant)\n\n final_color = final_color.add(reflectIntersectColor.scaleColor(bestObjectColor.special - 1))\n\n\n lightDir = light.position.add(intersectPos.negative()).normalize()\n\n cosineAngle = bestObjectNormal.dot(lightDir)\n\n if cosineAngle > 0:\n inShadow = False\n distanceToLight = light.position.add(intersectPos.negative()).normalize()\n distanceToLightMag = distanceToLight.magnitude()\n\n shadowRay = Ray(intersectPos, light.position.add(intersectPos.negative()).normalize())\n newIntersections = []\n\n for i in range(len(objects)):\n if inShadow == False:\n newIntersections.append(objects[i].intersect(shadowRay))\n else:\n break\n for i in range(len(newIntersections)):\n if newIntersections[i] > accuracy:\n if newIntersections[i] <= distanceToLightMag:\n inShadow = True\n break\n\n if inShadow == False:\n final_color = final_color.add(bestObjectColor.multiply(light.color).scaleColor(cosineAngle))\n\n if (bestObjectColor.special > 0 and bestObjectColor.special <= 1):\n dotProduct1 = D.dot(bestObjectNormal)\n scalar1 = bestObjectNormal.multiply(dotProduct1)\n scalar2 = scalar1.multiply(-2)\n add1 = scalar2.add(D)\n reflectionDir = add1.normalize()\n\n specular = lightDir.negative().dot(reflectionDir)\n # specular = reflectionDir.dot(lightDir)\n if (specular > 0):\n specular = specular**phongConstant\n final_color = final_color.add(light.color.scaleColor(specular*bestObjectColor.special))\n # opposite incoming ray dot Reflection raised to phong all this by specular color\n\n return final_color.clip()\n\n def calcClosestObject(self, objects):\n retIndex = 0\n if len(objects) == 0:\n return -1\n elif len(objects) == 1:\n if objects[0] > 0:\n return 0\n else:\n return -1\n else:\n max = math.inf\n for i in range(len(objects)):\n if max > objects[i] and objects[i] > 0:\n max = objects[i]\n retIndex = i\n\n if max != math.inf:\n return retIndex\n else:\n return -1\n\n def rayTree(self):\n pass\n\n def main(self):\n bgColor = Color(.1,.1,.1, 0)\n camPosition = Vector(0,0,1)\n lookAt = Vector(0,0,0)\n difference = camPosition.subtract(lookAt)\n camDir = difference.negative().normalize()\n camRight = Vector(1,0,0).cross(camDir).normalize()\n camDown = camRight.cross(camDir)\n camera = Camera(camPosition,camDir,camRight,camDown)\n\n light = Light(Vector(2,-2,2), Color(1,1,1, 0))\n ambientLight = .15\n accuracy = 0.000001\n\n pixels = []\n\n width = 500\n height = 500\n\n objects = []\n\n objects.append(Sphere(.2, Vector(0,0,0), Color(.1,.1,.1, 2)))\n objects.append(Sphere(.1, Vector(.2, -.2, .2), Color(1, .5, 0, 2)))\n objects.append(Sphere(.05, Vector(-.27, 0, .1), Color(0, 0, 1, 1)))\n objects.append(Sphere(.05, Vector(-.17, .17, .2), Color(1, 0, 1, 1)))\n objects.append(Sphere(.05, Vector(.0, .25, .15), Color(1, 0, 0, 1)))\n\n\n # objects.append(Sphere(.1, Vector(0, -.2, 0), Color(.1,.1,.1, 2)))\n # objects.append(Sphere(.1, Vector(.15, .1, .05), Color(0, 1, 0, 1)))\n # objects.append(Sphere(.1, Vector(-.15, .1, .05), Color(0, 0, 1, 1)))\n\n # objects.append(Triangle(Vector(.3, -.35, -.2).negative(), Vector(.2, .25, -.1).negative(), Vector(-.3, -.3, .2).negative(), Color(0,0,1, 1)))\n # objects.append(Triangle(Vector(.2, -.1, .1), Vector(.2, .5, .2), Vector(.2, -.1, -.35), Color(1, 1, 0, 1)))\n\n f = open(\"extra.ppm\", \"w\")\n f.write(\"P3\\n\" + str(width) + \"\\n\" + str(height) + \"\\n255\\n\")\n checkIntersects = []\n for i in range(width):\n for j in range(height):\n xamnt = (i + 0.5)/width\n yamnt = (((height - j) + 0.5)/height)\n\n rayDirection = camDir.add(camRight.multiply(xamnt-0.5).add(camDown.multiply(yamnt-0.5))).normalize()\n\n newRay = Ray(self.camPosition, rayDirection)\n\n intersections = []\n\n for obj in objects:\n newInter = obj.intersect(newRay)\n intersections.append(newInter)\n if newInter != -1:\n checkIntersects.append(newInter)\n bestIndex = self.calcClosestObject(intersections)\n if bestIndex == -1:\n pixels.append(bgColor)\n else:\n if (intersections[bestIndex] > accuracy):\n intersectPos = camPosition.add(rayDirection.multiply(intersections[bestIndex]))\n intersectDir = rayDirection\n intersectColor = self.getColorAt(intersectPos, intersectDir, objects, bestIndex, accuracy, ambientLight, light, 0, 36)\n\n pixels.append(intersectColor)\n\n self.rays.append(newRay)\n newRay.printPoint()\n for i in range(len(pixels)):\n f.write(pixels[i].toString())\n\nif __name__ == '__main__':\n rayTracer = RayTracer()\n rayTracer.main()","repo_name":"pultilian/Raytracer","sub_path":"RayTracer.py","file_name":"RayTracer.py","file_ext":"py","file_size_in_byte":15037,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"40"} +{"seq_id":"70151299320","text":"r\"\"\"\nSubmanifolds of topological manifolds\n\nGiven a topological manifold `M` over a topological field `K`, a *topological\nsubmanifold of* `M` is defined by a topological manifold `N` over the same\nfield `K` of dimension lower than the dimension of `M` and a topological\nembedding `\\phi` from `N` to `M` (i.e. `\\phi` is a homeomorphism onto its\nimage).\n\nIn the case where the map `\\phi` is only an embedding locally, it is called an\n*topological immersion*, and defines an *immersed submanifold*.\n\nThe global embedding property cannot be checked in sage, so the immersed or\nembedded aspect of the manifold must be declared by the user, by calling either\n:meth:`~sage.manifolds.topological_submanifold.TopologicalSubmanifold.set_embedding`\nor\n:meth:`~sage.manifolds.topological_submanifold.TopologicalSubmanifold.set_immersion`\nwhile declaring the map `\\phi`.\n\nThe map `\\phi: N\\to M` can also depend on one or multiple parameters. As long\nas `\\phi` remains injective in these parameters, it represents a *foliation*.\nThe *dimension* of the foliation is defined as the number of parameters.\n\nAUTHORS:\n\n- Florentin Jaffredo (2018): initial version\n- Eric Gourgoulhon (2018-2019): add documentation\n- Matthias Koeppe (2021): open subsets of submanifolds\n\nREFERENCES:\n\n- \\J. M. Lee: *Introduction to Smooth Manifolds* [Lee2013]_\n\n\"\"\"\n\n\n# *****************************************************************************\n# Copyright (C) 2018 Florentin Jaffredo \n# Copyright (C) 2018-2019 Eric Gourgoulhon \n# Copyright (C) 2021 Matthias Koeppe \n#\n# This program is free software: you can redistribute it and/or modify\n# it under the terms of the GNU General Public License as published by\n# the Free Software Foundation, either version 2 of the License, or\n# (at your option) any later version.\n# http://www.gnu.org/licenses/\n# *****************************************************************************\n\nfrom sage.manifolds.manifold import TopologicalManifold\nfrom sage.manifolds.continuous_map import ContinuousMap\nfrom sage.symbolic.expression import Expression\nfrom sage.symbolic.assumptions import assumptions, assume\nfrom sage.misc.lazy_import import lazy_import\nlazy_import(\"sage.plot.plot3d.parametric_surface\", \"ParametricSurface\")\n\n#############################################################################\n# Global options\n\n#############################################################################\n# Class\n\n\nclass TopologicalSubmanifold(TopologicalManifold):\n r\"\"\"\n Submanifold of a topological manifold.\n\n Given a topological manifold `M` over a topological field `K`, a\n *topological submanifold of* `M` is defined by a topological manifold `N`\n over the same field `K` of dimension lower than the dimension of `M` and\n a topological embedding `\\phi` from `N` to `M` (i.e. `\\phi` is an\n homeomorphism onto its image).\n\n In the case where `\\phi` is only an topological immersion (i.e. is only\n locally an embedding), one says that `N` is an *immersed submanifold*.\n\n The map `\\phi` can also depend on one or multiple parameters.\n As long as `\\phi` remains injective in these parameters, it represents\n a *foliation*. The *dimension* of the foliation is defined as the number of\n parameters.\n\n INPUT:\n\n - ``n`` -- positive integer; dimension of the submanifold\n - ``name`` -- string; name (symbol) given to the submanifold\n - ``field`` -- field `K` on which the submanifold is defined; allowed\n values are\n\n - ``'real'`` or an object of type ``RealField`` (e.g., ``RR``) for\n a manifold over `\\RR`\n - ``'complex'`` or an object of type ``ComplexField`` (e.g., ``CC``)\n for a manifold over `\\CC`\n - an object in the category of topological fields (see\n :class:`~sage.categories.fields.Fields` and\n :class:`~sage.categories.topological_spaces.TopologicalSpaces`)\n for other types of manifolds\n\n - ``structure`` -- manifold structure (see\n :class:`~sage.manifolds.structure.TopologicalStructure` or\n :class:`~sage.manifolds.structure.RealTopologicalStructure`)\n - ``ambient`` -- (default: ``None``) codomain `M` of the immersion `\\phi`;\n must be a topological manifold. If ``None``, it is set to ``self``\n - ``base_manifold`` -- (default: ``None``) if not ``None``, must be a\n topological manifold; the created object is then an open subset of\n ``base_manifold``\n - ``latex_name`` -- (default: ``None``) string; LaTeX symbol to\n denote the submanifold; if none are provided, it is set to ``name``\n - ``start_index`` -- (default: 0) integer; lower value of the range of\n indices used for \"indexed objects\" on the submanifold, e.g., coordinates\n in a chart\n - ``category`` -- (default: ``None``) to specify the category; if\n ``None``, ``Manifolds(field)`` is assumed (see the category\n :class:`~sage.categories.manifolds.Manifolds`)\n - ``unique_tag`` -- (default: ``None``) tag used to force the construction\n of a new object when all the other arguments have been used previously\n (without ``unique_tag``, the\n :class:`~sage.structure.unique_representation.UniqueRepresentation`\n behavior inherited from\n :class:`~sage.manifolds.subset.ManifoldSubset` via\n :class:`~sage.manifolds.manifold.TopologicalManifold`\n would return the previously constructed object corresponding to these\n arguments)\n\n EXAMPLES:\n\n Let `N` be a 2-dimensional submanifold of a 3-dimensional manifold `M`::\n\n sage: M = Manifold(3, 'M', structure=\"topological\")\n sage: N = Manifold(2, 'N', ambient=M, structure=\"topological\")\n sage: N\n 2-dimensional topological submanifold N immersed in the 3-dimensional\n topological manifold M\n sage: CM. = M.chart()\n sage: CN. = N.chart()\n\n Let us define a 1-dimensional foliation indexed by `t`::\n\n sage: t = var('t')\n sage: phi = N.continuous_map(M, {(CN,CM): [u, v, t+u^2+v^2]})\n sage: phi.display()\n N → M\n (u, v) ↦ (x, y, z) = (u, v, u^2 + v^2 + t)\n\n The foliation inverse maps are needed for computing the adapted chart on\n the ambient manifold::\n\n sage: phi_inv = M.continuous_map(N, {(CM, CN): [x, y]})\n sage: phi_inv.display()\n M → N\n (x, y, z) ↦ (u, v) = (x, y)\n sage: phi_inv_t = M.scalar_field({CM: z-x^2-y^2})\n sage: phi_inv_t.display()\n M → ℝ\n (x, y, z) ↦ -x^2 - y^2 + z\n\n `\\phi` can then be declared as an embedding `N\\to M`::\n\n sage: N.set_embedding(phi, inverse=phi_inv, var=t,\n ....: t_inverse={t: phi_inv_t})\n\n The foliation can also be used to find new charts on the ambient manifold\n that are adapted to the foliation, i.e. in which the expression of the\n immersion is trivial. At the same time, the appropriate coordinate changes\n are computed::\n\n sage: N.adapted_chart()\n [Chart (M, (u_M, v_M, t_M))]\n sage: M.atlas()\n [Chart (M, (x, y, z)), Chart (M, (u_M, v_M, t_M))]\n sage: len(M.coord_changes())\n 2\n\n The foliation parameters are always added as the last coordinates.\n\n .. SEEALSO::\n\n :mod:`~sage.manifolds.manifold`\n\n \"\"\"\n def __init__(self, n, name, field, structure, ambient=None,\n base_manifold=None, latex_name=None, start_index=0,\n category=None, unique_tag=None):\n r\"\"\"\n Construct a submanifold of a topological manifold.\n\n TESTS::\n\n sage: M = Manifold(3, 'M', structure=\"topological\")\n sage: N = Manifold(2, 'N', ambient=M, structure=\"topological\")\n sage: N\n 2-dimensional topological submanifold N immersed in the\n 3-dimensional topological manifold M\n\n \"\"\"\n TopologicalManifold.__init__(self, n, name, field, structure,\n base_manifold=base_manifold,\n latex_name=latex_name,\n start_index=start_index,\n category=category)\n if not (ambient is None\n or isinstance(ambient, TopologicalManifold)):\n raise TypeError(\"ambient must be a manifold\")\n self._init_immersion(ambient=ambient)\n\n def _init_immersion(self, ambient=None):\n r\"\"\"\n Initialize the attributes relative to the immersion of ``self`` in\n the ambient manifold.\n\n INPUT:\n\n - ``ambient`` -- (default: ``None``) codomain of the immersion;\n must be a topological manifold. If ``None``, it is set to ``self``\n\n TESTS::\n\n sage: M = Manifold(2, 'M', structure='topological')\n sage: N = Manifold(1, 'N', ambient=M, structure='topological')\n sage: N._init_immersion(ambient=M)\n\n \"\"\"\n self._immersion = None\n self._immersion_inv = None\n self._var = None\n self._dim_foliation = 0\n self._t_inverse = {}\n if ambient is None:\n self._ambient = self\n else:\n self._ambient = ambient\n self._codim = ambient._dim - self._dim\n if self._codim < 0:\n raise ValueError(\"the submanifold must be of smaller \"\n + \"dimension than its ambient manifold\")\n self._immersed = False\n self._embedded = False\n self._adapted_charts = None\n self._subs = None\n\n def _repr_(self):\n r\"\"\"\n Return a string representation of the submanifold.\n\n If no ambient manifold is specified, the submanifold is considered as\n a manifold.\n\n TESTS::\n\n sage: M = Manifold(3, 'M', structure=\"topological\")\n sage: N = Manifold(2, 'N', ambient=M, structure=\"topological\")\n sage: N\n 2-dimensional topological submanifold N immersed in the\n 3-dimensional topological manifold M\n sage: phi = N.continuous_map(M)\n sage: N.set_embedding(phi)\n sage: N\n 2-dimensional topological submanifold N embedded in the\n 3-dimensional topological manifold M\n\n \"\"\"\n if self is not self._manifold:\n return \"Open subset {} of the {}\".format(self._name, self._manifold)\n if self._ambient is self:\n return super(TopologicalManifold, self).__repr__()\n if self._embedded:\n return \"{}-dimensional {} submanifold {} embedded in the {}\".format(\n self._dim, self._structure.name, self._name, self._ambient)\n return \"{}-dimensional {} submanifold {} immersed in the {}\".format(\n self._dim, self._structure.name, self._name, self._ambient)\n\n def open_subset(self, name, latex_name=None, coord_def={}, supersets=None):\n r\"\"\"\n Create an open subset of the manifold.\n\n An open subset is a set that is (i) included in the manifold and (ii)\n open with respect to the manifold's topology. It is a topological\n manifold by itself.\n\n As ``self`` is a submanifold of its ambient manifold,\n the new open subset is also considered a submanifold of that.\n Hence the returned object is an instance of\n :class:`TopologicalSubmanifold`.\n\n INPUT:\n\n - ``name`` -- name given to the open subset\n - ``latex_name`` -- (default: ``None``) LaTeX symbol to denote\n the subset; if none are provided, it is set to ``name``\n - ``coord_def`` -- (default: {}) definition of the subset in\n terms of coordinates; ``coord_def`` must a be dictionary with keys\n charts on the manifold and values the symbolic expressions formed\n by the coordinates to define the subset\n - ``supersets`` -- (default: only ``self``) list of sets that the\n new open subset is a subset of\n\n OUTPUT:\n\n - the open subset, as an instance of :class:`TopologicalSubmanifold`\n\n EXAMPLES::\n\n sage: M = Manifold(3, 'M', structure=\"topological\")\n sage: N = Manifold(2, 'N', ambient=M, structure=\"topological\"); N\n 2-dimensional topological submanifold N immersed in the\n 3-dimensional topological manifold M\n sage: S = N.subset('S'); S\n Subset S of the\n 2-dimensional topological submanifold N immersed in the\n 3-dimensional topological manifold M\n sage: O = N.subset('O', is_open=True); O # indirect doctest\n Open subset O of the\n 2-dimensional topological submanifold N immersed in the\n 3-dimensional topological manifold M\n\n sage: phi = N.continuous_map(M)\n sage: N.set_embedding(phi)\n sage: N\n 2-dimensional topological submanifold N embedded in the\n 3-dimensional topological manifold M\n sage: S = N.subset('S'); S\n Subset S of the\n 2-dimensional topological submanifold N embedded in the\n 3-dimensional topological manifold M\n sage: O = N.subset('O', is_open=True); O # indirect doctest\n Open subset O of the\n 2-dimensional topological submanifold N embedded in the\n 3-dimensional topological manifold M\n\n \"\"\"\n resu = TopologicalSubmanifold(self._dim, name, self._field,\n self._structure, self._ambient,\n base_manifold=self._manifold,\n latex_name=latex_name,\n start_index=self._sindex)\n if supersets is None:\n supersets = [self]\n for superset in supersets:\n superset._init_open_subset(resu, coord_def=coord_def)\n return resu\n\n def _init_open_subset(self, resu, coord_def):\n r\"\"\"\n Initialize ``resu`` as an open subset of ``self``.\n\n INPUT:\n\n - ``resu`` -- an instance of :class:`TopologicalManifold` or\n a subclass.\n\n - ``coord_def`` -- (default: ``{}``) definition of the subset in\n terms of coordinates; ``coord_def`` must a be dictionary with keys\n charts on the manifold and values the symbolic expressions formed\n by the coordinates to define the subset\n\n EXAMPLES::\n\n sage: M = Manifold(3, 'M', structure=\"topological\")\n sage: N = Manifold(2, 'N', ambient=M, structure=\"topological\")\n sage: phi = N.continuous_map(M)\n sage: N.set_embedding(phi)\n sage: N\n 2-dimensional topological submanifold N embedded in the\n 3-dimensional topological manifold M\n sage: from sage.manifolds.topological_submanifold import TopologicalSubmanifold\n sage: O = TopologicalSubmanifold(3, 'O', field=M._field, structure=M._structure,\n ....: ambient=M, base_manifold=N)\n sage: N._init_open_subset(O, {})\n sage: O\n Open subset O of the\n 2-dimensional topological submanifold N embedded in the\n 3-dimensional topological manifold M\n sage: O.embedding()\n Continuous map\n from the Open subset O of the 2-dimensional topological submanifold N\n embedded in the 3-dimensional topological manifold M\n to the 3-dimensional topological manifold M\n \"\"\"\n super()._init_open_subset(resu, coord_def=coord_def)\n ## Extras for Submanifold\n if self._immersed:\n resu.set_immersion(self._immersion.restrict(resu),\n var=self._var, t_inverse=self._t_inverse)\n if self._embedded:\n resu.declare_embedding()\n\n def set_immersion(self, phi, inverse=None, var=None,\n t_inverse=None):\n r\"\"\"\n Register the immersion of the immersed submanifold.\n\n A *topological immersion* is a continuous map that is locally a\n topological embedding (i.e. a homeomorphism onto its image).\n A *differentiable immersion* is a differentiable map whose differential\n is injective at each point.\n\n If an inverse of the immersion onto its image exists, it can be\n registered at the same time. If the immersion depends on parameters,\n they must also be declared here.\n\n INPUT:\n\n - ``phi`` -- continuous map `\\phi` from ``self`` to ``self.ambient()``\n - ``inverse`` -- (default: ``None``) continuous map from\n ``self.ambient()`` to ``self``, which once restricted to the image\n of `\\phi` is the inverse of `\\phi` onto its image if the latter\n exists (NB: no check of this is performed)\n - ``var`` -- (default: ``None``) list of parameters involved in the\n definition of `\\phi` (case of foliation); if `\\phi` depends on a\n single parameter ``t``, one can write ``var=t`` as a shortcut for\n ``var=[t]``\n - ``t_inverse`` -- (default: ``None``) dictionary of scalar fields on\n ``self.ambient()`` providing the values of the parameters involved\n in the definition of `\\phi` (case of foliation), the keys being\n the parameters\n\n EXAMPLES::\n\n sage: M = Manifold(3, 'M', structure=\"topological\")\n sage: N = Manifold(2, 'N', ambient=M, structure=\"topological\")\n sage: N\n 2-dimensional topological submanifold N immersed in the\n 3-dimensional topological manifold M\n sage: CM. = M.chart()\n sage: CN. = N.chart()\n sage: t = var('t')\n sage: phi = N.continuous_map(M, {(CN,CM): [u,v,t+u^2+v^2]})\n sage: phi.display()\n N → M\n (u, v) ↦ (x, y, z) = (u, v, u^2 + v^2 + t)\n sage: phi_inv = M.continuous_map(N, {(CM,CN): [x,y]})\n sage: phi_inv.display()\n M → N\n (x, y, z) ↦ (u, v) = (x, y)\n sage: phi_inv_t = M.scalar_field({CM: z-x^2-y^2})\n sage: phi_inv_t.display()\n M → ℝ\n (x, y, z) ↦ -x^2 - y^2 + z\n sage: N.set_immersion(phi, inverse=phi_inv, var=t,\n ....: t_inverse={t: phi_inv_t})\n\n \"\"\"\n if not isinstance(phi, ContinuousMap):\n raise TypeError(\"the argument phi must be a continuous map\")\n if phi.domain() is not self or phi.codomain() is not self._ambient:\n raise ValueError(\"{} is not a map from {} to {}\".format(phi, self,\n self._ambient))\n self._immersion = phi\n\n if inverse is not None:\n self._immersion._inverse = inverse\n self._immersion_inv = inverse\n\n if var is not None:\n try:\n iter(var)\n for v in var:\n if not isinstance(v, Expression):\n raise TypeError()\n except TypeError:\n if not isinstance(var, Expression):\n raise TypeError(\"var must be a variable \"\n \"or list of variables\")\n\n if isinstance(var, Expression):\n self._var = [var]\n self._dim_foliation = 1\n else:\n self._var = var\n self._dim_foliation = len(var)\n if t_inverse is None:\n t_inverse = {}\n\n self._t_inverse = t_inverse\n self._immersed = True\n\n def declare_embedding(self):\n r\"\"\"\n Declare that the immersion provided by :meth:`set_immersion` is in\n fact an embedding.\n\n A *topological embedding* is a continuous map that is a homeomorphism\n onto its image. A *differentiable embedding* is a topological embedding\n that is also a differentiable immersion.\n\n EXAMPLES::\n\n sage: M = Manifold(3, 'M', structure=\"topological\")\n sage: N = Manifold(2, 'N', ambient=M, structure=\"topological\")\n sage: N\n 2-dimensional topological submanifold N immersed in the\n 3-dimensional topological manifold M\n sage: CM. = M.chart()\n sage: CN. = N.chart()\n sage: t = var('t')\n sage: phi = N.continuous_map(M, {(CN,CM): [u,v,t+u^2+v^2]})\n sage: phi_inv = M.continuous_map(N, {(CM,CN): [x,y]})\n sage: phi_inv_t = M.scalar_field({CM: z-x^2-y^2})\n sage: N.set_immersion(phi, inverse=phi_inv, var=t,\n ....: t_inverse={t: phi_inv_t})\n sage: N._immersed\n True\n sage: N._embedded\n False\n sage: N.declare_embedding()\n sage: N._immersed\n True\n sage: N._embedded\n True\n\n \"\"\"\n if not self._immersed:\n raise ValueError(\"please declare an embedding using set_immersion \"\n \"before calling declare_embedding()\")\n self._embedded = True\n\n def set_embedding(\n self, phi: ContinuousMap, inverse=None, var=None, t_inverse=None\n ):\n r\"\"\"\n Register the embedding of an embedded submanifold.\n\n A *topological embedding* is a continuous map that is a homeomorphism\n onto its image. A *differentiable embedding* is a topological embedding\n that is also a differentiable immersion.\n\n INPUT:\n\n - ``phi`` -- continuous map `\\phi` from ``self`` to ``self.ambient()``\n - ``inverse`` -- (default: ``None``) continuous map from\n ``self.ambient()`` to ``self``, which once restricted to the image\n of `\\phi` is the inverse of `\\phi` onto its image (NB: no check of\n this is performed)\n - ``var`` -- (default: ``None``) list of parameters involved in the\n definition of `\\phi` (case of foliation); if `\\phi` depends on a\n single parameter ``t``, one can write ``var=t`` as a shortcut for\n ``var=[t]``\n - ``t_inverse`` -- (default: ``None``) dictionary of scalar fields on\n ``self.ambient()`` providing the values of the parameters involved\n in the definition of `\\phi` (case of foliation), the keys being\n the parameters\n\n EXAMPLES::\n\n sage: M = Manifold(3, 'M', structure=\"topological\")\n sage: N = Manifold(2, 'N', ambient=M, structure=\"topological\")\n sage: N\n 2-dimensional topological submanifold N immersed in the\n 3-dimensional topological manifold M\n sage: CM. = M.chart()\n sage: CN. = N.chart()\n sage: t = var('t')\n sage: phi = N.continuous_map(M, {(CN,CM): [u,v,t+u^2+v^2]})\n sage: phi.display()\n N → M\n (u, v) ↦ (x, y, z) = (u, v, u^2 + v^2 + t)\n sage: phi_inv = M.continuous_map(N, {(CM,CN): [x,y]})\n sage: phi_inv.display()\n M → N\n (x, y, z) ↦ (u, v) = (x, y)\n sage: phi_inv_t = M.scalar_field({CM: z-x^2-y^2})\n sage: phi_inv_t.display()\n M → ℝ\n (x, y, z) ↦ -x^2 - y^2 + z\n sage: N.set_embedding(phi, inverse=phi_inv, var=t,\n ....: t_inverse={t: phi_inv_t})\n\n Now ``N`` appears as an embedded submanifold::\n\n sage: N\n 2-dimensional topological submanifold N embedded in the\n 3-dimensional topological manifold M\n\n \"\"\"\n self.set_immersion(phi, inverse, var, t_inverse)\n self.declare_embedding()\n\n def adapted_chart(self, postscript=None, latex_postscript=None):\n r\"\"\"\n Create charts and changes of charts in the ambient manifold adapted\n to the foliation.\n\n A manifold `M` of dimension `m` can be foliated by submanifolds `N` of\n dimension `n`. The corresponding embedding needs `m-n` free parameters\n to describe the whole manifold.\n\n A chart adapted to the foliation is a set of coordinates\n `(x_1,\\ldots,x_n,t_1,\\ldots,t_{m-n})` on `M` such that\n `(x_1,\\ldots,x_n)` are coordinates on `N` and `(t_1,\\ldots,t_{m-n})`\n are the `m-n` free parameters of the foliation.\n\n Provided that an embedding with free variables is already defined, this\n function constructs such charts and coordinates changes whenever\n it is possible.\n\n If there are restrictions of the coordinates on the starting chart,\n these restrictions are also propagated.\n\n INPUT:\n\n - ``postscript`` -- (default: ``None``) string defining the name of the\n coordinates of the adapted chart. This string will be appended to\n the names of the coordinates `(x_1,\\ldots,x_n)` and of the parameters\n `(t_1,\\ldots,t_{m-n})`. If ``None``, ``\"_\" + self.ambient()._name``\n is used\n - ``latex_postscript`` -- (default: ``None``) string defining the LaTeX\n name of the coordinates of the adapted chart. This string will be\n appended to the LaTeX names of the coordinates `(x_1,\\ldots,x_n)` and\n of the parameters `(t_1,\\ldots,t_{m-n})`, If ``None``,\n ``\"_\" + self.ambient()._latex_()`` is used\n\n OUTPUT:\n\n - list of adapted charts on `M` created from the charts of ``self``\n\n EXAMPLES::\n\n sage: M = Manifold(3, 'M', structure=\"topological\",\n ....: latex_name=r\"\\mathcal{M}\")\n sage: N = Manifold(2, 'N', ambient=M, structure=\"topological\")\n sage: N\n 2-dimensional topological submanifold N immersed in the\n 3-dimensional topological manifold M\n sage: CM. = M.chart()\n sage: CN. = N.chart()\n sage: t = var('t')\n sage: phi = N.continuous_map(M, {(CN,CM): [u,v,t+u^2+v^2]})\n sage: phi_inv = M.continuous_map(N, {(CM,CN): [x,y]})\n sage: phi_inv_t = M.scalar_field({CM: z-x^2-y^2})\n sage: N.set_embedding(phi, inverse=phi_inv, var=t,\n ....: t_inverse={t:phi_inv_t})\n sage: N.adapted_chart()\n [Chart (M, (u_M, v_M, t_M))]\n sage: latex(_)\n \\left[\\left(\\mathcal{M},({{u}_{\\mathcal{M}}}, {{v}_{\\mathcal{M}}},\n {{t}_{\\mathcal{M}}})\\right)\\right]\n\n The adapted chart has been added to the atlas of ``M``::\n\n sage: M.atlas()\n [Chart (M, (x, y, z)), Chart (M, (u_M, v_M, t_M))]\n sage: N.atlas()\n [Chart (N, (u, v))]\n\n The names of the adapted coordinates can be customized::\n\n sage: N.adapted_chart(postscript='1', latex_postscript='_1')\n [Chart (M, (u1, v1, t1))]\n sage: latex(_)\n \\left[\\left(\\mathcal{M},({{u}_1}, {{v}_1}, {{t}_1})\\right)\\right]\n\n \"\"\"\n if not self._embedded:\n raise ValueError(\"an embedding is required\")\n\n if self._dim_foliation + self._dim != self._ambient._dim:\n raise ValueError(\"a foliation of dimension dim(M) - dim(N) is \"\n \"needed to find an adapted chart\")\n res = []\n self._subs = []\n\n if postscript is None:\n postscript = \"_\" + self._ambient._name.replace(\"^\", \"\")\n # NB: \"^\" is deleted from the name of ambient to get valid\n # Python identifiers for the symbolic variables representing the\n # coordinates\n if latex_postscript is None:\n latex_postscript = \"_{\" + self._ambient._latex_() + \"}\"\n\n # All possible expressions for the immersion\n chart_pairs = list(self._immersion._coord_expression.keys())\n for (chart1, chart2) in chart_pairs:\n name = \" \".join(chart1[i]._repr_() + postscript + \":{\"\n + chart1[i]._latex_() + \"}\" + latex_postscript\n for i in self.irange()) + \" \" \\\n + \" \".join(v._repr_() + postscript + \":{\" + v._latex_()\n + \"}\" + latex_postscript for v in self._var)\n chart = chart2.domain().chart(name)\n if chart not in res:\n\n # Construct restrictions on coordinates:\n subs = {chart1[:][i]: chart[:][i] for i in range(self._dim)}\n # NB: chart1[:][i] is used instead of chart1[i] to allow for\n # start_index != 0\n for i in range(len(self._var)):\n subs[self._var[i]] = chart[:][self._dim + i]\n for rest in chart1._restrictions:\n chart.add_restrictions(rest.subs(subs))\n for _a in assumptions(*(chart1[:] + tuple(self._var))):\n if isinstance(_a, Expression):\n assume(_a.subs(subs))\n\n self._subs.append(subs)\n res.append(chart)\n self._immersion.add_expr(chart1, chart,\n list(chart1[:]) + self._var)\n self._immersion_inv.add_expr(chart, chart1,\n chart[:][0:self._dim])\n for i in range(len(self._var)):\n self._t_inverse[self._var[i]].add_expr(\n chart[:][self._dim:][i], chart=chart)\n\n for (chartNV, chartMV) in self._immersion._coord_expression:\n for (chartNU, chartMU) in self._immersion._coord_expression:\n if chartMU is not chartMV and\\\n (chartMU, chartMV) not in self._ambient._coord_changes:\n if (chartNU, chartNV) in self._coord_changes or \\\n chartNU is chartNV:\n _f = self._immersion.coord_functions(chartNV, chartMV)\n _g = self._coord_changes[(chartNU, chartNV)]._transf \\\n if chartNU is not chartNV else lambda *x: x\n _h = self._immersion_inv.coord_functions(chartMU,\n chartNU)\n expr = list(_f(*_g(*_h(*chartMU[:]))))\n substitutions = {v: self._t_inverse[v].expr(chartMU)\n for v in self._var}\n for i in range(len(expr)):\n expr[i] = expr[i].subs(substitutions)\n\n chartMU.transition_map(chartMV, expr)\n self._adapted_charts = res\n return res\n\n def plot(self, param, u, v, chart1=None, chart2=None, **kwargs):\n r\"\"\"\n Plot an embedding.\n\n Plot the embedding defined by the foliation and a set of values for the\n free parameters. This function can only plot 2-dimensional surfaces\n embedded in 3-dimensional manifolds. It ultimately calls\n :class:`~sage.plot.plot3d.parametric_surface.ParametricSurface`.\n\n INPUT:\n\n - ``param`` -- dictionary of values indexed by the free variables\n appearing in the foliation.\n - ``u`` -- iterable of the values taken by the first coordinate of the\n surface to plot\n - ``v`` -- iterable of the values taken by the second coordinate of the\n surface to plot\n - ``chart1`` -- (default: ``None``) chart in which ``u`` and ``v`` are\n considered. By default, the default chart of the submanifold is used\n - ``chart2`` -- (default: ``None``) chart in the codomain of the\n embedding. By default, the default chart of the codomain is used\n - ``**kwargs`` -- other arguments as used in\n :class:`~sage.plot.plot3d.parametric_surface.ParametricSurface`\n\n EXAMPLES::\n\n sage: M = Manifold(3, 'M', structure=\"topological\")\n sage: N = Manifold(2, 'N', ambient = M, structure=\"topological\")\n sage: CM. = M.chart()\n sage: CN. = N.chart()\n sage: t = var('t')\n sage: phi = N.continuous_map(M, {(CN,CM): [u,v,t+u^2+v^2]})\n sage: phi_inv = M.continuous_map(N, {(CM,CN): [x,y]})\n sage: phi_inv_t = M.scalar_field({CM: z-x^2-y^2})\n sage: N.set_embedding(phi, inverse=phi_inv, var=t,\n ....: t_inverse = {t:phi_inv_t})\n sage: N.adapted_chart()\n [Chart (M, (u_M, v_M, t_M))]\n sage: P0 = N.plot({t:0}, srange(-1, 1, 0.1), srange(-1, 1, 0.1),\n ....: CN, CM, opacity=0.3, mesh=True)\n sage: P1 = N.plot({t:1}, srange(-1, 1, 0.1), srange(-1, 1, 0.1),\n ....: CN, CM, opacity=0.3, mesh=True)\n sage: P2 = N.plot({t:2}, srange(-1, 1, 0.1), srange(-1, 1, 0.1),\n ....: CN, CM, opacity=0.3, mesh=True)\n sage: P3 = N.plot({t:3}, srange(-1, 1, 0.1), srange(-1, 1, 0.1),\n ....: CN, CM, opacity=0.3, mesh=True)\n sage: P0 + P1 + P2 + P3\n Graphics3d Object\n\n .. PLOT::\n\n M = Manifold(3, 'M', structure=\"topological\")\n N = Manifold(2, 'N', ambient = M, structure=\"topological\")\n CM = M.chart('x y z'); x, y, z = CM[:]\n CN = N.chart('u v'); u, v = CN[:]\n t = var('t')\n phi = N.continuous_map(M, {(CN,CM): [u,v,t+u**2+v**2]})\n phi_inv = M.continuous_map(N, {(CM,CN): [x,y]})\n phi_inv_t = M.scalar_field({CM: z-x**2-y**2})\n N.set_embedding(phi, inverse=phi_inv, var=t,\n t_inverse = {t:phi_inv_t})\n N.adapted_chart()\n P0 = N.plot({t:0}, srange(-1, 1, 0.1), srange(-1, 1, 0.1),\n CN, CM, opacity=0.3, mesh=True)\n P1 = N.plot({t:1}, srange(-1, 1, 0.1), srange(-1, 1, 0.1),\n CN, CM, opacity=0.3, mesh=True)\n P2 = N.plot({t:2}, srange(-1, 1, 0.1), srange(-1, 1, 0.1),\n CN, CM, opacity=0.3, mesh=True)\n P3 = N.plot({t:3}, srange(-1, 1, 0.1), srange(-1, 1, 0.1),\n CN, CM, opacity=0.3, mesh=True)\n sphinx_plot(P0 + P1 + P2 + P3)\n\n .. SEEALSO::\n\n :class:`~sage.plot.plot3d.parametric_surface.ParametricSurface`\n\n \"\"\"\n\n if self._dim != 2 or self._ambient._dim != 3:\n raise ValueError(\"plot only for 2-dimensional hypersurfaces\")\n if chart1 is None:\n chart1 = self.default_chart()\n if chart2 is None:\n chart2 = self._ambient.default_chart()\n expr = list(self._immersion.coord_functions(chart1, chart2))\n for i in range(len(expr)):\n expr[i] = expr[i].expr().subs(param)\n fx = expr[0].function(*chart1[:])\n fy = expr[1].function(*chart1[:])\n fz = expr[2].function(*chart1[:])\n\n return ParametricSurface((fx, fy, fz), (u, v), **kwargs)\n\n def ambient(self) -> TopologicalManifold:\n r\"\"\"\n Return the manifold in which ``self`` is immersed or embedded.\n\n EXAMPLES::\n\n sage: M = Manifold(3, 'M', structure=\"topological\")\n sage: N = Manifold(2, 'N', ambient=M, structure=\"topological\")\n sage: N.ambient()\n 3-dimensional topological manifold M\n \"\"\"\n return self._ambient\n\n def immersion(self) -> ContinuousMap:\n r\"\"\"\n Return the immersion of ``self`` into the ambient manifold.\n\n EXAMPLES::\n\n sage: M = Manifold(3, 'M', structure=\"topological\")\n sage: N = Manifold(2, 'N', ambient=M, structure=\"topological\")\n sage: CM. = M.chart()\n sage: CN. = N.chart()\n sage: t = var('t')\n sage: phi = N.continuous_map(M, {(CN,CM): [u,v,t+u^2+v^2]})\n sage: phi_inv = M.continuous_map(N, {(CM,CN): [x,y]})\n sage: phi_inv_t = M.scalar_field({CM: z-x^2-y^2})\n sage: N.set_immersion(phi, inverse=phi_inv, var=t,\n ....: t_inverse={t: phi_inv_t})\n sage: N.immersion()\n Continuous map from the 2-dimensional topological submanifold N\n immersed in the 3-dimensional topological manifold M to the\n 3-dimensional topological manifold M\n\n \"\"\"\n if not self._immersed:\n raise ValueError(\"the submanifold is not immersed\")\n assert self._immersion\n return self._immersion\n\n def embedding(self) -> ContinuousMap:\n r\"\"\"\n Return the embedding of ``self`` into the ambient manifold.\n\n EXAMPLES::\n\n sage: M = Manifold(3, 'M', structure=\"topological\")\n sage: N = Manifold(2, 'N', ambient=M, structure=\"topological\")\n sage: CM. = M.chart()\n sage: CN. = N.chart()\n sage: t = var('t')\n sage: phi = N.continuous_map(M, {(CN,CM): [u,v,t+u^2+v^2]})\n sage: phi_inv = M.continuous_map(N, {(CM,CN): [x,y]})\n sage: phi_inv_t = M.scalar_field({CM: z-x^2-y^2})\n sage: N.set_embedding(phi, inverse=phi_inv, var=t,\n ....: t_inverse={t: phi_inv_t})\n sage: N.embedding()\n Continuous map from the 2-dimensional topological submanifold N\n embedded in the 3-dimensional topological manifold M to the\n 3-dimensional topological manifold M\n\n \"\"\"\n if not self._embedded:\n raise ValueError(\"the submanifold is not embedded\")\n assert self._immersion\n return self._immersion\n\n def as_subset(self):\n r\"\"\"\n Return ``self`` as a subset of the ambient manifold.\n\n ``self`` must be an embedded submanifold.\n\n EXAMPLES::\n\n sage: M = Manifold(2, 'M', structure=\"topological\")\n sage: N = Manifold(1, 'N', ambient=M, structure=\"topological\")\n sage: CM. = M.chart()\n sage: CN. = N.chart(coord_restrictions=lambda u: [u > -1, u < 1])\n sage: phi = N.continuous_map(M, {(CN,CM): [u, u^2]})\n sage: N.set_embedding(phi)\n sage: N\n 1-dimensional topological submanifold N\n embedded in the 2-dimensional topological manifold M\n sage: N.as_subset()\n Image of the Continuous map\n from the 1-dimensional topological submanifold N\n embedded in the 2-dimensional topological manifold M\n to the 2-dimensional topological manifold M\n\n \"\"\"\n return self.embedding().image()\n","repo_name":"sagemath/sage-archive-2023-02-01","sub_path":"src/sage/manifolds/topological_submanifold.py","file_name":"topological_submanifold.py","file_ext":"py","file_size_in_byte":38812,"program_lang":"python","lang":"en","doc_type":"code","stars":2037,"dataset":"github-code","pt":"40"} +{"seq_id":"25774607146","text":"import numpy as np\n\nfrom gen_rand_centroids import gen_rand_centroids\nfrom label import label\n\n\ndef k_means(dataset, k, features, center_range, scale):\n\n # K-means initialization\n\n centroids = gen_rand_centroids(k=k, features=features, center_range=center_range, scale=scale) # Generates k random centroids\n\n labeled_dataset = label(dataset, centroids, k, features)\n\n # K-means main loop\n\n points_in_cluster = np.zeros(k) # Total number of points in each cluster (after classification)\n features_sum = np.zeros((k, features)) # Partial sum of each feature, calculated for each cluster\n\n while True:\n\n prev_centroids = centroids # Keeps track of the previous centroids, enabling breaking the loop\n\n for i in range(0, len(labeled_dataset)): # Computes the centroid for each cluster\n points_in_cluster[int(labeled_dataset.loc[i, features])] += 1 # Counts the number of points in each cluster\n for j in range(0, features): # Sums the features of each point, for each cluster\n features_sum[int(labeled_dataset.loc[i, features]), j] += labeled_dataset.loc[i, j]\n\n for i in range(0, k): # For each cluster, calculates the new centroid\n for j in range(0, features):\n if points_in_cluster[i] == 0: # Avoids runtime warnings because of divisions by zero\n pass\n else:\n centroids[i, j] = features_sum[i, j] / points_in_cluster[i]\n\n labeled_dataset = label(labeled_dataset.drop(columns=[features]), centroids, k, features) # Re-assigns the points in function of the new centroids\n\n if (centroids == prev_centroids).all(): # Breaks the loop if centroids are not moving anymore\n break\n\n return labeled_dataset, centroids\n","repo_name":"PaulaMihalcea/Multistart-k-means","sub_path":"k_means.py","file_name":"k_means.py","file_ext":"py","file_size_in_byte":1803,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"40"} +{"seq_id":"18455819170","text":"import argparse\nimport os\n\nimport netCDF4\nimport numpy as np\nfrom helper.mds import mds\nimport time as t\nfrom helper.pearson import pearson_corr_distance_matrix\nimport logging\n\nENSEMBLE = \"../artificialData/\" # Path to ensemble data\nOUT = \"../tmp\" # Path to store temporary data\nVARIABLE_NAME = 'data' # Name of the field in the nc file\n\nlogging.basicConfig(filename=OUT+'/full.log', level=logging.DEBUG)\n# Load Data\ndata = np.empty((0,0))\ni = 0\nnumberOfRuns = len(os.listdir(ENSEMBLE))\nfor run in os.listdir(ENSEMBLE):\n print(\"Loading run %s (%i)\"%(run, (100.0*i)/numberOfRuns))\n path = os.path.join(os.path.join(ENSEMBLE, run), os.listdir(os.path.join(ENSEMBLE, run))[0])\n f = netCDF4.Dataset(path)\n timelines = f.variables[VARIABLE_NAME]\n timelines = np.transpose(timelines, axes=[1, 2, 0])\n timelines = timelines.reshape((timelines.shape[0] * timelines.shape[1], timelines.shape[2]))\n if(data.shape == (0,0)):\n data = timelines\n else:\n data = np.append(data, timelines, axis=1)\n f.close()\n i=i+1\n# Distance matrix\nstart_time = t.time()\ndistance_matrix = pearson_corr_distance_matrix(timelines=data, lag=0)\nnp.save(OUT+'/corr_full.npy', distance_matrix)\ndistance_matrix = -(distance_matrix+1)*0.5+1\n\nprint('... calculated full correlation in %s seconds' % (t.time() - start_time))\nlogging.debug('calculated correlation in %s seconds' % (t.time() - start_time))\n\nY, eigens = mds(distance_matrix, dimensions=3)\nnp.save(OUT+'/y_full.npy', Y)\nnp.save(OUT+'/eigens_full.npy', eigens)\n\nprint('... calculated mds in %s seconds' % (t.time() - start_time))\nlogging.debug('calculated mds in %s seconds' % (t.time() - start_time))\n","repo_name":"marinaevers/regional-correlations","sub_path":"backend/create_correlation_mds.py","file_name":"create_correlation_mds.py","file_ext":"py","file_size_in_byte":1667,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"40"} +{"seq_id":"40024123566","text":"# Нужно реализовать класс StackMax, который поддерживает операцию\n# определения максимума среди всех элементов в стеке. Класс также должен\n# поддерживать все операции, реализованные в классе Stack, из урока. При\n# этом в классе StackMax может быть реализовано не более трёх методов. Стек\n# может содержать только данные типов, поддерживающих операцию сравнения.\n# Иначе операция поиска максимума будет некорректной.\n\n\nclass StackMaxEffective:\n def __init__(self):\n self.items = []\n self.max = None\n\n def is_empty(self):\n return self.items == []\n\n def push(self, item):\n if self.is_empty():\n self.max = item\n self.items.append(item)\n elif item > self.max:\n\n # если item > self.max, то\n # item - self.max > 0, тогда прибавив item к обеим частям\n # неравенства получим\n # item - self.max + item > item, тогда получаем\n # 2 * item - self.max > item\n # то есть, вместо item мы можем смело сохранить в стеке вот эту\n # конструкцию 2 * item - self.max, которая точно больше item и\n # связывает текущий максимум и значение.\n\n tmp = 2 * item - self.max\n self.items.append(tmp)\n self.max = item\n else:\n self.items.append(item)\n\n def pop(self):\n if self.is_empty():\n return 'error'\n if self.peek() < self.max:\n self.items.pop()\n return None\n\n # если self.max < self.peek(), тогда\n # self.max - self.peek() < 0 и, прибавив self.max к обеим частям\n # неравенства, получим\n # self.max - self.peek() + self.max < self.max, то есть,\n # previous.max = 2 * popped.max - 2 * item + previous.max\n #\n # 2 * item - previous.max\n\n # вот так и восстановим предыдущее значение self.max, когда будем\n # удалять текущий максимум\n\n self.max = 2 * self.max - self.peek()\n self.items.pop()\n return None\n\n def peek(self):\n if self.is_empty():\n return None\n return self.items[len(self.items) - 1]\n\n def size(self):\n return len(self.items)\n\n def get_max(self):\n if self.is_empty():\n return None\n return self.max\n\n\nif __name__ == '__main__':\n stack = StackMaxEffective()\n n = int(input())\n for i in range(n):\n command = input().split()\n if command[0] == 'push':\n stack.push(int(command[1]))\n elif command[0] == 'get_max':\n print(stack.get_max())\n elif command[0] == 'pop':\n if stack.pop() is not None:\n print(stack.pop())\n","repo_name":"egor-karitskiy/algorythms","sub_path":"12/12.2.I.py","file_name":"12.2.I.py","file_ext":"py","file_size_in_byte":3291,"program_lang":"python","lang":"ru","doc_type":"code","stars":0,"dataset":"github-code","pt":"40"} +{"seq_id":"33426123838","text":"def format_cems_for_messaging(mtd_units, ndr_units, ytd_units):\n return {\n 'mtd_osat': mtd_units['osat'],\n 'mtd_taste': mtd_units['taste'],\n 'mtd_speed': mtd_units['speed'],\n 'mtd_ace': mtd_units['ace'],\n 'mtd_clean': mtd_units['clean'],\n 'mtd_accuracy': mtd_units['accuracy'],\n 'mtd_surveys': mtd_units['surveys'],\n 'ndr_osat': ndr_units['osat'],\n 'ndr_taste': ndr_units['taste'],\n 'ndr_speed': ndr_units['speed'],\n 'ndr_ace': ndr_units['ace'],\n 'ndr_clean': ndr_units['clean'],\n 'ndr_accuracy': ndr_units['accuracy'],\n 'ndr_surveys': ndr_units['surveys'],\n 'ytd_osat': ytd_units['osat'],\n 'ytd_taste': ytd_units['taste'],\n 'ytd_speed': ytd_units['speed'],\n 'ytd_ace': ytd_units['ace'],\n 'ytd_clean': ytd_units['clean'],\n 'ytd_accuracy': ytd_units['accuracy'],\n 'ytd_surveys': ytd_units['surveys'],\n }","repo_name":"Phillip-England/lux","sub_path":"data/format_cems_for_messaging.py","file_name":"format_cems_for_messaging.py","file_ext":"py","file_size_in_byte":867,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"40"} +{"seq_id":"15578622135","text":"import numpy\nimport os\nimport tempfile\nfrom codebase.constants import msms_pdb2xyz, msms_exe, msms_home\n\n__author__ = 'basir'\n\n\ndef get_surface_atoms(pdb_file):\n xyz_file = pdb_file.replace(\".pdb\", \".xyzr\")\n os.chdir(msms_home)\n make_xyz_command = \"{0} {1} > {2}\".format(msms_pdb2xyz, pdb_file, xyz_file)\n os.system(make_xyz_command)\n assert os.path.isfile(xyz_file), \"Failed to generate XYZR file using command:\\n\".format(make_xyz_command)\n\n msms_output_file = pdb_file.replace(\".pdb\", \"\")\n make_vertex_file_command = \"{0} -probe_radius 1.5 -if {1} -of {2} > {3}\".format(msms_exe, xyz_file,\n msms_output_file,\n tempfile.mktemp())\n os.system(make_vertex_file_command)\n surface_file = msms_output_file + \".vert\"\n assert os.path.isfile(surface_file), \"Failed to generate surface file using command:\\n{0}\".format(\n make_vertex_file_command)\n\n with open(surface_file, \"r\") as file_pointer:\n vertex_list = []\n normal_list = []\n for line in file_pointer.readlines():\n sl = line.split()\n if not len(sl) == 9:\n # skip header\n continue\n vl = [float(x) for x in sl[0:3]]\n nl = [float(x) for x in sl[3:6]]\n vertex_list.append(vl)\n normal_list.append(nl)\n return numpy.array(vertex_list), numpy.array(normal_list)","repo_name":"basirshariat/PAIRpred","sub_path":"codebase/tools_interface/msms.py","file_name":"msms.py","file_ext":"py","file_size_in_byte":1527,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"40"} +{"seq_id":"40759827889","text":"from rest_framework.authentication import BasicAuthentication\nfrom rest_framework.viewsets import ModelViewSet\n\nfrom .models import Books, User\nfrom .permission import *\nfrom .serializers import BooksSerializer, UserSerializer\n\n\nclass UserViewSet(ModelViewSet):\n queryset = User.objects.all()\n serializer_class = UserSerializer\n authentication_classes = [BasicAuthentication]\n\n def get_permissions(self):\n permission_classes = []\n if self.action == 'create':\n permission_classes = [IsAdmin]\n elif self.action == 'list':\n permission_classes = [IsAdmin]\n elif self.action == 'retrieve' or self.action == 'update' or self.action == 'partial_update':\n permission_classes = [IsAdmin]\n elif self.action == 'destroy':\n permission_classes = [IsAdmin]\n return [permission() for permission in permission_classes]\nclass BooksViewSet(ModelViewSet):\n authentication_classes = [BasicAuthentication]\n queryset = Books.objects.all()\n serializer_class = BooksSerializer\n\n def get_permissions(self):\n permission_classes = []\n if self.action == 'create':\n permission_classes = [IsAdmin]\n elif self.action == 'list':\n permission_classes = [IsAdminOrManagerOrGuest]\n elif self.action == 'retrieve' or self.action == 'update' or self.action == 'partial_update':\n permission_classes = [IsManagerOrAdmin]\n elif self.action == 'destroy':\n permission_classes = [IsAdmin]\n return [permission() for permission in permission_classes]\n","repo_name":"Scrouly/VSRPP_lab","sub_path":"library/ISotL/views.py","file_name":"views.py","file_ext":"py","file_size_in_byte":1601,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"40"} +{"seq_id":"10714518727","text":"\n# coding: utf-8\n\n# In[1]:\n\n\nfrom pyspark import SparkContext\nsc = SparkContext.getOrCreate()\n\n\n# In[3]:\n\n\n\nimport numpy as np\n\nTOTAL = 1000000\ndots = sc.parallelize([2.0 * np.random.random(2) - 1.0 for i in range(TOTAL)]).cache()\nprint(\"Number of random points:\", dots.count())\n\nstats = dots.stats()\nprint('Mean:', stats.mean())\nprint('stdev:', stats.stdev())\n\n\n# In[4]:\n\n\nget_ipython().run_line_magic('matplotlib', 'inline')\nfrom operator import itemgetter\nfrom matplotlib import pyplot as plt\n\nplt.figure(figsize = (10, 5))\n\n# Plot 1\nplt.subplot(1, 2, 1)\nplt.xlim((-1.0, 1.0))\nplt.ylim((-1.0, 1.0))\n\nsample = dots.sample(False, 0.01)\nX = sample.map(itemgetter(0)).collect()\nY = sample.map(itemgetter(1)).collect()\nplt.scatter(X, Y)\n\n# Plot 2\nplt.subplot(1, 2, 2)\nplt.xlim((-1.0, 1.0))\nplt.ylim((-1.0, 1.0))\n\ninCircle = lambda v: np.linalg.norm(v) <= 1.0\ndotsIn = sample.filter(inCircle).cache()\ndotsOut = sample.filter(lambda v: not inCircle(v)).cache()\n\n# inside circle\nXin = dotsIn.map(itemgetter(0)).collect()\nYin = dotsIn.map(itemgetter(1)).collect()\nplt.scatter(Xin, Yin, color = 'r')\n\n# outside circle\nXout = dotsOut.map(itemgetter(0)).collect()\nYout = dotsOut.map(itemgetter(1)).collect()\nplt.scatter(Xout, Yout)\n\n","repo_name":"RoshaniG/Model-Management-Framework","sub_path":"SparkTesting.py","file_name":"SparkTesting.py","file_ext":"py","file_size_in_byte":1224,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"48"} +{"seq_id":"3725503292","text":"import numpy as np\r\n\r\ndef test_optimal(cost):\r\n m,_=np.shape(cost)\r\n \r\n ids=[]\r\n ava_ids=np.argwhere(cost[0]==0)\r\n \r\n ids.append(ava_ids[0][0])\r\n while(len(ids)>0 and len(ids)= max(pre_ids)[0]):\r\n # not optimal\r\n if(len(ids)==1):\r\n return ids\r\n ids=ids[:-1]\r\n \r\n pre_ids=np.argwhere(cost[len(ids)-1]==0)\r\n \r\n ava_ids=np.argwhere(cost[len(ids)-1]==0)\r\n #print(ava_ids)\r\n for id2 in range(len(ava_ids)):\r\n if(ava_ids[id2][0] not in ids and ava_ids[id2][0]>ids[-1]):\r\n ids[-1]=ava_ids[id2][0]\r\n find_next=True\r\n break\r\n if(find_next==False):\r\n if(len(ids)==1):\r\n return ids\r\n ids=ids[:-1]\r\n \r\n \r\n return ids\r\n \r\ndef assignment(cost):\r\n m,n=np.shape(cost)\r\n assert m>=n\r\n newcost=np.zeros((m,m))\r\n newcost[:,:n]=cost\r\n newcost=(newcost.T-np.min(newcost,1)).T\r\n \r\n newcost=newcost-np.min(newcost,0)\r\n ids=test_optimal(newcost)\r\n \r\n mask=newcost.copy()\r\n max_value=np.max(newcost)+1\r\n if(m>n):\r\n mask[:,n:] +=max_value\r\n while(len(ids)col_num):\r\n mask[id1] +=max_value\r\n if(row_numlen(np.argwhere(newcost[:,id2]==0))):\r\n mask[id1] +=max_value\r\n else:\r\n mask[:,id2] +=max_value\r\n min_value=np.min(mask)\r\n for id1 in range(m):\r\n for id2 in range(n):\r\n if(mask[id1][id2]>=2*max_value):\r\n newcost[id1][id2] +=min_value\r\n if(mask[id1][id2]